asylum29 / php-formula-interpreter
PHP公式解释器
v0.9.2
2023-11-03 10:26 UTC
Requires (Dev)
- phpunit/phpunit: 7.5.20
- symfony/class-loader: 2.1.*
This package is auto-updated.
Last update: 2024-10-03 12:29:01 UTC
README
一个用于解析和运行公式的独立PHP库
通过composer安装
composer require asylum29/php-formula-interpreter
它是如何工作的?
首先,创建一个 \Mormat\FormulaInterpreter\Compiler
的实例
$compiler = new \Mormat\FormulaInterpreter\Compiler();
然后使用 compile()
方法解析您想要解释的公式。它将返回一个 \Mormat\FormulaInterpreter\Executable
的实例
$executable = $compiler->compile('2 + 2');
最后,从可执行文件中运行公式
$result = $executable->run(); // $result equals 4
公式的示例
// variables can be used
price + 2
// parenthesis can be used
(1 + 2) * 3
// default functions are available
sqrt(4)
// complex formulas can be used
(((100 * 0.43075) * 1.1 * 1.5) / (1-0.425)) * 1.105
// string are supported
lowercase('FOO')
// arrays are supported
count([2, 3, 4])
// custom functions can be registered
your_function_here(2)
// use the in operator to check if an item is in array
1 in [1, 2, 3] // returns true
// use the in operator to check if a substring is in a string
'Wars' in 'Star Wars'
公式中支持的数据类型
数值
数值可以是整数或浮点数
2 // integer
2.30 // float
字符串
使用单引号作为字符串的分隔符
'foobar'
数组
使用逗号分隔项,使用括号包裹项
[1, 2, 3]
函数、字符串和操作可以作为数组的一项使用
[cos(0), 'foobar', 2 + 2]
使用运算符
以下运算符可用
运算符 *
和 \
首先被评估,然后是运算符 +
和 -
您也可以通过使用括号来强制表达式的优先级,如下所示
2 * (3 + 2)
您可以使用任意数量的括号。
2 * (2 * (3 + 2 * (3 + 2)) + 2)
使用变量
变量只是公式中的一个词,如下所示
price * rate / 100
在PHP中执行公式之前,请确保将所有所需的变量注入到数组中
$variables = array( 'price' => 40.2, 'rate' => 12.8 ); $executable->run($variables);
使用函数
可用的函数
如何注册自定义函数?
在 \Mormat\FormulaInterpreter\Compiler
类中使用 registerCustomFunction()
方法。
自定义函数必须实现 \Mormat\FormulaInterpreter\Functions\FunctionInterface
接口。该接口包含以下方法
- getName() 返回函数的名称
- supports($arguments) 如果发送到函数的 $arguments 是有效的,则返回 true。
- execute($arguments) 执行函数并返回值。
为什么是这个库?
某些用户可能希望执行简单的计算并且可以尽可能多地更改它。在使用库之前,您可以使用 eval
函数。但这种方法有两个主要缺点
-
安全性。PHP脚本通过 eval 函数被评估。PHP是一种非常强大的语言,可能对用户来说太强大了,尤其是当用户想要注入恶意代码时。
-
复杂性。PHP对于不了解编程语言的人来说也很复杂。解释一个类似于Excel的公式可能会更好。