Skip to content

Releases: zxc7563598/php-simple-rule-engine

v1.0.2

27 May 02:58
Compare
Choose a tag to compare

无关痛痒的description调整

v1.0.1

04 May 12:53
Compare
Choose a tag to compare

无关痛痒的README调整

v1.0.0

29 Apr 13:20
Compare
Choose a tag to compare

🎉 v1.0.0发布

🛠️ 用法示例

use Hejunjie\SimpleRuleEngine\Rule;
use Hejunjie\SimpleRuleEngine\Engine;

// 定义规则
$rules = [
    new Rule('age', '>=', 18, '年龄必须大于等于18岁'),
    new Rule('country', '==', 'SG', '国家必须是新加坡'),
];

// 待评估的数据
$data = [
    'age' => 20,
    'country' => 'SG',
];

// 评估结果
$result = Engine::evaluate($rules, $data, 'AND'); // 返回 true 或 false

// 获取详细评估信息
$details = Engine::evaluateWithDetails($rules, $data);
/*
返回示例:
[
    ['description' => '年龄必须大于等于18岁', 'passed' => true],
    ['description' => '国家必须是新加坡', 'passed' => true],
]
*/

🧩 内置操作符

操作符 描述 额外说明
== 等于
!= 不等于
> 大于
>= 大于等于
< 小于
<= 小于等于
in 包含于集合中 数组:[内容 1,内容 2,...]
not_in 不包含于集合中 数组:[内容 1,内容 2,...]
contains 包含字符串
not_contains 不包含字符串
start_swith 以指定字符串开头
end_swith 以指定字符串结尾
between 在指定范围内 数组:[最大值,最小值]
not_between 不在指定范围内 数组:[最大值,最小值]
before_date 日期早于 任意常规日期格式,包括时间戳均可
after_date 日期晚于 任意常规日期格式,包括时间戳均可
date_equal 日期相等 任意常规日期格式,包括时间戳均可

你也可以通过注册机制添加自定义操作符。


🔌 自定义操作符

实现 OperatorInterface​ 接口,并通过 OperatorFactory​ 注册:

use Hejunjie\SimpleRuleEngine\Operators\OperatorInterface;
use Hejunjie\SimpleRuleEngine\OperatorFactory;

class CustomizeOperator implements OperatorInterface
{
    /**
     * 评估方法
     *
     * @param mixed $fieldValue 用户输入数据
     * @param mixed $ruleValue 对比数据
     *
     * @return bool
     */
    public function evaluate(mixed $fieldValue, mixed $ruleValue): bool
    {
        // TODO: 实现判断逻辑
    }

    /**
     * 操作符名称
     *
     * @return string
     */
    public function name(): string
    {
        return 'customize';
    }
}

// 注册自定义操作符 customize
$factory = OperatorFactory::getInstance();
$factory->register(new CustomizeOperator());

// 可以在定义规则时使用 customize
$rules = [
    new Rule('field', 'customize', 'value', '自定义规则描述'),
    ...
    ...
];