PHP code example of hejunjie / simple-rule-engine

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

    

hejunjie / simple-rule-engine example snippets


use Hejunjie\SimpleRuleEngine\Rule;
use Hejunjie\SimpleRuleEngine\Engine;

// Define Rules
$rules = [
    new Rule('age', '>=', 18, 'Age must be greater than or equal to 18'),
    new Rule('country', '==', 'SG', 'Country must be Singapore'),
];

// Data to be evaluated
$data = [
    'age' => 20,
    'country' => 'SG',
];

// Evaluation Result
$result = Engine::evaluate($rules, $data, 'AND'); // Return true or false

// Get Detailed Evaluation Information
$details = Engine::evaluateWithDetails($rules, $data);
/*
Return Example:
[
    ['description' => 'Age must be greater than or equal to 18', 'passed' => true],
    ['description' => 'Country must be Singapore', 'passed' => true],
]
*/

use Hejunjie\SimpleRuleEngine\Interface\OperatorInterface;
use Hejunjie\SimpleRuleEngine\OperatorFactory;

class CustomizeOperator implements OperatorInterface
{
    /**
     * Evaluation Method
     *
     * @param mixed $fieldValue field Value
     * @param mixed $ruleValue rule Value
     *
     * @return bool
     */
    public function evaluate(mixed $fieldValue, mixed $ruleValue): bool
    {
        // TODO: Implement the evaluation logic
    }

    /**
     * Operator Name
     *
     * @return string
     */
    public function name(): string
    {
        return 'customize';
    }
}

// Register custom operator with customize
$factory = OperatorFactory::getInstance();
$factory->register(new CustomizeOperator());

// You can use customize when defining rules
$rules = [
    new Rule('field', 'customize', 'value', 'Custom rule description'),
    ...
    ...
];