4 * This file is part of Psy Shell.
6 * (c) 2012-2017 Justin Hileman
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Psy\Test\CodeCleaner;
14 use PhpParser\NodeTraverser;
15 use PhpParser\PrettyPrinter\Standard as Printer;
16 use Psy\CodeCleaner\CodeCleanerPass;
17 use Psy\Exception\ParseErrorException;
18 use Psy\ParserFactory;
20 class CodeCleanerTestCase extends \PHPUnit\Framework\TestCase
27 protected function setPass(CodeCleanerPass $pass)
30 if (!isset($this->traverser)) {
31 $this->traverser = new NodeTraverser();
33 $this->traverser->addVisitor($this->pass);
36 protected function parse($code, $prefix = '<?php ')
38 $code = $prefix . $code;
40 return $this->getParser()->parse($code);
41 } catch (\PhpParser\Error $e) {
42 if (!$this->parseErrorIsEOF($e)) {
43 throw ParseErrorException::fromParseError($e);
47 // Unexpected EOF, try again with an implicit semicolon
48 return $this->getParser()->parse($code . ';');
49 } catch (\PhpParser\Error $e) {
55 protected function traverse(array $stmts)
57 return $this->traverser->traverse($stmts);
60 protected function prettyPrint(array $stmts)
62 return $this->getPrinter()->prettyPrint($stmts);
65 protected function assertProcessesAs($from, $to)
67 $stmts = $this->parse($from);
68 $stmts = $this->traverse($stmts);
69 $this->assertEquals($to, $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);