kitano/php-expression

PHP 表达式语言

dev-master / 0.1.x-dev 2013-09-02 08:28 UTC

This package is not auto-updated.

Last update: 2024-09-21 16:53:56 UTC


README

这个库的目的是提供一个 PHP 表达式语言的通用基础。

这并不是一个具有创造性的库,因为它几乎从伟大的 JMSSecurityExtraBundle 中抽取了几乎所有代码,它已经为强大的 EL(表达式语言)定义了这样的基础。

想法是将这段代码从 Johannes 的包中提取出来,并使其标准化。

简单用法

$compiler = new ExpressionCompiler();
$evaluator = eval($compiler->compileExpression(new Expression("date.format(format)")));

$context = array(
    'date' => new \DateTime(),
    'format' => 'Y',
);
$result = $evaluator($context);

echo $result; // 2013

添加自定义函数编译器

isNumber() 函数表达式

  1. 首先,您需要为您自己的函数创建一个编译器

    <?php
    
    namespace My\Expression\Compiler\Func;
    
    use Pel\Expression\Compiler\Func\FunctionCompilerInterface;
    use Pel\Expression\ExpressionCompiler;
    use Pel\Expression\Ast\FunctionExpression;
    use Pel\Exception\RuntimeException;
    
    class IsNumberFunctionCompiler implements FunctionCompilerInterface
    {
        public function getName()
        {
            return 'isNumber';
        }
    
        public function compilePreconditions(ExpressionCompiler $compiler, FunctionExpression $function)
        {
            if (1 !== count($function->args)) {
                throw new RuntimeException(sprintf('The isNumber() function expects exactly one argument, but got "%s".', var_export($function->args, true)));
            }
        }
    
        public function compile(ExpressionCompiler $compiler, FunctionExpression $function)
        {
            $compiler
                ->write("is_numeric(")
                ->compileInternal($function->args[0])
                ->write(")")
            ;
        }
    }
  2. 接下来,在实例化 ExpressionCompiler 之后,您只需注册您自定义的函数编译器

    <?php
    
    $compiler = new ExpressionCompiler();
    $compiler->addFunctionCompiler(new IsNumberFunctionCompiler());
    
    $evaluator = eval($compiler->compileExpression(new Expression("isNumber('1234')")));
    var_dump(call_user_func($evaluator, array()));
    // bool(true)
    
    $evaluator = eval($compiler->compileExpression(new Expression("isNumber('1234abc')")));
    var_dump(call_user_func($evaluator, array()));
    // bool(false)

许可证

这个包遵循 MIT 许可证。请参阅库中的完整许可证。

LICENSE