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.
16 use PhpParser\ParserFactory as OriginalParserFactory;
19 * Parser factory to abstract over PHP parser library versions.
23 const ONLY_PHP5 = 'ONLY_PHP5';
24 const ONLY_PHP7 = 'ONLY_PHP7';
25 const PREFER_PHP5 = 'PREFER_PHP5';
26 const PREFER_PHP7 = 'PREFER_PHP7';
29 * Possible kinds of parsers for the factory, from PHP parser library.
33 public static function getPossibleKinds()
35 return array('ONLY_PHP5', 'ONLY_PHP7', 'PREFER_PHP5', 'PREFER_PHP7');
39 * Is this parser factory supports kinds?
41 * PHP parser < 2.0 doesn't support kinds, >= 2.0 — does.
45 public function hasKindsSupport()
47 return class_exists('PhpParser\ParserFactory');
51 * Default kind (if supported, based on current interpreter's version).
55 public function getDefaultKind()
57 if ($this->hasKindsSupport()) {
58 return version_compare(PHP_VERSION, '7.0', '>=') ? static::ONLY_PHP7 : static::ONLY_PHP5;
63 * New parser instance with given kind.
65 * @param string|null $kind One of class constants (only for PHP parser 2.0 and above)
69 public function createParser($kind = null)
71 if ($this->hasKindsSupport()) {
72 $originalFactory = new OriginalParserFactory();
74 $kind = $kind ?: $this->getDefaultKind();
76 if (!in_array($kind, static::getPossibleKinds())) {
77 throw new \InvalidArgumentException('Unknown parser kind');
80 $parser = $originalFactory->create(constant('PhpParser\ParserFactory::' . $kind));
83 throw new \InvalidArgumentException('Install PHP Parser v2.x to specify parser kind');
86 $parser = new Parser(new Lexer());