4 * This file is part of Psy Shell.
6 * (c) 2012-2018 Justin Hileman
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
14 use PhpParser\PrettyPrinter\Standard as Printer;
15 use Psy\Exception\ParseErrorException;
16 use Psy\ParserFactory;
18 class ParserTestCase extends \PHPUnit\Framework\TestCase
24 public function tearDown()
26 $this->traverser = null;
28 $this->printer = null;
31 protected function parse($code, $prefix = '<?php ')
33 $code = $prefix . $code;
35 return $this->getParser()->parse($code);
36 } catch (\PhpParser\Error $e) {
37 if (!$this->parseErrorIsEOF($e)) {
38 throw ParseErrorException::fromParseError($e);
42 // Unexpected EOF, try again with an implicit semicolon
43 return $this->getParser()->parse($code . ';');
44 } catch (\PhpParser\Error $e) {
50 protected function traverse(array $stmts)
52 if (!isset($this->traverser)) {
53 throw new \RuntimeException('Test cases must provide a traverser');
56 return $this->traverser->traverse($stmts);
59 protected function prettyPrint(array $stmts)
61 return $this->getPrinter()->prettyPrint($stmts);
64 protected function assertProcessesAs($from, $to)
66 $stmts = $this->parse($from);
67 $stmts = $this->traverse($stmts);
68 $toStmts = $this->parse($to);
69 $this->assertSame($this->prettyPrint($toStmts), $this->prettyPrint($stmts));
72 private function getParser()
74 if (!isset($this->parser)) {
75 $parserFactory = new ParserFactory();
76 $this->parser = $parserFactory->createParser();
82 private function getPrinter()
84 if (!isset($this->printer)) {
85 $this->printer = new Printer();
88 return $this->printer;
91 private function parseErrorIsEOF(\PhpParser\Error $e)
93 $msg = $e->getRawMessage();
95 return ($msg === 'Unexpected token EOF') || (\strpos($msg, 'Syntax error, unexpected EOF') !== false);