Security update for Core, with self-updated composer
[yaffs-website] / vendor / psy / psysh / test / Psy / Test / CodeCleaner / CodeCleanerTestCase.php
1 <?php
2
3 /*
4  * This file is part of Psy Shell.
5  *
6  * (c) 2012-2017 Justin Hileman
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Psy\Test\CodeCleaner;
13
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;
19
20 class CodeCleanerTestCase extends \PHPUnit\Framework\TestCase
21 {
22     protected $pass;
23     protected $traverser;
24     private $parser;
25     private $printer;
26
27     protected function setPass(CodeCleanerPass $pass)
28     {
29         $this->pass = $pass;
30         if (!isset($this->traverser)) {
31             $this->traverser = new NodeTraverser();
32         }
33         $this->traverser->addVisitor($this->pass);
34     }
35
36     protected function parse($code, $prefix = '<?php ')
37     {
38         $code = $prefix . $code;
39         try {
40             return $this->getParser()->parse($code);
41         } catch (\PhpParser\Error $e) {
42             if (!$this->parseErrorIsEOF($e)) {
43                 throw ParseErrorException::fromParseError($e);
44             }
45
46             try {
47                 // Unexpected EOF, try again with an implicit semicolon
48                 return $this->getParser()->parse($code . ';');
49             } catch (\PhpParser\Error $e) {
50                 return false;
51             }
52         }
53     }
54
55     protected function traverse(array $stmts)
56     {
57         return $this->traverser->traverse($stmts);
58     }
59
60     protected function prettyPrint(array $stmts)
61     {
62         return $this->getPrinter()->prettyPrint($stmts);
63     }
64
65     protected function assertProcessesAs($from, $to)
66     {
67         $stmts = $this->parse($from);
68         $stmts = $this->traverse($stmts);
69         $this->assertEquals($to, $this->prettyPrint($stmts));
70     }
71
72     private function getParser()
73     {
74         if (!isset($this->parser)) {
75             $parserFactory = new ParserFactory();
76             $this->parser  = $parserFactory->createParser();
77         }
78
79         return $this->parser;
80     }
81
82     private function getPrinter()
83     {
84         if (!isset($this->printer)) {
85             $this->printer = new Printer();
86         }
87
88         return $this->printer;
89     }
90
91     private function parseErrorIsEOF(\PhpParser\Error $e)
92     {
93         $msg = $e->getRawMessage();
94
95         return ($msg === 'Unexpected token EOF') || (strpos($msg, 'Syntax error, unexpected EOF') !== false);
96     }
97 }