PHP code example of kennyth01 / php-rules-engine

1. Go to this page and download the library: Download kennyth01/php-rules-engine 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/ */

    

kennyth01 / php-rules-engine example snippets


$engine = new Engine();
$rule = json_decode(file_get_contents('rule.player.isFouledOut.json'), true);

$engine->addRule(new Rule($rule));
$engine->addFact('personalFoulCount', 6);
$engine->addFact('gameDuration', 40);

$engine->setTargetRule('rule.player.isFouledOut');

$result = $engine->evaluate();
print_r($result);

[
    'type' => 'fouledOut',
    'params' => [
        'message' => 'Player has fouled out!'
    ],
    'facts' => [
        'personalFoulCount' => 6,
        'gameDuration' => 40

    ],
    'interpretation' => '((gameDuration is equal to 40 AND personalFoulCount is >= 5) OR (gameDuration is equal to 48 AND NOT (personalFoulCount is less than 6)))'
]

$engine = new Engine();

$ruleConfig = [
    "name" => "speed.check",
    "conditions" => [
        "all" => [
            [
                "fact" => "currentSpeed",
                "operator" => "lessThanInclusive",
                "value" => ["fact" => "speedLimit"]  // Compare to another fact
            ]
        ]
    ],
    "event" => ["type" => "withinLimit", "params" => ["message" => "Speed is within limit"]],
    "failureEvent" => ["type" => "speeding", "params" => ["message" => "Exceeding speed limit"]]
];

$engine->addRule(new Rule($ruleConfig));
$engine->setTargetRule('speed.check');

// Add both facts dynamically
$engine->addFact('currentSpeed', 55);
$engine->addFact('speedLimit', 60);

$result = $engine->evaluate();
// Result: withinLimit - Speed is within limit

$ruleConfig = [
    "name" => "age.verification",
    "conditions" => [
        "all" => [
            [
                "fact" => "user",
                "path" => "$.age",
                "operator" => "greaterThanInclusive",
                "value" => [
                    "fact" => "ts', ['minimumAge' => 18]);
bash
composer