ParserFactory.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php declare(strict_types=1);
  2. namespace PhpParser;
  3. use PhpParser\Lexer\Emulative;
  4. use PhpParser\Parser\Php7;
  5. class ParserFactory
  6. {
  7. const PREFER_PHP7 = 1;
  8. const PREFER_PHP5 = 2;
  9. const ONLY_PHP7 = 3;
  10. const ONLY_PHP5 = 4;
  11. /**
  12. * Creates a Parser instance, according to the provided kind.
  13. *
  14. * @param int $kind One of ::PREFER_PHP7, ::PREFER_PHP5, ::ONLY_PHP7 or ::ONLY_PHP5
  15. * @param Lexer|null $lexer Lexer to use. Defaults to emulative lexer when not specified
  16. * @param array $parserOptions Parser options. See ParserAbstract::__construct() argument
  17. *
  18. * @return Parser The parser instance
  19. */
  20. public function create(int $kind, Lexer $lexer = null, array $parserOptions = []) : Parser {
  21. if (null === $lexer) {
  22. $lexer = new Lexer\Emulative();
  23. }
  24. switch ($kind) {
  25. case self::PREFER_PHP7:
  26. return new Parser\Multiple([
  27. new Parser\Php7($lexer, $parserOptions), new Parser\Php5($lexer, $parserOptions)
  28. ]);
  29. case self::PREFER_PHP5:
  30. return new Parser\Multiple([
  31. new Parser\Php5($lexer, $parserOptions), new Parser\Php7($lexer, $parserOptions)
  32. ]);
  33. case self::ONLY_PHP7:
  34. return new Parser\Php7($lexer, $parserOptions);
  35. case self::ONLY_PHP5:
  36. return new Parser\Php5($lexer, $parserOptions);
  37. default:
  38. throw new \LogicException(
  39. 'Kind must be one of ::PREFER_PHP7, ::PREFER_PHP5, ::ONLY_PHP7 or ::ONLY_PHP5'
  40. );
  41. }
  42. }
  43. /**
  44. * Create a parser targeting the newest version supported by this library. Code for older
  45. * versions will be accepted if there have been no relevant backwards-compatibility breaks in
  46. * PHP.
  47. *
  48. * All supported lexer attributes (comments, startLine, endLine, startTokenPos, endTokenPos,
  49. * startFilePos, endFilePos) will be enabled.
  50. */
  51. public function createForNewestSupportedVersion(): Parser {
  52. return new Php7(new Emulative($this->getLexerOptions()));
  53. }
  54. /**
  55. * Create a parser targeting the host PHP version, that is the PHP version we're currently
  56. * running on. This parser will not use any token emulation.
  57. *
  58. * All supported lexer attributes (comments, startLine, endLine, startTokenPos, endTokenPos,
  59. * startFilePos, endFilePos) will be enabled.
  60. */
  61. public function createForHostVersion(): Parser {
  62. return new Php7(new Lexer($this->getLexerOptions()));
  63. }
  64. private function getLexerOptions(): array {
  65. return ['usedAttributes' => [
  66. 'comments', 'startLine', 'endLine', 'startTokenPos', 'endTokenPos', 'startFilePos', 'endFilePos',
  67. ]];
  68. }
  69. }