The purpose of this library is to provide a common base for an PHP Expression Language.
This is not really a creative library since it burrows almost all the code from the great JMSSecurityExtraBundle which already defines more or less such a base for a powerful EL (Expression Language).
The idea is to take this code outside of the Johannes's bundle and to standardize it.
$compiler = newExpressionCompiler(); $evaluator = eval($compiler->compileExpression(newExpression("date.format(format)"))); $context = array( 'date' => new \DateTime(), 'format' => 'Y', ); $result = $evaluator($context); echo$result; // 2013The isNumber() function expression:
First you need to create a compiler for your function
<?phpnamespaceMy\Expression\Compiler\Func; usePel\Expression\Compiler\Func\FunctionCompilerInterface; usePel\Expression\ExpressionCompiler; usePel\Expression\Ast\FunctionExpression; usePel\Exception\RuntimeException; class IsNumberFunctionCompiler implements FunctionCompilerInterface{publicfunctiongetName(){return'isNumber'} publicfunctioncompilePreconditions(ExpressionCompiler$compiler, FunctionExpression$function){if (1 !== count($function->args)){thrownewRuntimeException(sprintf('The isNumber() function expects exactly one argument, but got "%s".', var_export($function->args, true)))} } publicfunctioncompile(ExpressionCompiler$compiler, FunctionExpression$function){$compiler ->write("is_numeric(") ->compileInternal($function->args[0]) ->write(")") } }
Next, after having instanciated the
ExpressionCompiler, you just need to register your custom function compiler<?php$compiler = newExpressionCompiler(); $compiler->addFunctionCompiler(newIsNumberFunctionCompiler()); $evaluator = eval($compiler->compileExpression(newExpression("isNumber('1234')"))); var_dump(call_user_func($evaluator, array())); // bool(true)$evaluator = eval($compiler->compileExpression(newExpression("isNumber('1234abc')"))); var_dump(call_user_func($evaluator, array())); // bool(false)
This bundle is under the MIT license. See the complete license in library:
LICENSE