ParserFactory.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /*
  3. * This file is part of Psy Shell.
  4. *
  5. * (c) 2012-2023 Justin Hileman
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Psy;
  11. use PhpParser\Parser;
  12. use PhpParser\ParserFactory as OriginalParserFactory;
  13. /**
  14. * Parser factory to abstract over PHP parser library versions.
  15. */
  16. class ParserFactory
  17. {
  18. const ONLY_PHP5 = 'ONLY_PHP5';
  19. const ONLY_PHP7 = 'ONLY_PHP7';
  20. const PREFER_PHP5 = 'PREFER_PHP5';
  21. const PREFER_PHP7 = 'PREFER_PHP7';
  22. /**
  23. * Possible kinds of parsers for the factory, from PHP parser library.
  24. *
  25. * @return string[]
  26. */
  27. public static function getPossibleKinds(): array
  28. {
  29. return ['ONLY_PHP5', 'ONLY_PHP7', 'PREFER_PHP5', 'PREFER_PHP7'];
  30. }
  31. /**
  32. * Default kind (if supported, based on current interpreter's version).
  33. *
  34. * @return string|null
  35. */
  36. public function getDefaultKind()
  37. {
  38. return static::ONLY_PHP7;
  39. }
  40. /**
  41. * New parser instance with given kind.
  42. *
  43. * @param string|null $kind One of class constants (only for PHP parser 2.0 and above)
  44. */
  45. public function createParser($kind = null): Parser
  46. {
  47. $originalFactory = new OriginalParserFactory();
  48. $kind = $kind ?: $this->getDefaultKind();
  49. if (!\in_array($kind, static::getPossibleKinds())) {
  50. throw new \InvalidArgumentException('Unknown parser kind');
  51. }
  52. $parser = $originalFactory->create(\constant(OriginalParserFactory::class.'::'.$kind));
  53. return $parser;
  54. }
  55. }