1
0
mirror of https://github.com/deuill/go-php.git synced 2024-09-21 08:50:45 +00:00
go-php/context/context.go

81 lines
1.5 KiB
Go
Raw Normal View History

2015-10-01 23:48:33 +00:00
package context
2015-10-01 23:48:33 +00:00
// #cgo CFLAGS: -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM
// #cgo CFLAGS: -I/usr/include/php/Zend
// #cgo LDFLAGS: -lphp5
//
// #include <stdlib.h>
// #include "context.h"
import "C"
import (
"fmt"
"io"
"unsafe"
2015-10-01 23:48:33 +00:00
"github.com/deuill/go-php/value"
)
type Context struct {
context *C.struct__engine_context
writer io.Writer
2015-10-01 23:48:33 +00:00
values map[string]*value.Value
}
2015-10-01 23:48:33 +00:00
func (c *Context) Bind(name string, val interface{}) error {
v, err := value.New(val)
if err != nil {
2015-09-22 20:54:58 +00:00
return err
}
n := C.CString(name)
defer C.free(unsafe.Pointer(n))
2015-09-22 20:54:58 +00:00
if _, err = C.context_bind(c.context, n, v.Ptr()); err != nil {
v.Destroy()
2015-10-01 23:48:33 +00:00
return fmt.Errorf("Binding value '%v' to context failed", val)
}
2015-09-22 20:54:58 +00:00
c.values[name] = v
return nil
}
func (c *Context) Exec(filename string) error {
name := C.CString(filename)
defer C.free(unsafe.Pointer(name))
_, err := C.context_exec(c.context, name)
if err != nil {
return fmt.Errorf("Error executing script '%s' in context", filename)
}
return nil
}
2015-10-01 23:48:33 +00:00
func (c *Context) Write(p []byte) (int, error) {
return c.writer.Write(p)
}
func (c *Context) Destroy() {
2015-09-22 20:54:58 +00:00
for _, v := range c.values {
v.Destroy()
}
C.context_destroy(c.context)
c = nil
}
2015-10-01 23:48:33 +00:00
func New(w io.Writer) (*Context, error) {
ctx := &Context{writer: w, values: make(map[string]*value.Value)}
2015-10-01 23:48:33 +00:00
ptr, err := C.context_new(unsafe.Pointer(ctx))
if err != nil {
2015-10-01 23:48:33 +00:00
return nil, fmt.Errorf("Failed to initialize context for PHP engine")
}
2015-10-01 23:48:33 +00:00
ctx.context = ptr
return ctx, nil
}