PHP code example of kevintherm / exprc

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

    

kevintherm / exprc example snippets




use Kevintherm\Exprc\Exprc;

$exprc = new Exprc();

$rule = "user.status = 'active' AND score >= 42";
$record = [
    'user' => ['status' => 'active'],
    'score' => 100,
];

$matches = $exprc->matches($rule, $record);
// true



use Kevintherm\Exprc\Exprc;
use Kevintherm\Exprc\Evaluators\InMemoryEpvaluator;
use Kevintherm\Exprc\Evaluators\CallbackEvaluator;

$exprc = new Exprc();
$ast = $exprc->parse("status IN ['active','pending'] AND tags CONTAINS 'beta'");

$inMemory = InMemoryEvaluator::for([
    'status' => 'active',
    'tags' => ['beta', 'pro'],
])->evaluate($ast);

$callback = CallbackEvaluator::for(function ($comparison): bool {
    return $comparison->field === 'status' && $comparison->value === 'active';
})->evaluate($ast);



use Kevintherm\Exprc\Exprc;
use Kevintherm\Exprc\Resolvers\CollectionFieldResolver;

$exprc = new Exprc();
$ast = $exprc->parse("metadata['version'] = 'v2' AND tags CONTAINS 'beta'");

$resolver = new CollectionFieldResolver(
    tableAlias: 'r',
    fieldMap: [
        'status' => 'state',
    ],
);

$query = DB::table('rules as r');
QueryBuilderEvaluator::for($query, $resolver)->evaluate($ast);

$results = $query->get();

use Kevintherm\Exprc\Ast\VisitorInterface;
use Kevintherm\Exprc\Ast\ComparisonNode;

class RelationshipFinder implements VisitorInterface {
    public array $relationships = [];
    
    public function visitComparisonNode(ComparisonNode $node): mixed {
        if (str_contains($node->field, '.')) {
            $this->relationships[] = explode('.', $node->field)[0];
        }
        return null;
    }
    // ... implement other methods
}

$finder = new RelationshipFinder();
$ast->accept($finder);
// $finder->relationships now contains all base relations found in the rule

class MyEvaluator extends InMemoryEvaluator {
    public function beforeProcessNode(Node $node): void {
        // Intercept node before evaluation
    }

    public function afterProcessNode(Node $node, mixed $result): void {
        // Log or transform result
    }
}