PHP code example of nathanjel / sel-lang
1. Go to this page and download the library: Download nathanjel/sel-lang library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
nathanjel / sel-lang example snippets
$rule = Sel::compile('IF(QTY * PRICE > LIMIT, "over budget", "ok")');
foreach ([['QTY' => '3', 'PRICE' => '19.99'], ['QTY' => '1', 'PRICE' => '5.00']] as $row) {
$ctx = Value::fromNative($row + ['LIMIT' => '50.00']);
printf(" QTY=%s PRICE=%s => %s\n", $row['QTY'], $row['PRICE'], $rule->run($ctx)->asText());
}
final class RuleSet
{
private array $rules = [];
public function __construct(array $sources) // field => SEL source
{
foreach ($sources as $field => $source) {
$this->rules[$field] = Sel::compile($source);
}
}
public function validate(array $payload): array
{
$messages = [];
foreach ($this->rules as $field => $program) {
$context = Value::fromNative($payload);
try {
$result = $program->run($context)->asText();
} catch (SelError $e) {
$result = self::present($field, $e);
}
if ($result !== '') {
$messages[$field] = $result;
}
}
return $messages;
}
private static function present(string $field, SelError $e): string
{
if ($e->code === 'E_ABORT') {
return $e->getMessage();
}
error_log("SEL rule for {$field} failed: {$e}");
return 'could not be validated';
}
$ node js/bin/sel.mjs -e '2.50 + 2.50'
5.00
$ php php/bin/sel -e 'JOIN(MAP((1,2,3), _ * _), ",")'
1,4,9
$ php php/bin/sel --deps -e 'T = QTY * PRICE; T > LIMIT'
LIMIT
PRICE
QTY
$ node js/bin/sel.mjs # REPL, keeps its context between lines
sel> A = (1, 2, 3)
-{"1"=t"1", "2"=t"2", "3"=t"3"}
sel> SUM(A, _)
6
sel
A[1] = (A = 2); A => t"2"{"1"=t"2"}
sel
A[COUNT(A)] = 1; A => -{"0"=t"1"}
A = 1; A += (A = 5); A => 6
sel
2.50 + 2.50 => 5.00
0.10 + 0.20 == 0.30 => TRUE
1 / 3 => 0.3333333333
"5.00" == "5" => TRUE
"5.00" $== "5" => FALSE
A = 3; "value {A} here" => value 3 here
JOIN(("a", "b", "c"), "-") => a-b-c
A = (1, 2); A = (A, 3); COUNT(A) => 3
A[1] = 3; A == 3 => TRUE
ALL((1, 2, 3), _ > 0) => TRUE
JOIN(MAP((1, 2), _ * 2), ",") => 2,4
SUM((1.5, 2.5), _) => 4.0
S = 85; COND(S >= 90, "A", S >= 80, "B", "F") => B
LEN("Zażółć") & "/" & BLEN("Zażółć") => 6/10
RMATCH('^\d{2}-\d{3}$', "31-874") => TRUE
IF(1, "a", "b") => !E_NOT_BOOL
" 2" + 1 => !E_NOT_NUM
1 < 2 < 3 => !E_SYNTAX
NULL ?? "default" => default
" " ??? "fallback" => fallback
IS_NULL(NULL) => TRUE
IS_BLANK(" ") => TRUE