Milk Admin

API ExpressionParser (PHP & JS)

The API is very similar between PHP and JavaScript. Below are the main methods and differences.

Main Methods

Method PHP JS Description
setParameters(...) setParameters(array $params) setParametersFromForm(form|object) Sets parameters available for [field]
setParameter(...) setParameter(string $name, mixed $value) setParameter(name, value) Sets a single parameter
parse(...) parse(string $source) parse(source) Parses the expression into AST
execute(...) execute(ast|string) execute(ast|string) Executes the AST and returns the result
analyze(...) analyze(source, execute=true) analyze(source, execute=true) Returns AST, operation order, tree and result
getOperationOrder(...) getOperationOrder(ast|string) getOperationOrder(ast|string) List operations in execution order
visualizeTree(...) visualizeTree(ast|string) visualizeTree(ast|string) Textual representation of the AST
formatResult(...) formatResult(mixed) formatResult(value) Formats dates and booleans for readable output
reset / resetAll reset() / resetAll() reset() / resetAll() Reset variables (and parameters)
getBuiltinFunctions() getBuiltinFunctions() getBuiltinFunctions() List of available functions
normalizeCheckboxValue(...) normalizeCheckboxValue(mixed) normalizeCheckboxValue(value) Normalizes checkbox values to boolean

Example (PHP)

$parser = new \App\ExpressionParser();
$parser->setParameters([
    'qty' => 3,
    'price' => 10
]);

$result = $parser->execute('[qty] * [price]'); // 30

Example (JS)

const parser = new ExpressionParser();
parser.setParameter('qty', 3);
parser.setParameter('price', 10);

const result = parser.execute('[qty] * [price]'); // 30
Important differences:
  • In JS you can use setParametersFromForm(form) to load values directly from an HTML form.
  • In PHP getVariables() and getParameters() are available to inspect the internal state.
Loading...