nicoswd/php-rule-parser
Composer 安装命令:
composer require nicoswd/php-rule-parser
包简介
Rule Engine - Rule Parser & Evaluator
README 文档
README
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:
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 falseDon't force boolean comparison for tokens that are already booleans.my_func() && 2 > 1should workAllow string concatenating with "+"Duplicate regex modifiers should throw an errorAdd support for function callsSupport for regular expressionsFix build on PHP 7 / NightlyAllow variables in arraysVerify function and method name spelling (.tOuPpErCAse() is currently valid)Change regex and implementation for method callsAdd / implement missing methodsInvalid regex modifiers should not result in an unknown token- ...
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 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 nicoswd/php-rule-parser 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Generates a Blade directive exporting all of your named Laravel routes. Also provides a nice route() helper function in JavaScript.
Easy to use SDK with grabber for multiple platforms at once like YouTube, Dailymotion, Facebook and more.
Caching and compression for Twig assets (JavaScript and CSS).
A pretty nice way to expose your translation messages to your JavaScript.
Feature complete, object oriented, composable, extendable Elasticsearch query DSL builder for PHP.
Elasticsearch DSL library
统计信息
- 总下载量: 81.29k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 131
- 点击次数: 49
- 依赖项目数: 7
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2015-07-22