1<?php declare(strict_types=1);
2
3namespace PhpParser;
4
5class NodeDumperTest extends \PHPUnit\Framework\TestCase {
6    private function canonicalize($string) {
7        return str_replace("\r\n", "\n", $string);
8    }
9
10    /**
11     * @dataProvider provideTestDump
12     */
13    public function testDump($node, $dump): void {
14        $dumper = new NodeDumper();
15
16        $this->assertSame($this->canonicalize($dump), $this->canonicalize($dumper->dump($node)));
17    }
18
19    public static function provideTestDump() {
20        return [
21            [
22                [],
23'array(
24)'
25            ],
26            [
27                ['Foo', 'Bar', 'Key' => 'FooBar'],
28'array(
29    0: Foo
30    1: Bar
31    Key: FooBar
32)'
33            ],
34            [
35                new Node\Name(['Hallo', 'World']),
36'Name(
37    name: Hallo\World
38)'
39            ],
40            [
41                new Node\Expr\Array_([
42                    new Node\ArrayItem(new Node\Scalar\String_('Foo'))
43                ]),
44'Expr_Array(
45    items: array(
46        0: ArrayItem(
47            key: null
48            value: Scalar_String(
49                value: Foo
50            )
51            byRef: false
52            unpack: false
53        )
54    )
55)'
56            ],
57        ];
58    }
59
60    public function testDumpWithPositions(): void {
61        $parser = (new ParserFactory())->createForHostVersion();
62        $dumper = new NodeDumper(['dumpPositions' => true]);
63
64        $code = "<?php\n\$a = 1;\necho \$a;";
65        $expected = <<<'OUT'
66array(
67    0: Stmt_Expression[2:1 - 2:7](
68        expr: Expr_Assign[2:1 - 2:6](
69            var: Expr_Variable[2:1 - 2:2](
70                name: a
71            )
72            expr: Scalar_Int[2:6 - 2:6](
73                value: 1
74            )
75        )
76    )
77    1: Stmt_Echo[3:1 - 3:8](
78        exprs: array(
79            0: Expr_Variable[3:6 - 3:7](
80                name: a
81            )
82        )
83    )
84)
85OUT;
86
87        $stmts = $parser->parse($code);
88        $dump = $dumper->dump($stmts, $code);
89
90        $this->assertSame($this->canonicalize($expected), $this->canonicalize($dump));
91    }
92
93    public function testError(): void {
94        $this->expectException(\InvalidArgumentException::class);
95        $this->expectExceptionMessage('Can only dump nodes and arrays.');
96        $dumper = new NodeDumper();
97        $dumper->dump(new \stdClass());
98    }
99}
100