|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* Copyright 2016 Johannes M. Schmitt <[email protected]> |
|
5
|
|
|
* |
|
6
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
|
7
|
|
|
* you may not use this file except in compliance with the License. |
|
8
|
|
|
* You may obtain a copy of the License at |
|
9
|
|
|
* |
|
10
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0 |
|
11
|
|
|
* |
|
12
|
|
|
* Unless required by applicable law or agreed to in writing, software |
|
13
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS, |
|
14
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
15
|
|
|
* See the License for the specific language governing permissions and |
|
16
|
|
|
* limitations under the License. |
|
17
|
|
|
*/ |
|
18
|
|
|
|
|
19
|
|
|
namespace JMS\Serializer\Expression; |
|
20
|
|
|
|
|
21
|
|
|
use Symfony\Component\ExpressionLanguage\ExpressionLanguage; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @author Asmir Mustafic <[email protected]> |
|
25
|
|
|
*/ |
|
26
|
|
|
class ExpressionEvaluator implements ExpressionEvaluatorInterface |
|
27
|
|
|
{ |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* @var ExpressionLanguage |
|
31
|
|
|
*/ |
|
32
|
|
|
private $expressionLanguage; |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* @var array |
|
36
|
|
|
*/ |
|
37
|
|
|
private $context = array(); |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* @var array |
|
41
|
|
|
*/ |
|
42
|
|
|
private $cache = array(); |
|
43
|
|
|
|
|
44
|
33 |
|
public function __construct(ExpressionLanguage $expressionLanguage, array $context = array(), array $cache = array()) |
|
45
|
|
|
{ |
|
46
|
33 |
|
$this->expressionLanguage = $expressionLanguage; |
|
47
|
33 |
|
$this->context = $context; |
|
48
|
33 |
|
$this->cache = $cache; |
|
49
|
33 |
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* @param string $name |
|
53
|
|
|
* @param mixed $value |
|
54
|
|
|
*/ |
|
55
|
|
|
public function setContextVariable($name, $value) |
|
56
|
|
|
{ |
|
57
|
|
|
$this->context[$name] = $value; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* @param string $expression |
|
62
|
|
|
* @param array $data |
|
63
|
|
|
* @return mixed |
|
64
|
|
|
*/ |
|
65
|
33 |
|
public function evaluate($expression, array $data = array()) |
|
66
|
|
|
{ |
|
67
|
33 |
|
if (!is_string($expression)) { |
|
68
|
|
|
return $expression; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
33 |
|
$context = $data + $this->context; |
|
72
|
|
|
|
|
73
|
33 |
|
if (!array_key_exists($expression, $this->cache)) { |
|
74
|
33 |
|
$this->cache[$expression] = $this->expressionLanguage->parse($expression, array_keys($context)); |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
33 |
|
return $this->expressionLanguage->evaluate($this->cache[$expression], $context); |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|