PHP code example of nicoswd / php-rule-parser

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

    

nicoswd / php-rule-parser example snippets


$variables = ['foo' => 6];

$rule = new Rule('foo in [4, 6, 7]', $variables);
var_dump($rule->isTrue()); // bool(true)

$rule = new Rule('[1, 4, 3].join(".") === "1.4.3"');
var_dump($rule->isTrue()); // bool(true)

$variables = ['threshold' => 80];

$rule = new Rule('threshold >= 50 && threshold <= 100', $variables);
var_dump($rule->isTrue()); // bool(true)

class User
{
    // ...

    public function points(): int
    {
        return 1337;    
    }
}

$variables = [
    'user' => new User(),
];

$rule = new Rule('user.points() > 300', $variables);
var_dump($rule->isTrue()); // bool(true)

$ruleStr = '
    (2 == 2) && (
        1 < 3 && 3 == 2 ( // Missing and/or before parentheses
            1 == 1
        )
    )';

$rule = new Rule($ruleStr);

try {
    $rule->isTrue();
} catch (\Exception $e) {
    echo $e->getMessage();
}

if (!$rule->isValid()) {
    echo $rule->getError();
}

use nicoSWD\Rule;

$ruleStr = '
    // This is true
    2 < 3 && (
        // This is false
        foo in [4, 6, 7] ||
        // True
        [1, 4, 3].join("") === "143"
    ) && (
        // True
        "foo|bar|baz".split("|" /* uh oh */) === ["foo", /* what */ "bar", "baz"] &&
        // True
        bar > 6
    )';

$highlighter = new Rule\Highlighter\Highlighter(new Rule\Tokenizer());

// Optional custom styles
$highlighter->setStyle(
    Rule\Constants::GROUP_VARIABLE,
    'color: #007694; font-weight: 900;'
);

echo $highlighter->highlightString($ruleStr);
bash
$ composer