Yaffs site version 1.1
[yaffs-website] / vendor / psy / psysh / src / Psy / ParserFactory.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;
13
14 use PhpParser\Lexer;
15 use PhpParser\Parser;
16 use PhpParser\ParserFactory as OriginalParserFactory;
17
18 /**
19  * Parser factory to abstract over PHP parser library versions.
20  */
21 class ParserFactory
22 {
23     const ONLY_PHP5   = 'ONLY_PHP5';
24     const ONLY_PHP7   = 'ONLY_PHP7';
25     const PREFER_PHP5 = 'PREFER_PHP5';
26     const PREFER_PHP7 = 'PREFER_PHP7';
27
28     /**
29      * Possible kinds of parsers for the factory, from PHP parser library.
30      *
31      * @return array
32      */
33     public static function getPossibleKinds()
34     {
35         return array('ONLY_PHP5', 'ONLY_PHP7', 'PREFER_PHP5', 'PREFER_PHP7');
36     }
37
38     /**
39      * Is this parser factory supports kinds?
40      *
41      * PHP parser < 2.0 doesn't support kinds, >= 2.0 — does.
42      *
43      * @return bool
44      */
45     public function hasKindsSupport()
46     {
47         return class_exists('PhpParser\ParserFactory');
48     }
49
50     /**
51      * Default kind (if supported, based on current interpreter's version).
52      *
53      * @return string|null
54      */
55     public function getDefaultKind()
56     {
57         if ($this->hasKindsSupport()) {
58             return version_compare(PHP_VERSION, '7.0', '>=') ? static::ONLY_PHP7 : static::ONLY_PHP5;
59         }
60     }
61
62     /**
63      * New parser instance with given kind.
64      *
65      * @param string|null $kind One of class constants (only for PHP parser 2.0 and above)
66      *
67      * @return Parser
68      */
69     public function createParser($kind = null)
70     {
71         if ($this->hasKindsSupport()) {
72             $originalFactory = new OriginalParserFactory();
73
74             $kind = $kind ?: $this->getDefaultKind();
75
76             if (!in_array($kind, static::getPossibleKinds())) {
77                 throw new \InvalidArgumentException('Unknown parser kind');
78             }
79
80             $parser = $originalFactory->create(constant('PhpParser\ParserFactory::' . $kind));
81         } else {
82             if ($kind !== null) {
83                 throw new \InvalidArgumentException('Install PHP Parser v2.x to specify parser kind');
84             }
85
86             $parser = new Parser(new Lexer());
87         }
88
89         return $parser;
90     }
91 }