PHP code example of goplasmatic / datalogic

1. Go to this page and download the library: Download goplasmatic/datalogic 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/ */

    

goplasmatic / datalogic example snippets


use Goplasmatic\Datalogic\Engine;

$engine = new Engine();
echo $engine->apply('{"+":[1,2]}', '{}');  // "3"

$engine = new Engine();
$rule = $engine->compile('{"var":"x"}');
foreach ([1, 2, 3] as $x) {
    echo $rule->evaluate(json_encode(['x' => $x])), "\n";
}

$shape = $engine->compileTemplate('{"user": {"var": "name"}, "n": 1}');
echo $shape->evaluate('{"name": "ana"}');  // {"user":"ana","n":1}

use Goplasmatic\Datalogic\Exception\ParseException;

echo $engine->check('{"if": [{">": [{"var": "age"}, 17]}, "adult", {"vr": "x"}]}');
// [{"code":"UnknownOperator","severity":"error","message":"unknown operator `vr`; did you mean `var`?",
//   "pointer":"/if/2","operator":"vr"}]

try {
    $rule = $engine->compileChecked($ruleJson);
} catch (ParseException $e) {
    echo $e->errorType;        // "CompileError"
    echo $e->diagnosticsJson;  // every diagnostic, errors and warnings
}

$rule = $engine->compile(
    '{"and": [{">=": [{"var": "user.age"}, 18]}, {"in": [{"var": "user.plan"}, ["pro", "team"]]}]}'
);
echo $rule->facts();
// {"reads":[["user","age"],["user","plan"]],"computed_reads":false,"reads_complete":true,
//  "reads_data":true,"operators":[">=","and","in","val"],"custom_operators":[],
//  "deterministic":true}

$session = $engine->openSession();
foreach ($inputs as $data) {
    $result = $session->evaluate($rule, $data);
}

use Goplasmatic\Datalogic\DataHandle;

$data = new DataHandle('{"user":{"age":42,"plan":"pro"}}');
$rule->evaluate($data);              // same result as the string overload
$session->evaluate($rule, $data);    // hot path: zero parse work per call

$session->evaluateBool($rule, $data);    // bool  (strict: JSON true/false only)
$session->evaluateInt($rule, $data);     // int   (exact integers only)
$session->evaluateFloat($rule, $data);   // float (any JSON number)
$session->evaluateTruthy($rule, $data);  // bool  (JSONLogic truthiness, never mismatches)

use Goplasmatic\Datalogic\BatchItemError;

$results = $session->evaluateBatch($rule, $handles);   // list<DataHandle> in
$results = $session->evaluateMany($rules, $data);      // list<Rule> in

foreach ($results as $i => $r) {
    if ($r instanceof BatchItemError) {
        error_log("item {$i} failed: {$r->tag}: {$r->message}");
        continue;
    }
    // $r is the item's JSON-string result
}

$engine = Engine::builder()
    ->addOperator('double', function (string $argsJson): string {
        $args = json_decode($argsJson, true);
        return (string) ((int) $args[0] * 2);
    })
    ->build();
echo $engine->apply('{"double":[21]}', '{}');  // "42"

Engine::builder()
    ->withStrictOperatorNames(true)
    ->addOperator('length', fn (string $args): string => '0');  // throws: `length` is a built-in

$lenient = Engine::builder()
    ->setConfigJson('{"division_by_zero":"return_null"}')
    ->build();
echo $lenient->apply('{"/":[1.5,0]}', '{}');  // "null"

$strict = Engine::builder()
    ->setConfigJson('{"preset":"strict"}')
    ->build();
$strict->apply('{"+":["",1]}', '{}');         // throws: strict rejects non-numeric coercion

$m = $engine->openSession()->evaluateMetered($rule, '{"xs": [1, 2, 3]}');
echo $m['value'], ' cost ', $m['ops'], " operations\n";

$strings = Engine::builder()->withFamilies('ExtString')->build();
echo $strings->apply('{"length": "abc"}', 'null');  // 3
$strings->apply('{"now": []}', 'null');             // throws: InvalidOperator

use Goplasmatic\Datalogic\Exception\EvaluateException;

try {
    $engine->apply('{"+":["x",1]}', '{}');  // arithmetic on a non-numeric string throws {"type":"NaN"}
} catch (EvaluateException $e) {
    echo $e->errorType;     // "Thrown"
    echo $e->operatorName;  // "+"
    echo $e->pathJson;      // JSON-array path through the compiled tree
}

$session = $engine->openTracedSession();
$run = $session->evaluate('{"+":[{"var":"x"},1]}', '{"x":41}');
echo $run->result;             // 42
echo count($run->steps);       // number of execution steps
echo $run->pointers['3'];      // /+/1: node 3 is the literal 1
ini
; php.ini
opcache.preload=/path/to/vendor/goplasmatic/datalogic/preload.php
opcache.preload_user=www-data
ffi.enable=preload