1<?php
2
3declare(strict_types=1);
4
5namespace JMS\Serializer\Expression;
6
7use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
8
9/**
10 * @author Asmir Mustafic <goetas@gmail.com>
11 */
12class ExpressionEvaluator implements CompilableExpressionEvaluatorInterface, ExpressionEvaluatorInterface
13{
14    /**
15     * @var ExpressionLanguage
16     */
17    private $expressionLanguage;
18
19    /**
20     * @var array
21     */
22    private $context = [];
23
24    public function __construct(ExpressionLanguage $expressionLanguage, array $context = [])
25    {
26        $this->expressionLanguage = $expressionLanguage;
27        $this->context = $context;
28    }
29
30    /**
31     * @param mixed $value
32     */
33    public function setContextVariable(string $name, $value): void
34    {
35        $this->context[$name] = $value;
36    }
37
38    /**
39     * @return mixed
40     */
41    public function evaluate(string $expression, array $data = [])
42    {
43        return $this->expressionLanguage->evaluate($expression, $data + $this->context);
44    }
45
46    /**
47     * @return mixed
48     */
49    public function evaluateParsed(Expression $expression, array $data = [])
50    {
51        return $this->expressionLanguage->evaluate($expression->getExpression(), $data + $this->context);
52    }
53
54    public function parse(string $expression, array $names = []): Expression
55    {
56        return new Expression($this->expressionLanguage->parse($expression, array_merge(array_keys($this->context), $names)));
57    }
58}
59