-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
ConstantEvaluator.php
50 lines (41 loc) · 1.41 KB
/
ConstantEvaluator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
declare(strict_types=1);
namespace phpDocumentor\Reflection\Php\ValueEvaluator;
use phpDocumentor\Reflection\Php\Factory\ContextStack;
use PhpParser\ConstExprEvaluationException;
use PhpParser\ConstExprEvaluator;
use PhpParser\Node;
use PhpParser\Node\Expr;
use function sprintf;
/**
* @internal
*/
final class ConstantEvaluator
{
/** @throws ConstExprEvaluationException */
public function evaluate(Expr $expr, ContextStack $contextStack): string
{
// @codeCoverageIgnoreStart
$evaluator = new ConstExprEvaluator(function (Expr $expr) use ($contextStack) {
return $this->evaluateFallback($expr, $contextStack);
});
return $evaluator->evaluateSilently($expr);
// @codeCoverageIgnoreEnd
}
/** @throws ConstExprEvaluationException */
private function evaluateFallback(Expr $expr, ContextStack $contextStack): string
{
$typeContext = $contextStack->getTypeContext();
if ($typeContext === null) {
throw new ConstExprEvaluationException(
sprintf('Expression of type %s cannot be evaluated', $expr->getType())
);
}
if ($expr instanceof Node\Scalar\MagicConst\Namespace_) {
return $typeContext->getNamespace();
}
throw new ConstExprEvaluationException(
sprintf('Expression of type %s cannot be evaluated', $expr->getType())
);
}
}