NodeDumperTest.php 2.4 KB

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