菜谱项目

NodeDumperTest.php 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  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 array(
  17. array(
  18. array(),
  19. 'array(
  20. )'
  21. ),
  22. array(
  23. array('Foo', 'Bar', 'Key' => 'FooBar'),
  24. 'array(
  25. 0: Foo
  26. 1: Bar
  27. Key: FooBar
  28. )'
  29. ),
  30. array(
  31. new Node\Name(array('Hallo', 'World')),
  32. 'Name(
  33. parts: array(
  34. 0: Hallo
  35. 1: World
  36. )
  37. )'
  38. ),
  39. array(
  40. new Node\Expr\Array_(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: Expr_Assign[2:1 - 2:6](
  67. var: Expr_Variable[2:1 - 2:2](
  68. name: a
  69. )
  70. expr: Scalar_LNumber[2:6 - 2:6](
  71. value: 1
  72. )
  73. )
  74. 1: Stmt_Echo[3:1 - 3:8](
  75. exprs: array(
  76. 0: Expr_Variable[3:6 - 3:7](
  77. name: a
  78. )
  79. )
  80. )
  81. )
  82. OUT;
  83. $stmts = $parser->parse($code);
  84. $dump = $dumper->dump($stmts, $code);
  85. $this->assertSame($this->canonicalize($expected), $this->canonicalize($dump));
  86. }
  87. /**
  88. * @expectedException \InvalidArgumentException
  89. * @expectedExceptionMessage Can only dump nodes and arrays.
  90. */
  91. public function testError() {
  92. $dumper = new NodeDumper;
  93. $dumper->dump(new \stdClass);
  94. }
  95. }