You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
*Note:* This is a development branch. Use at own risk until tagged stable.
12
+
11
13
You're looking at a PHP library to parse and evaluate text based rules with a Javascript-like syntax. This project was born out of the necessity to evaluate hundreds of rules that were originally written and evaluated in JavaScript, and now needed to be evaluated on the server-side, using PHP.
12
14
13
15
This library has initially been used to change and configure the behavior of certain "Workflows" (without changing actual code) in an intranet application, but it may serve a purpose elsewhere.
@@ -69,6 +71,56 @@ $rule = new Rule($ruleStr, $variables);
69
71
var_dump($rule->isTrue()); // bool(true)
70
72
```
71
73
74
+
## Custom Functions
75
+
76
+
```php
77
+
$ruleStr = 'double(value) === result';
78
+
79
+
$variables = [
80
+
'value' => 2,
81
+
'result' => 4
82
+
];
83
+
84
+
$rule = new Rule($ruleStr, $variables);
85
+
86
+
$rule->registerFunction('double', function (BaseToken $multiplier) : BaseToken {
87
+
if (!$multiplier instanceof TokenInteger) {
88
+
throw new \Exception;
89
+
}
90
+
91
+
return new TokenInteger($multiplier->getValue() * 2);
92
+
});
93
+
94
+
var_dump($rule->isTrue()); // bool(true)
95
+
```
96
+
97
+
## Redefine Operators
98
+
Operators can be overwritten with custom ones, if desired. Note that it's easy to break stuff by doing that.
99
+
You may want to set a different `$priority` when registering a token. `::registerToken($type, $regex, $priority)`. Take a look at `Tokenizer::__construct()` for more info.
100
+
101
+
```php
102
+
$ruleStr = ':this is greater than :that';
103
+
104
+
$variables = [
105
+
':this' => 8,
106
+
':that' => 7
107
+
];
108
+
109
+
$rule = new Rule($ruleStr, $variables);
110
+
111
+
$rule->registerToken(
112
+
Tokenizer::TOKEN_GREATER,
113
+
'\bis\s+greater\s+than\b'
114
+
);
115
+
116
+
$rule->registerToken(
117
+
Tokenizer::TOKEN_VARIABLE,
118
+
':\w+'
119
+
);
120
+
121
+
var_dump($rule->isTrue()); // bool(true)
122
+
```
123
+
72
124
## Error Handling
73
125
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 it can be checked prior using `$rule->isValid()`.
0 commit comments