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