ParserTestCase.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /*
  3. * This file is part of Psy Shell.
  4. *
  5. * (c) 2012-2023 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 TestCase
  15. {
  16. protected $traverser;
  17. private $parser;
  18. private $printer;
  19. /**
  20. * @after
  21. */
  22. public function clearProperties()
  23. {
  24. $this->traverser = null;
  25. $this->parser = null;
  26. $this->printer = null;
  27. }
  28. protected function parse($code, $prefix = '<?php ')
  29. {
  30. $code = $prefix.$code;
  31. try {
  32. return $this->getParser()->parse($code);
  33. } catch (\PhpParser\Error $e) {
  34. if (!$this->parseErrorIsEOF($e)) {
  35. throw ParseErrorException::fromParseError($e);
  36. }
  37. try {
  38. // Unexpected EOF, try again with an implicit semicolon
  39. return $this->getParser()->parse($code.';');
  40. } catch (\PhpParser\Error $e) {
  41. return false;
  42. }
  43. }
  44. }
  45. protected function traverse(array $stmts)
  46. {
  47. if (!isset($this->traverser)) {
  48. throw new \RuntimeException('Test cases must provide a traverser');
  49. }
  50. return $this->traverser->traverse($stmts);
  51. }
  52. protected function prettyPrint(array $stmts)
  53. {
  54. return $this->getPrinter()->prettyPrint($stmts);
  55. }
  56. protected function assertProcessesAs($from, $to)
  57. {
  58. $stmts = $this->parse($from);
  59. $stmts = $this->traverse($stmts);
  60. $toStmts = $this->parse($to);
  61. $this->assertSame($this->prettyPrint($toStmts), $this->prettyPrint($stmts));
  62. }
  63. private function getParser()
  64. {
  65. if (!isset($this->parser)) {
  66. $parserFactory = new ParserFactory();
  67. $this->parser = $parserFactory->createParser();
  68. }
  69. return $this->parser;
  70. }
  71. private function getPrinter()
  72. {
  73. if (!isset($this->printer)) {
  74. $this->printer = new Printer();
  75. }
  76. return $this->printer;
  77. }
  78. private function parseErrorIsEOF(\PhpParser\Error $e)
  79. {
  80. $msg = $e->getRawMessage();
  81. return ($msg === 'Unexpected token EOF') || (\strpos($msg, 'Syntax error, unexpected EOF') !== false);
  82. }
  83. }