ParserTestCase.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. /*
  3. * This file is part of Psy Shell.
  4. *
  5. * (c) 2012-2018 Justin Hileman
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Psy\Test;
  11. use PhpParser\PrettyPrinter\Standard as Printer;
  12. use Psy\Exception\ParseErrorException;
  13. use Psy\ParserFactory;
  14. class ParserTestCase extends \PHPUnit\Framework\TestCase
  15. {
  16. protected $traverser;
  17. private $parser;
  18. private $printer;
  19. public function tearDown()
  20. {
  21. $this->traverser = null;
  22. $this->parser = null;
  23. $this->printer = null;
  24. }
  25. protected function parse($code, $prefix = '<?php ')
  26. {
  27. $code = $prefix . $code;
  28. try {
  29. return $this->getParser()->parse($code);
  30. } catch (\PhpParser\Error $e) {
  31. if (!$this->parseErrorIsEOF($e)) {
  32. throw ParseErrorException::fromParseError($e);
  33. }
  34. try {
  35. // Unexpected EOF, try again with an implicit semicolon
  36. return $this->getParser()->parse($code . ';');
  37. } catch (\PhpParser\Error $e) {
  38. return false;
  39. }
  40. }
  41. }
  42. protected function traverse(array $stmts)
  43. {
  44. if (!isset($this->traverser)) {
  45. throw new \RuntimeException('Test cases must provide a traverser');
  46. }
  47. return $this->traverser->traverse($stmts);
  48. }
  49. protected function prettyPrint(array $stmts)
  50. {
  51. return $this->getPrinter()->prettyPrint($stmts);
  52. }
  53. protected function assertProcessesAs($from, $to)
  54. {
  55. $stmts = $this->parse($from);
  56. $stmts = $this->traverse($stmts);
  57. $toStmts = $this->parse($to);
  58. $this->assertSame($this->prettyPrint($toStmts), $this->prettyPrint($stmts));
  59. }
  60. private function getParser()
  61. {
  62. if (!isset($this->parser)) {
  63. $parserFactory = new ParserFactory();
  64. $this->parser = $parserFactory->createParser();
  65. }
  66. return $this->parser;
  67. }
  68. private function getPrinter()
  69. {
  70. if (!isset($this->printer)) {
  71. $this->printer = new Printer();
  72. }
  73. return $this->printer;
  74. }
  75. private function parseErrorIsEOF(\PhpParser\Error $e)
  76. {
  77. $msg = $e->getRawMessage();
  78. return ($msg === 'Unexpected token EOF') || (\strpos($msg, 'Syntax error, unexpected EOF') !== false);
  79. }
  80. }