1: <?php declare(strict_types=1);
2:
3: namespace PhpParser;
4:
5: use PhpParser\Node\Expr;
6: use PhpParser\Node\Scalar;
7:
8: /**
9: * Evaluates constant expressions.
10: *
11: * This evaluator is able to evaluate all constant expressions (as defined by PHP), which can be
12: * evaluated without further context. If a subexpression is not of this type, a user-provided
13: * fallback evaluator is invoked. To support all constant expressions that are also supported by
14: * PHP (and not already handled by this class), the fallback evaluator must be able to handle the
15: * following node types:
16: *
17: * * All Scalar\MagicConst\* nodes.
18: * * Expr\ConstFetch nodes. Only null/false/true are already handled by this class.
19: * * Expr\ClassConstFetch nodes.
20: *
21: * The fallback evaluator should throw ConstExprEvaluationException for nodes it cannot evaluate.
22: *
23: * The evaluation is dependent on runtime configuration in two respects: Firstly, floating
24: * point to string conversions are affected by the precision ini setting. Secondly, they are also
25: * affected by the LC_NUMERIC locale.
26: */
27: class ConstExprEvaluator {
28: /** @var callable|null */
29: private $fallbackEvaluator;
30:
31: /**
32: * Create a constant expression evaluator.
33: *
34: * The provided fallback evaluator is invoked whenever a subexpression cannot be evaluated. See
35: * class doc comment for more information.
36: *
37: * @param callable|null $fallbackEvaluator To call if subexpression cannot be evaluated
38: */
39: public function __construct(?callable $fallbackEvaluator = null) {
40: $this->fallbackEvaluator = $fallbackEvaluator ?? function (Expr $expr) {
41: throw new ConstExprEvaluationException(
42: "Expression of type {$expr->getType()} cannot be evaluated"
43: );
44: };
45: }
46:
47: /**
48: * Silently evaluates a constant expression into a PHP value.
49: *
50: * Thrown Errors, warnings or notices will be converted into a ConstExprEvaluationException.
51: * The original source of the exception is available through getPrevious().
52: *
53: * If some part of the expression cannot be evaluated, the fallback evaluator passed to the
54: * constructor will be invoked. By default, if no fallback is provided, an exception of type
55: * ConstExprEvaluationException is thrown.
56: *
57: * See class doc comment for caveats and limitations.
58: *
59: * @param Expr $expr Constant expression to evaluate
60: * @return mixed Result of evaluation
61: *
62: * @throws ConstExprEvaluationException if the expression cannot be evaluated or an error occurred
63: */
64: public function evaluateSilently(Expr $expr) {
65: set_error_handler(function ($num, $str, $file, $line) {
66: throw new \ErrorException($str, 0, $num, $file, $line);
67: });
68:
69: try {
70: return $this->evaluate($expr);
71: } catch (\Throwable $e) {
72: if (!$e instanceof ConstExprEvaluationException) {
73: $e = new ConstExprEvaluationException(
74: "An error occurred during constant expression evaluation", 0, $e);
75: }
76: throw $e;
77: } finally {
78: restore_error_handler();
79: }
80: }
81:
82: /**
83: * Directly evaluates a constant expression into a PHP value.
84: *
85: * May generate Error exceptions, warnings or notices. Use evaluateSilently() to convert these
86: * into a ConstExprEvaluationException.
87: *
88: * If some part of the expression cannot be evaluated, the fallback evaluator passed to the
89: * constructor will be invoked. By default, if no fallback is provided, an exception of type
90: * ConstExprEvaluationException is thrown.
91: *
92: * See class doc comment for caveats and limitations.
93: *
94: * @param Expr $expr Constant expression to evaluate
95: * @return mixed Result of evaluation
96: *
97: * @throws ConstExprEvaluationException if the expression cannot be evaluated
98: */
99: public function evaluateDirectly(Expr $expr) {
100: return $this->evaluate($expr);
101: }
102:
103: /** @return mixed */
104: private function evaluate(Expr $expr) {
105: if ($expr instanceof Scalar\Int_
106: || $expr instanceof Scalar\Float_
107: || $expr instanceof Scalar\String_
108: ) {
109: return $expr->value;
110: }
111:
112: if ($expr instanceof Expr\Array_) {
113: return $this->evaluateArray($expr);
114: }
115:
116: // Unary operators
117: if ($expr instanceof Expr\UnaryPlus) {
118: return +$this->evaluate($expr->expr);
119: }
120: if ($expr instanceof Expr\UnaryMinus) {
121: return -$this->evaluate($expr->expr);
122: }
123: if ($expr instanceof Expr\BooleanNot) {
124: return !$this->evaluate($expr->expr);
125: }
126: if ($expr instanceof Expr\BitwiseNot) {
127: return ~$this->evaluate($expr->expr);
128: }
129:
130: if ($expr instanceof Expr\BinaryOp) {
131: return $this->evaluateBinaryOp($expr);
132: }
133:
134: if ($expr instanceof Expr\Ternary) {
135: return $this->evaluateTernary($expr);
136: }
137:
138: if ($expr instanceof Expr\ArrayDimFetch && null !== $expr->dim) {
139: return $this->evaluate($expr->var)[$this->evaluate($expr->dim)];
140: }
141:
142: if ($expr instanceof Expr\ConstFetch) {
143: return $this->evaluateConstFetch($expr);
144: }
145:
146: return ($this->fallbackEvaluator)($expr);
147: }
148:
149: private function evaluateArray(Expr\Array_ $expr): array {
150: $array = [];
151: foreach ($expr->items as $item) {
152: if (null !== $item->key) {
153: $array[$this->evaluate($item->key)] = $this->evaluate($item->value);
154: } elseif ($item->unpack) {
155: $unpacked = $this->evaluate($item->value);
156: if (!is_array($unpacked)) {
157: throw new \Error('Only arrays can be unpacked in constant expression');
158: }
159: foreach ($unpacked as $key => $value) {
160: if (is_int($key)) {
161: $array[] = $value;
162: } else {
163: $array[$key] = $value;
164: }
165: }
166: } else {
167: $array[] = $this->evaluate($item->value);
168: }
169: }
170: return $array;
171: }
172:
173: /** @return mixed */
174: private function evaluateTernary(Expr\Ternary $expr) {
175: if (null === $expr->if) {
176: return $this->evaluate($expr->cond) ?: $this->evaluate($expr->else);
177: }
178:
179: return $this->evaluate($expr->cond)
180: ? $this->evaluate($expr->if)
181: : $this->evaluate($expr->else);
182: }
183:
184: /** @return mixed */
185: private function evaluateBinaryOp(Expr\BinaryOp $expr) {
186: if ($expr instanceof Expr\BinaryOp\Coalesce
187: && $expr->left instanceof Expr\ArrayDimFetch
188: ) {
189: // This needs to be special cased to respect BP_VAR_IS fetch semantics
190: return $this->evaluate($expr->left->var)[$this->evaluate($expr->left->dim)]
191: ?? $this->evaluate($expr->right);
192: }
193:
194: // The evaluate() calls are repeated in each branch, because some of the operators are
195: // short-circuiting and evaluating the RHS in advance may be illegal in that case
196: $l = $expr->left;
197: $r = $expr->right;
198: switch ($expr->getOperatorSigil()) {
199: case '&': return $this->evaluate($l) & $this->evaluate($r);
200: case '|': return $this->evaluate($l) | $this->evaluate($r);
201: case '^': return $this->evaluate($l) ^ $this->evaluate($r);
202: case '&&': return $this->evaluate($l) && $this->evaluate($r);
203: case '||': return $this->evaluate($l) || $this->evaluate($r);
204: case '??': return $this->evaluate($l) ?? $this->evaluate($r);
205: case '.': return $this->evaluate($l) . $this->evaluate($r);
206: case '/': return $this->evaluate($l) / $this->evaluate($r);
207: case '==': return $this->evaluate($l) == $this->evaluate($r);
208: case '>': return $this->evaluate($l) > $this->evaluate($r);
209: case '>=': return $this->evaluate($l) >= $this->evaluate($r);
210: case '===': return $this->evaluate($l) === $this->evaluate($r);
211: case 'and': return $this->evaluate($l) and $this->evaluate($r);
212: case 'or': return $this->evaluate($l) or $this->evaluate($r);
213: case 'xor': return $this->evaluate($l) xor $this->evaluate($r);
214: case '-': return $this->evaluate($l) - $this->evaluate($r);
215: case '%': return $this->evaluate($l) % $this->evaluate($r);
216: case '*': return $this->evaluate($l) * $this->evaluate($r);
217: case '!=': return $this->evaluate($l) != $this->evaluate($r);
218: case '!==': return $this->evaluate($l) !== $this->evaluate($r);
219: case '+': return $this->evaluate($l) + $this->evaluate($r);
220: case '**': return $this->evaluate($l) ** $this->evaluate($r);
221: case '<<': return $this->evaluate($l) << $this->evaluate($r);
222: case '>>': return $this->evaluate($l) >> $this->evaluate($r);
223: case '<': return $this->evaluate($l) < $this->evaluate($r);
224: case '<=': return $this->evaluate($l) <= $this->evaluate($r);
225: case '<=>': return $this->evaluate($l) <=> $this->evaluate($r);
226: case '|>': return ($this->fallbackEvaluator)($expr);
227: }
228:
229: throw new \Exception('Should not happen');
230: }
231:
232: /** @return mixed */
233: private function evaluateConstFetch(Expr\ConstFetch $expr) {
234: $name = $expr->name->toLowerString();
235: switch ($name) {
236: case 'null': return null;
237: case 'false': return false;
238: case 'true': return true;
239: }
240:
241: return ($this->fallbackEvaluator)($expr);
242: }
243: }
244: