Documentation
¶
Index ¶
- type Context
- type ExitError
- type ExprCache
- type IncludeCache
- type IncludeFunc
- type Options
- type Runtime
- func (rt *Runtime) ClassExists(name string, autoload bool) (bool, error)
- func (rt *Runtime) Const(name string) (any, bool)
- func (rt *Runtime) Context() context.Context
- func (rt *Runtime) DeclaredClasses() []string
- func (rt *Runtime) DefinedConstants() map[string]any
- func (rt *Runtime) DefinedFunctions() (internal, user []string)
- func (rt *Runtime) Eval(e model.Expr, scope *Scope) (any, error)
- func (rt *Runtime) Exit(code int) error
- func (rt *Runtime) FS() fs.FS
- func (rt *Runtime) IncludePath() string
- func (rt *Runtime) IncludedFiles() []string
- func (rt *Runtime) Load(src string) (*model.Program, error)
- func (rt *Runtime) LoadFile(path string) (*model.Program, error)
- func (rt *Runtime) OnError(fn func(error))
- func (rt *Runtime) PHPInfo() error
- func (rt *Runtime) RegisterAutoloader(callback any, prepend bool)
- func (rt *Runtime) RegisterClass(c *model.Class)
- func (rt *Runtime) RegisterConstructor(name string, ctor any)
- func (rt *Runtime) RegisterFunc(name string, fn any)
- func (rt *Runtime) Run(p *model.Program) error
- func (rt *Runtime) SAPI() string
- func (rt *Runtime) SPLAutoload(class string) error
- func (rt *Runtime) SetConst(name string, val any)
- func (rt *Runtime) SetContext(ctx context.Context)
- func (rt *Runtime) SetExprCache(cache *ExprCache)
- func (rt *Runtime) SetGlobal(name string, val any)
- func (rt *Runtime) SetIncludeCache(cache *IncludeCache)
- func (rt *Runtime) SetIncludePath(value string) string
- func (rt *Runtime) SetIncludeResolver(fn IncludeFunc)
- func (rt *Runtime) WorkDir() string
- func (rt *Runtime) WritablePaths() []string
- type Scope
- type Transpiler
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Context ¶
type Context struct {
Get map[string]string
Post map[string]string
Path map[string]string
Headers map[string]string
// contains filtered or unexported fields
}
Context carries HTTP request data exposed to PHP as superglobals, header functions, and staged response headers.
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/titpetric/phpscript/runner"
)
func main() {
req := httptest.NewRequest(http.MethodGet, "/users/42?tab=profile", nil)
req.Header.Set("X-Request-Id", "abc123")
req.Pattern = "GET /users/{id}"
req.SetPathValue("id", "42")
ctx := runner.FromRequest(req)
ctx.Header("X-Powered-By: phpscript")
fmt.Println(ctx.Get["tab"])
fmt.Println(ctx.Path["id"])
fmt.Println(ctx.Headers["X-Request-Id"])
fmt.Println(ctx.ResponseHeaders().Get("X-Powered-By"))
}
Output: profile 42 abc123 phpscript
func FromRequest ¶
FromRequest builds a Context from an HTTP request. Query and form values are flattened to their first value (PHP's scalar superglobal shape); path values are pulled out of the matched ServeMux pattern via r.PathValue.
func (Context) GetAllHeaders ¶
GetAllHeaders implements PHP getallheaders(): an associative array of the incoming request headers keyed by canonical header name.
func (Context) Header ¶
Header implements PHP header($header[, $replace[, $code]]): it parses a "Name: value" line and stages it on the response header set. replace controls whether an existing header of the same name is overwritten (default true).
func (Context) Register ¶
Register installs the request-aware PHP functions onto rt and seeds the request superglobals. After this, transpiled PHP can call getallheaders() / header() and read $_GET, $_POST, $_PATH — all backed by this Context.
func (Context) ResponseHeaders ¶
ResponseHeaders returns the headers staged by the PHP header() function so a host handler can copy them onto the http.ResponseWriter after execution.
type ExitError ¶
type ExitError struct {
Code int
}
ExitError is returned when PHP die()/exit() interrupts script execution.
type ExprCache ¶
type ExprCache struct {
// contains filtered or unexported fields
}
ExprCache stores compiled expression programs by AST expression node and by transpiled expr source. The node cache is the fastest path for reused parsed programs. The source cache lets freshly parsed but identical PHP expression trees reuse compiled expr bytecode across load+execute cycles.
func NewExprCache ¶
func NewExprCache() *ExprCache
NewExprCache returns an empty compiled expression cache.
type IncludeCache ¶
type IncludeCache struct {
// contains filtered or unexported fields
}
IncludeCache stores parsed include/require programs by cleaned filesystem path. Parsed programs are treated as immutable by Runtime.Run/exec: hoisting copies declarations into runtime maps, while statement execution only reads the AST, so cached *model.Program values can be shared safely by callers that do not mutate ASTs themselves.
func NewIncludeCache ¶
func NewIncludeCache() *IncludeCache
NewIncludeCache returns an empty parsed include cache.
type IncludeFunc ¶
IncludeFunc resolves an include/require path to a parsed program. Wiring this from the host keeps the runner free of file-system and parser dependencies.
type Options ¶
type Options struct {
// RootFS is the filesystem used to load PHP entrypoints and includes.
RootFS fs.FS
// SAPI provides output for `php_sapi_name`.
SAPI string
// WorkDir is the directory inside RootFS used as the script working directory.
// Empty means the RootFS root.
WorkDir string
// WritablePaths optionally restricts filesystem writes. When empty, writes are
// left to normal OS/user permissions. Enforcement is done by filesystem shims.
WritablePaths []string
}
Options configures a Runtime.
type Runtime ¶
type Runtime struct {
// contains filtered or unexported fields
}
Runtime executes parsed PHP statements and evaluates transpiled expressions with registered functions, classes, constructors, and runtime state.
func (*Runtime) ClassExists ¶ added in v0.1.0
ClassExists reports whether a PHP or host-backed class exists. If autoload is true, registered autoloaders are given a chance to define a missing class.
func (*Runtime) DeclaredClasses ¶ added in v0.1.0
DeclaredClasses returns the names of PHP classes and host-backed constructor classes currently available to the runtime. PHP does not guarantee ordering; phpscript sorts the snapshot for deterministic diagnostics.
func (*Runtime) DefinedConstants ¶ added in v0.1.0
DefinedConstants returns a stable snapshot of all runtime constants.
func (*Runtime) DefinedFunctions ¶ added in v0.1.0
DefinedFunctions returns stable snapshots of registered host/internal and PHP user-defined function names.
func (*Runtime) Eval ¶
Eval transpiles e, binds the referenced variables from scope, and runs the resulting program through the expr-lang VM.
func (*Runtime) IncludePath ¶ added in v0.1.0
IncludePath returns the current SPL include path.
func (*Runtime) IncludedFiles ¶
IncludedFiles returns the cleaned dirFS filenames included by this runtime.
func (*Runtime) OnError ¶
OnError installs an error handler (register_error_handler). When set, runtime evaluation errors are routed here instead of aborting the caller.
func (*Runtime) PHPInfo ¶ added in v0.1.0
PHPInfo prints a compact phpinfo-style text report for the phpscript runtime. It intentionally reports runtime facts rather than PHP extensions that phpscript does not provide.
func (*Runtime) RegisterAutoloader ¶ added in v0.1.0
RegisterAutoloader appends or prepends a callback to the SPL autoload queue. The callback receives a fully-qualified class name without a leading slash.
func (*Runtime) RegisterClass ¶
RegisterClass adds a resolved class to the class table so `new Name` works.
func (*Runtime) RegisterConstructor ¶
RegisterConstructor binds a class name to a Go constructor so `new Name` in PHP instantiates a native Go value. The constructor may take a leading context.Context (auto-injected) and may return a trailing error, which is surfaced to the interpreter as a thrown error. Example:
rt.RegisterConstructor("Storage", func(ctx context.Context) (Storage, error) { ... }).
// PHP: $storage = new Storage; // == storage, err := NewStorage(ctx).
func (*Runtime) RegisterFunc ¶
RegisterFunc forwards a Go function (or any callable) into the VM under name. This is the shim mechanism: e.g. rt.RegisterFunc("strlen", func(s string) int { return len(s) }) makes `strlen($x)` work in transpiled code.
func (*Runtime) SPLAutoload ¶ added in v0.1.0
SPLAutoload implements PHP's default autoloader: lowercase the qualified class name and search each include_path entry for class.php.
func (*Runtime) SetConst ¶
SetConst registers a PHP constant (e.g. define("FOO", 1) or a built-in like T_VARIABLE). Constants are visible in every scope, including inside functions and methods — unlike globals, which PHP confines to the global scope.
func (*Runtime) SetContext ¶
SetContext installs the lifecycle context auto-injected into registered Go callables whose first parameter is a context.Context (constructors, methods, functions). Defaults to context.Background().
func (*Runtime) SetExprCache ¶
SetExprCache installs a shared compiled-expression cache. Passing nil disables AST-node expression caching for this runtime.
func (*Runtime) SetGlobal ¶
SetGlobal seeds a variable into the global scope before execution. Useful for injecting request data (the README's $_SERVER gray area) or, in tests, an input value.
func (*Runtime) SetIncludeCache ¶
func (rt *Runtime) SetIncludeCache(cache *IncludeCache)
SetIncludeCache installs a shared include cache. Passing nil disables include caching.
func (*Runtime) SetIncludePath ¶ added in v0.1.0
SetIncludePath sets the path list used by the default SPL autoloader and returns its previous value.
func (*Runtime) SetIncludeResolver ¶
func (rt *Runtime) SetIncludeResolver(fn IncludeFunc)
SetIncludeResolver installs the include/require resolver.
func (*Runtime) WritablePaths ¶
WritablePaths returns the configured writable path whitelist.
type Scope ¶
type Scope struct {
// contains filtered or unexported fields
}
Scope is a flat variable table for one execution frame.
PHP has no block scoping: variables introduced inside if/for/foreach bodies live in the enclosing function scope. Each function call gets a fresh Scope; the file body runs in the global Scope.
There is intentionally no `global` keyword implemented.
func ScopeFromContext ¶ added in v0.0.6
ScopeFromContext returns the active PHP execution frame attached to a context auto-injected into a registered free function.
func (*Scope) DefinedVars ¶ added in v0.1.0
DefinedVars returns a snapshot of PHP-visible variables in this frame. Interpreter bookkeeping slots use a double-underscore prefix and are not PHP variables, so they are omitted.
type Transpiler ¶
type Transpiler struct {
// contains filtered or unexported fields
}
Transpiler lowers expression AST nodes into type-agnostic expr-lang source that delegates PHP-specific behavior to runtime helpers.
Example ¶
package main
import (
"fmt"
"github.com/titpetric/phpscript/model"
"github.com/titpetric/phpscript/runner"
)
func main() {
t := runner.NewTranspiler()
src, vars, err := t.Transpile(&model.Binary{
Op: ".",
Left: &model.Var{
Name: "greeting",
},
Right: &model.Lit{
Value: " world",
},
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(src)
fmt.Println(vars)
}
Output: __concat(v_greeting, " world") [greeting]