1 | <?php |
||
11 | class ExpressionEvaluator |
||
12 | { |
||
13 | const EXPRESSION_REGEX = '/expr\((?P<expression>.+)\)/'; |
||
14 | |||
15 | /** |
||
16 | * @var ExpressionLanguage |
||
17 | */ |
||
18 | private $expressionLanguage; |
||
19 | |||
20 | /** |
||
21 | * @var array |
||
22 | */ |
||
23 | private $context; |
||
24 | |||
25 | /** |
||
26 | * @var array |
||
27 | */ |
||
28 | private $cache; |
||
29 | |||
30 | public function __construct(ExpressionLanguage $expressionLanguage, array $context = array(), array $cache = array()) |
||
31 | { |
||
32 | $this->expressionLanguage = $expressionLanguage; |
||
33 | $this->context = $context; |
||
34 | $this->cache = $cache; |
||
35 | } |
||
36 | |||
37 | /** |
||
38 | * @param string $name |
||
39 | * @param mixed $value |
||
40 | */ |
||
41 | public function setContextVariable($name, $value) |
||
45 | |||
46 | /** |
||
47 | * @param string $expression |
||
48 | * @param mixed $data |
||
49 | * @return mixed |
||
50 | */ |
||
51 | public function evaluate($expression, $data) |
||
52 | { |
||
53 | if (!is_string($expression)) { |
||
54 | return $expression; |
||
55 | } |
||
56 | |||
57 | $key = $expression; |
||
58 | |||
59 | if (!array_key_exists($key, $this->cache)) { |
||
60 | if (!preg_match(self::EXPRESSION_REGEX, $expression, $matches)) { |
||
61 | $this->cache[$key] = false; |
||
62 | } else { |
||
63 | $expression = $matches['expression']; |
||
64 | $context = $this->context; |
||
65 | $context['object'] = $data; |
||
66 | $this->cache[$key] = $this->expressionLanguage->parse($expression, array_keys($context)); |
||
67 | } |
||
68 | } |
||
69 | |||
70 | if (false !== $this->cache[$key]) { |
||
71 | if (!isset($context)) { |
||
72 | $context = $this->context; |
||
73 | $context['object'] = $data; |
||
74 | } |
||
75 | |||
76 | return $this->expressionLanguage->evaluate($this->cache[$key], $context); |
||
77 | } |
||
78 | |||
79 | return $expression; |
||
80 | } |
||
81 | |||
82 | public function evaluateArray(array $array, $data) |
||
94 | |||
95 | /** |
||
96 | * Register a new new ExpressionLanguage function. |
||
97 | * |
||
98 | * @param ExpressionFunctionInterface $function |
||
99 | * |
||
100 | * @return ExpressionEvaluator |
||
101 | */ |
||
102 | public function registerFunction(ExpressionFunctionInterface $function) |
||
116 | } |
||
117 |