NodeDumperTest.php 2.3 KB

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