ParserFactory.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php declare(strict_types=1);
  2. namespace PhpParser;
  3. use PhpParser\Parser\Php7;
  4. use PhpParser\Parser\Php8;
  5. class ParserFactory {
  6. /**
  7. * Create a parser targeting the given version on a best-effort basis. The parser will generally
  8. * accept code for the newest supported version, but will try to accommodate code that becomes
  9. * invalid in newer versions or changes in interpretation.
  10. */
  11. public function createForVersion(PhpVersion $version): Parser {
  12. if ($version->isHostVersion()) {
  13. $lexer = new Lexer();
  14. } else {
  15. $lexer = new Lexer\Emulative($version);
  16. }
  17. if ($version->id >= 80000) {
  18. return new Php8($lexer, $version);
  19. }
  20. return new Php7($lexer, $version);
  21. }
  22. /**
  23. * Create a parser targeting the newest version supported by this library. Code for older
  24. * versions will be accepted if there have been no relevant backwards-compatibility breaks in
  25. * PHP.
  26. */
  27. public function createForNewestSupportedVersion(): Parser {
  28. return $this->createForVersion(PhpVersion::getNewestSupported());
  29. }
  30. /**
  31. * Create a parser targeting the host PHP version, that is the PHP version we're currently
  32. * running on. This parser will not use any token emulation.
  33. */
  34. public function createForHostVersion(): Parser {
  35. return $this->createForVersion(PhpVersion::getHostVersion());
  36. }
  37. }