1 <?php declare(strict_types=1);
5 use PhpParser\Node\Expr;
6 use PhpParser\Node\Scalar;
7 use PHPUnit\Framework\TestCase;
9 class ConstExprEvaluatorTest extends TestCase
11 /** @dataProvider provideTestEvaluate */
12 public function testEvaluate($exprString, $expected) {
13 $parser = new Parser\Php7(new Lexer());
14 $expr = $parser->parse('<?php ' . $exprString . ';')[0]->expr;
15 $evaluator = new ConstExprEvaluator();
16 $this->assertSame($expected, $evaluator->evaluateDirectly($expr));
19 public function provideTestEvaluate() {
25 ['["foo" => "bar"]', ["foo" => "bar"]],
35 ['true ? 1 : (1/0)', 1],
36 ['false ? (1/0) : 1', 1],
39 ['false ?? 42', false],
43 ['0b11 & 0b10', 0b10],
44 ['0b11 | 0b10', 0b11],
45 ['0b11 ^ 0b10', 0b01],
64 ['true && true', true],
65 ['true and true', true],
66 ['false && (1/0)', false],
67 ['false and (1/0)', false],
68 ['false || false', false],
69 ['false or false', false],
70 ['true || (1/0)', true],
71 ['true or (1/0)', true],
72 ['true xor false', true],
77 * @expectedException \PhpParser\ConstExprEvaluationException
78 * @expectedExceptionMessage Expression of type Expr_Variable cannot be evaluated
80 public function testEvaluateFails() {
81 $evaluator = new ConstExprEvaluator();
82 $evaluator->evaluateDirectly(new Expr\Variable('a'));
85 public function testEvaluateFallback() {
86 $evaluator = new ConstExprEvaluator(function(Expr $expr) {
87 if ($expr instanceof Scalar\MagicConst\Line) {
90 throw new ConstExprEvaluationException();
92 $expr = new Expr\BinaryOp\Plus(
93 new Scalar\LNumber(8),
94 new Scalar\MagicConst\Line()
96 $this->assertSame(50, $evaluator->evaluateDirectly($expr));
100 * @dataProvider provideTestEvaluateSilently
102 public function testEvaluateSilently($expr, $exception, $msg) {
103 $evaluator = new ConstExprEvaluator();
106 $evaluator->evaluateSilently($expr);
107 } catch (ConstExprEvaluationException $e) {
109 'An error occurred during constant expression evaluation',
113 $prev = $e->getPrevious();
114 $this->assertInstanceOf($exception, $prev);
115 $this->assertSame($msg, $prev->getMessage());
119 public function provideTestEvaluateSilently() {
122 new Expr\BinaryOp\Mod(new Scalar\LNumber(42), new Scalar\LNumber(0)),
127 new Expr\BinaryOp\Div(new Scalar\LNumber(42), new Scalar\LNumber(0)),
128 \ErrorException::class,