47 lines
1.1 KiB
PHP
47 lines
1.1 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace App\Services;
|
||
|
|
|
||
|
|
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
|
||
|
|
use Symfony\Component\ExpressionLanguage\ParsedExpression;
|
||
|
|
|
||
|
|
class RuleExpressionService
|
||
|
|
{
|
||
|
|
protected ExpressionLanguage $language;
|
||
|
|
|
||
|
|
/** @var array<string, ParsedExpression> */
|
||
|
|
protected array $parsedCache = [];
|
||
|
|
|
||
|
|
public function __construct()
|
||
|
|
{
|
||
|
|
$this->language = new ExpressionLanguage();
|
||
|
|
}
|
||
|
|
|
||
|
|
public function evaluate(string $expr, array $context = [])
|
||
|
|
{
|
||
|
|
$expr = trim($expr);
|
||
|
|
if ($expr === '') {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
$names = array_keys($context);
|
||
|
|
sort($names);
|
||
|
|
$cacheKey = md5($expr . '|' . implode(',', $names));
|
||
|
|
|
||
|
|
if (!isset($this->parsedCache[$cacheKey])) {
|
||
|
|
$this->parsedCache[$cacheKey] = $this->language->parse($expr, $names);
|
||
|
|
}
|
||
|
|
|
||
|
|
return $this->language->evaluate($this->parsedCache[$cacheKey], $context);
|
||
|
|
}
|
||
|
|
|
||
|
|
public function evaluateBoolean(?string $expr, array $context = []): bool
|
||
|
|
{
|
||
|
|
if ($expr === null || trim($expr) === '') {
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
|
||
|
|
return (bool) $this->evaluate($expr, $context);
|
||
|
|
}
|
||
|
|
}
|