puritandesigns / poindexter
一个公式计算库
v0.3.2
2021-09-17 18:51 UTC
Requires
- php: >=7.4
Requires (Dev)
- phpunit/phpunit: ^8.3
- roave/security-advisories: dev-master
README
一个用于 PHP 的公式计算库。
安装
您可以使用 composer 安装此包
composer require puritandesigns/poindexter
用法
以下是一些用法示例
use Poindexter\Parsing\Parser; // Simple arithmetic Parser::calculate('1 + 1')->getValue(); // returns 2 Parser::calculate('2 * 2')->getValue(); // returns 4 // Comparisons // returns 1 (truthy) Parser::calculate('1 < 2')->getValue(); Parser::calculate('2 = 2')->getValue(); // returns 0 (falsy) Parser::calculate('2 <= 1')->getValue(); Parser::calculate('1 = 2')->getValue(); // Logical Operators (returns binary value) // and Parser::calculate('1 & 1')->getValue(); // returns 1 Parser::calculate('1 & 0')->getValue(); // returns 0 Parser::calculate('0 & 0')->getValue(); // returns 0 // or Parser::calculate('1 | 1')->getValue(); // returns 1 Parser::calculate('1 | 0')->getValue(); // returns 1 Parser::calculate('0 | 0')->getValue(); // returns 0 // Variables Parser::calculate('x + y', ['x' => 1, 'y' => 2])->getValue(); Parser::calculate('long_name + y', ['long_name' => 1, 'y' => 2])->getValue(); // Simple parentheses Parser::calculate('(1 + x) * (1 + y)', ['x' => 1, 'y' => 2])->getValue();
注意事项
以下是一些需要注意的事项....
解析器相当懒惰。
它不能解析字符串中的嵌套括号。但可以使用数组输入。
解析器需要元素之间有空格的字符串:- 'x+y' 会被理解为一个变量,而不是三个不同的语句 - 'x + y' 会被解析为三个语句:变量 x,加法,和变量 y
您可以从 Factors 对象手动构建更复杂的语句
use Poindexter\Interfaces\ResultInterface; use Poindexter\Factors; $factors = [ new Factors\Number(5), new Factors\Add(), new Factors\Parenthesis([ new Factors\Number(5), new Factors\Add(), new Factors\Parenthesis([ new Factors\Number(5), new Factors\Add(), new Factors\Number(5) ]) ]), new Factors\Divide(), new Factors\Number(5) ]; $calculator = new \Poindexter\Calculator($factors, ResultInterface::INTEGER); $calculator->calculate()->getValue();
请参阅测试以获取更多示例。
小心比较器
包含 <、>、=、& 等... 会为该特定表达式产生一个二进制(1 或 0)结果。如果不小心,可能会改变您公式的意图。