2015-10-01 23:48:33 +00:00
|
|
|
package context
|
2015-09-17 21:22:07 +00:00
|
|
|
|
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
|
|
|
|
//
|
2015-09-17 21:22:07 +00:00
|
|
|
// #include <stdlib.h>
|
|
|
|
// #include "context.h"
|
|
|
|
import "C"
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"unsafe"
|
2015-10-01 23:48:33 +00:00
|
|
|
|
2015-10-02 17:07:57 +00:00
|
|
|
"../value"
|
2015-09-17 21:22:07 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
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-09-20 00:16:43 +00:00
|
|
|
}
|
|
|
|
|
2015-10-01 23:48:33 +00:00
|
|
|
func (c *Context) Bind(name string, val interface{}) error {
|
|
|
|
v, err := value.New(val)
|
2015-09-20 00:16:43 +00:00
|
|
|
if err != nil {
|
2015-09-22 20:54:58 +00:00
|
|
|
return err
|
2015-09-20 00:16:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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-20 00:16:43 +00:00
|
|
|
}
|
|
|
|
|
2015-09-22 20:54:58 +00:00
|
|
|
c.values[name] = v
|
2015-09-20 00:16:43 +00:00
|
|
|
|
|
|
|
return nil
|
2015-09-17 21:22:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2015-09-17 21:22:07 +00:00
|
|
|
func (c *Context) Destroy() {
|
2015-09-22 20:54:58 +00:00
|
|
|
for _, v := range c.values {
|
|
|
|
v.Destroy()
|
2015-09-20 00:16:43 +00:00
|
|
|
}
|
|
|
|
|
2015-09-17 21:22:07 +00:00
|
|
|
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-09-17 21:22:07 +00:00
|
|
|
|
2015-10-01 23:48:33 +00:00
|
|
|
ptr, err := C.context_new(unsafe.Pointer(ctx))
|
2015-09-17 21:22:07 +00:00
|
|
|
if err != nil {
|
2015-10-01 23:48:33 +00:00
|
|
|
return nil, fmt.Errorf("Failed to initialize context for PHP engine")
|
2015-09-17 21:22:07 +00:00
|
|
|
}
|
|
|
|
|
2015-10-01 23:48:33 +00:00
|
|
|
ctx.context = ptr
|
|
|
|
|
|
|
|
return ctx, nil
|
2015-09-17 21:22:07 +00:00
|
|
|
}
|