nicoswd/php-rule-parser 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

nicoswd/php-rule-parser

Composer 安装命令:

composer require nicoswd/php-rule-parser

包简介

Rule Engine - Rule Parser & Evaluator

README 文档

README

Latest Stable Version Total Downloads Code Quality StyleCI Code Coverage

A PHP library that parses and evaluates boolean expressions using a JavaScript-like syntax. It supports variables, comparison and logical operators, arithmetic, regular expressions, arrays, string methods, and function calls, all from plain text rules.

Install

Via Composer

composer install nicoswd/php-rule-parser

Usage Examples

E-commerce: Validate coupon eligibility

$variables = [
    'cart_total'     => 120,
    'user_tier'      => 'gold',
    'is_blacklisted' => false,
];

$rule = new Rule('
    cart_total >= 50 && 
    user_tier in ["gold", "platinum"] &&
    !is_blacklisted
', $variables);

var_dump($rule->isTrue()); // bool(true) — eligible for discount

Access control: Check user permissions

$variables = [
    'role'         => 'editor',
    'is_suspended' => false,
];

$rule = new Rule('role in ["admin", "editor"] && !is_suspended', $variables);
var_dump($rule->isTrue()); // bool(true) — access granted

Pricing: Calculate order total with conditions

$variables = [
    'base_price' => 29.99,
    'tax_rate'   => 21,
    'quantity'   => 3,
];

$rule = new Rule('(base_price + (base_price * tax_rate / 100)) * quantity', $variables);
var_dump($rule->result()); // float(108.8571...) — total with tax

Form validation: Check input constraints

$variables = [
    'age'     => 25,
    'country' => 'US',
];

$rule = new Rule('age >= 18 && country in ["US", "CA", "UK"]', $variables);
var_dump($rule->isTrue()); // bool(true) — valid registration

Notification routing: Target specific users

$variables = [
    'plan'                 => 'pro',
    'last_login'           => 3,
    'notification_opt_out' => false,
];

$rule = new Rule('
    plan in ["pro", "enterprise"] &&
    last_login < 7 &&
    !notification_opt_out
', $variables);

var_dump($rule->isTrue()); // bool(true) — send notification

Feature flags: Roll out features gradually

$variables = [
    'user_id' => 7,
];

$rule = new Rule('user_id % 10 < 3', $variables);
var_dump($rule->isTrue()); // bool(true) — feature enabled for this user

String manipulation: Format user data

$variables = [
    'firstName' => 'John',
    'lastName'  => 'Doe',
];

$rule = new Rule('firstName.toUpperCase() + " " + lastName.toUpperCase()', $variables);
var_dump($rule->result()); // string("JOHN DOE")

Object method calls: Evaluate complex conditions

class Subscription
{
    public function isActive(): bool
    {
        return true;
    }

    public function daysUntilExpiry(): int
    {
        return 15;
    }
}

$variables = [
    'subscription' => new Subscription(),
];

$rule = new Rule('subscription.isActive() && subscription.daysUntilExpiry() > 7', $variables);
var_dump($rule->isTrue()); // bool(true) — subscription is active and not expiring soon

Arithmetic: Operator precedence

$rule = new Rule('2 + 3 * 4 == 14');
var_dump($rule->isTrue()); // bool(true) - multiplication before addition

$rule = new Rule('(2 + 3) * 4 == 20');
var_dump($rule->isTrue()); // bool(true) - parentheses override precedence

Arithmetic: Unary operators

$rule = new Rule('-5 * 3 == -15');
var_dump($rule->isTrue()); // bool(true) - unary minus

$rule = new Rule('!false');
var_dump($rule->isTrue()); // bool(true) - logical NOT

$rule = new Rule('!(1 == 2)');
var_dump($rule->isTrue()); // bool(true) - NOT with comparison

Note

For security reasons, PHP's magic methods like __construct and __destruct cannot be called from within rules. However, __call will be invoked automatically if available, unless the called method is defined.

Built-in Methods

Name Example
charAt "foo".charAt(2) === "o"
concat "foo".concat("bar", "baz") === "foobarbaz"
endsWith "foo".endsWith("oo")
startsWith "foo".startsWith("fo")
indexOf "foo".indexOf("oo") === 1
join ["foo", "bar"].join(",") === "foo,bar"
replace "foo".replace("oo", "aa") === "faa"
split "foo-bar".split("-") === ["foo", "bar"]
substr "foo".substr(1) === "oo"
test "foo".test(/oo$/)
toLowerCase "FOO".toLowerCase() === "foo"
toUpperCase "foo".toUpperCase() === "FOO"

Built-in Functions

Name Example
parseInt parseInt("22aa") === 22
parseFloat parseFloat("3.1") === 3.1

Supported Operators

Type Description Operator
Comparison greater than >
Comparison greater than or equal to >=
Comparison less than <
Comparison less or equal to <=
Comparison equal to ==
Comparison not equal to !=
Comparison identical ===
Comparison not identical !==
Containment contains in
Containment does not contain not in
Logical and &&
Logical or ||
Arithmetic addition +
Arithmetic subtraction -
Arithmetic multiplication *
Arithmetic division /
Arithmetic modulo %
Unary negation -
Unary logical NOT !

Error Handling

Both $rule->isTrue() and $rule->isFalse() will throw an exception if the syntax is invalid. These calls can either be placed inside a try / catch block, or validity can be checked beforehand using $rule->isValid().

$ruleStr = '
    (2 == 2) && (
        1 < 3 && 3 == 2 ( // Missing and/or before parentheses
            1 == 1
        )
    )';

$rule = new Rule($ruleStr);

try {
    $rule->isTrue();
} catch (\Exception $e) {
    echo $e->getMessage();
}

Or alternatively:

if (!$rule->isValid()) {
    echo $rule->error;
}

Both will output: Unexpected "(" at position 28

Syntax Highlighting

A custom syntax highlighter is also provided.

use nicoSWD\Rule\Highlighter\Highlighter;
use nicoSWD\Rule\TokenStream\Token\TokenType;

$ruleStr = '
    // This is true
    2 < 3 && (
        // This is false
        foo in [4, 6, 7] ||
        // True
        [1, 4, 3].join("") === "143"
    ) && (
        // True
        "foo|bar|baz".split("|" /* uh oh */) === ["foo", /* what */ "bar", "baz"] &&
        // True
        bar > 6
    )';

$highlighter = new Highlighter();

// Optional custom styles
$highlighter->setStyle(
    TokenType::VARIABLE,
    'color: #007694; font-weight: 900;'
);

echo $highlighter->highlightString($ruleStr);

Outputs:

Syntax preview

Security

If you discover any security related issues, please email security@nic0.me instead of using the issue tracker.

Testing

$ composer test

Contributing

Pull requests are very welcome! If they include tests, even better. This project follows PSR-12 coding standards, please make sure your pull requests do too.

To Do

  • Support for object properties (foo.length)
  • Support for array / string dereferencing: "foo"[1]
  • Support for returning actual results, other than true or false
  • Don't force boolean comparison for tokens that are already booleans. my_func() && 2 > 1 should work
  • Allow string concatenating with "+"
  • Duplicate regex modifiers should throw an error
  • Add support for function calls
  • Support for regular expressions
  • Fix build on PHP 7 / Nightly
  • Allow variables in arrays
  • Verify function and method name spelling (.tOuPpErCAse() is currently valid)
  • Change regex and implementation for method calls
  • Add / implement missing methods
  • Invalid regex modifiers should not result in an unknown token
  • ...

License

License

nicoswd/php-rule-parser 适用场景与选型建议

nicoswd/php-rule-parser 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 81.29k 次下载、GitHub Stars 达 130, 最近一次更新时间为 2015 年 07 月 22 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「javascript」 「parser」 「DSL」 「workflow」 「tokenizer」 「engine」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 nicoswd/php-rule-parser 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 nicoswd/php-rule-parser 我们能提供哪些服务?
定制开发 / 二次开发

基于 nicoswd/php-rule-parser 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 81.29k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 131
  • 点击次数: 49
  • 依赖项目数: 7
  • 推荐数: 0

GitHub 信息

  • Stars: 130
  • Watchers: 6
  • Forks: 18
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2015-07-22