NodeDumperTest.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php declare(strict_types=1);
  2. namespace PhpParser;
  3. use PHPUnit\Framework\TestCase;
  4. class NodeDumperTest extends TestCase
  5. {
  6. private function canonicalize($string) {
  7. return str_replace("\r\n", "\n", $string);
  8. }
  9. /**
  10. * @dataProvider provideTestDump
  11. */
  12. public function testDump($node, $dump) {
  13. $dumper = new NodeDumper;
  14. $this->assertSame($this->canonicalize($dump), $this->canonicalize($dumper->dump($node)));
  15. }
  16. public function provideTestDump() {
  17. return [
  18. [
  19. [],
  20. 'array(
  21. )'
  22. ],
  23. [
  24. ['Foo', 'Bar', 'Key' => 'FooBar'],
  25. 'array(
  26. 0: Foo
  27. 1: Bar
  28. Key: FooBar
  29. )'
  30. ],
  31. [
  32. new Node\Name(['Hallo', 'World']),
  33. 'Name(
  34. parts: array(
  35. 0: Hallo
  36. 1: World
  37. )
  38. )'
  39. ],
  40. [
  41. new Node\Expr\Array_([
  42. new Node\Expr\ArrayItem(new Node\Scalar\String_('Foo'))
  43. ]),
  44. 'Expr_Array(
  45. items: array(
  46. 0: Expr_ArrayItem(
  47. key: null
  48. value: Scalar_String(
  49. value: Foo
  50. )
  51. byRef: false
  52. )
  53. )
  54. )'
  55. ],
  56. ];
  57. }
  58. public function testDumpWithPositions() {
  59. $parser = (new ParserFactory)->create(
  60. ParserFactory::ONLY_PHP7,
  61. new Lexer(['usedAttributes' => ['startLine', 'endLine', 'startFilePos', 'endFilePos']])
  62. );
  63. $dumper = new NodeDumper(['dumpPositions' => true]);
  64. $code = "<?php\n\$a = 1;\necho \$a;";
  65. $expected = <<<'OUT'
  66. array(
  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_LNumber[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. )
  85. OUT;
  86. $stmts = $parser->parse($code);
  87. $dump = $dumper->dump($stmts, $code);
  88. $this->assertSame($this->canonicalize($expected), $this->canonicalize($dump));
  89. }
  90. public function testError() {
  91. $this->expectException(\InvalidArgumentException::class);
  92. $this->expectExceptionMessage('Can only dump nodes and arrays.');
  93. $dumper = new NodeDumper;
  94. $dumper->dump(new \stdClass);
  95. }
  96. }