CodeParsingTest.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace PhpParser;
  3. require_once __DIR__ . '/CodeTestAbstract.php';
  4. class CodeParsingTest extends CodeTestAbstract
  5. {
  6. /**
  7. * @dataProvider provideTestParse
  8. */
  9. public function testParse($name, $code, $expected, $modeLine) {
  10. if (null !== $modeLine) {
  11. $modes = array_fill_keys(explode(',', $modeLine), true);
  12. } else {
  13. $modes = [];
  14. }
  15. $lexer = new Lexer\Emulative(array('usedAttributes' => array(
  16. 'startLine', 'endLine', 'startFilePos', 'endFilePos', 'comments'
  17. )));
  18. $parser5 = new Parser\Php5($lexer);
  19. $parser7 = new Parser\Php7($lexer);
  20. $dumpPositions = isset($modes['positions']);
  21. $output5 = $this->getParseOutput($parser5, $code, $dumpPositions);
  22. $output7 = $this->getParseOutput($parser7, $code, $dumpPositions);
  23. if (isset($modes['php5'])) {
  24. $this->assertSame($expected, $output5, $name);
  25. $this->assertNotSame($expected, $output7, $name);
  26. } else if (isset($modes['php7'])) {
  27. $this->assertNotSame($expected, $output5, $name);
  28. $this->assertSame($expected, $output7, $name);
  29. } else {
  30. $this->assertSame($expected, $output5, $name);
  31. $this->assertSame($expected, $output7, $name);
  32. }
  33. }
  34. private function getParseOutput(Parser $parser, $code, $dumpPositions) {
  35. $errors = new ErrorHandler\Collecting;
  36. $stmts = $parser->parse($code, $errors);
  37. $output = '';
  38. foreach ($errors->getErrors() as $error) {
  39. $output .= $this->formatErrorMessage($error, $code) . "\n";
  40. }
  41. if (null !== $stmts) {
  42. $dumper = new NodeDumper(['dumpComments' => true, 'dumpPositions' => $dumpPositions]);
  43. $output .= $dumper->dump($stmts, $code);
  44. }
  45. return canonicalize($output);
  46. }
  47. public function provideTestParse() {
  48. return $this->getTests(__DIR__ . '/../code/parser', 'test');
  49. }
  50. private function formatErrorMessage(Error $e, $code) {
  51. if ($e->hasColumnInfo()) {
  52. return $e->getMessageWithColumnInfo($code);
  53. } else {
  54. return $e->getMessage();
  55. }
  56. }
  57. }