naotake51/evaluation

v1.0.0 2022-04-23 08:52 UTC

This package is auto-updated.

Last update: 2024-09-15 20:35:50 UTC


README

naotake51/evaluation 是一个 Composer 包,用于创建一个简单的表达式评估模块。它允许您注册自己的函数来评估表达式(字符串)。

使用方法

use Naotake51\Evaluation\Evaluation;

$evaluation = new Evaluation([
    'square' => function (array $arguments) {
        return $arguments[0] * $arguments[0];
    }
]);
$result = $evaluation('square(2) + square(2)'); // => 8

文字

运算符和优先级

魔术函数

$evaluation = new Evaluation([
    '__add' => function (array $arguments) {
        return "$arguments[0] + $arguments[1]";
    }
]);
$result = $evaluation('1 + 2'); // => '1 + 2'
$evaluation = new Evaluation([
    '*' => function (string $identify, array $arguments) {
        return 'call' . $identify . '(' . implode(', ', $arguments). ')';
    }
]);
$result = $evaluation('hoge(1, 2)'); // => 'call hoge(1, 2)'

参数检查

通过传递数组,您可以定义参数的类型。也可以通过使用 '|' 分隔符来表示 OR。

$evaluation = new Evaluation([
    'repeat' => [
        'string, integer|null' => function (string $str, ?int $repeat) {
            return str_repeat($str, $repeat ?? 2);
        },
    ]
]);
$result = $evaluation("repeat('abc', 3)"); // => 'abcabcabc'

重载

可以通过注册来重载多个模式。

$evaluation = new Evaluation([
    '__add' => [
        'string, string' => function (string $a, string $b) {
            return $a . $b;
        },
        'numeric, numeric' => function ($a, $b) {
            return $a + $b;
        },
    ]
]);
$result = $evaluation("'abc' + 'def'"); // => 'abcdef'

运行时错误

use Naotake51\Evaluation\Evaluation;
use Naotake51\Evaluation\Errors\EvaluationError;

try {
    $evaluation = new Evaluation([
        'hoge' => function (array $arguments) {
            return 'hoge';
        },
    ]);
    $result = $evaluation("fuga()"); // => UndefineFunctionError
} catch (EvaluationError $e) {
    error_log($e->getMessage()); // => 'function fuga is not exists.'
}