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 protected function parse($code, $prefix = '<?php ')
26 $code = $prefix . $code;
28 return $this->getParser()->parse($code);
29 } catch (\PhpParser\Error $e) {
30 if (!$this->parseErrorIsEOF($e)) {
31 throw ParseErrorException::fromParseError($e);
35 // Unexpected EOF, try again with an implicit semicolon
36 return $this->getParser()->parse($code . ';');
37 } catch (\PhpParser\Error $e) {
43 protected function traverse(array $stmts)
45 if (!isset($this->traverser)) {
46 throw new \RuntimeException('Test cases must provide a traverser');
49 return $this->traverser->traverse($stmts);
52 protected function prettyPrint(array $stmts)
54 return $this->getPrinter()->prettyPrint($stmts);
57 protected function assertProcessesAs($from, $to)
59 $stmts = $this->parse($from);
60 $stmts = $this->traverse($stmts);
61 $this->assertSame($to, $this->prettyPrint($stmts));
64 private function getParser()
66 if (!isset($this->parser)) {
67 $parserFactory = new ParserFactory();
68 $this->parser = $parserFactory->createParser();
74 private function getPrinter()
76 if (!isset($this->printer)) {
77 $this->printer = new Printer();
80 return $this->printer;
83 private function parseErrorIsEOF(\PhpParser\Error $e)
85 $msg = $e->getRawMessage();
87 return ($msg === 'Unexpected token EOF') || (strpos($msg, 'Syntax error, unexpected EOF') !== false);