uuf6429/expression-language-arrowfunc

Symfony 表达式语言中的箭头函数支持

v0.1.0-alpha 2016-10-30 17:19 UTC

This package is auto-updated.

Last update: 2024-09-21 02:10:02 UTC


README

Build Status Minimum PHP Version License Coverage Scrutinizer Code Quality Packagist

Symfony 表达式语言组件中对箭头函数(也称为“Lambda 表达式”或“匿名函数”)的支持。

语法

 (a) -> { a * 2 }
  ^  ^      ^
  |  |      '----- Function body is a single expression that can make use of passed parameters or global variables.
  |  '------------ The lambda operator - input parameters are to the left and the output expression to the right.
  '--------------- Comma-separated list of parameters passed to arrow function.

安全性

在PHP中,返回回调可能很危险。如果返回的值没有进行检查,PHP可能最终会执行任意全局函数、静态类方法或对象方法。

问题示例

$language = new ExpressionLanguage();
$expression = '(value) -> { value > 20 }';
$filter = $language->evaluate($expression);
$values = array_filter([18, 23, 40], $filter);

如果$expression返回一个字符串或数组,array_filter()将任意调用返回的内容。

解决方案

有两种解决方案

  • 将使用回调的方法的类型声明设置为Closure不是Callable) - 容易出错且相当危险。
  • 引擎返回的回调被包装在一个默认无法调用的对象中 - 这是最安全的选项(也是默认选项)。