diff --git a/lib/PhpParser/ParserFactory.php b/lib/PhpParser/ParserFactory.php index f041e7ffe3..baba23bdb4 100644 --- a/lib/PhpParser/ParserFactory.php +++ b/lib/PhpParser/ParserFactory.php @@ -2,6 +2,9 @@ namespace PhpParser; +use PhpParser\Lexer\Emulative; +use PhpParser\Parser\Php7; + class ParserFactory { const PREFER_PHP7 = 1; @@ -41,4 +44,33 @@ public function create(int $kind, Lexer $lexer = null, array $parserOptions = [] ); } } + + /** + * Create a parser targeting the newest version supported by this library. Code for older + * versions will be accepted if there have been no relevant backwards-compatibility breaks in + * PHP. + * + * All supported lexer attributes (comments, startLine, endLine, startTokenPos, endTokenPos, + * startFilePos, endFilePos) will be enabled. + */ + public function createForNewestSupportedVersion(): Parser { + return new Php7(new Emulative($this->getLexerOptions())); + } + + /** + * Create a parser targeting the host PHP version, that is the PHP version we're currently + * running on. This parser will not use any token emulation. + * + * All supported lexer attributes (comments, startLine, endLine, startTokenPos, endTokenPos, + * startFilePos, endFilePos) will be enabled. + */ + public function createForHostVersion(): Parser { + return new Php7(new Lexer($this->getLexerOptions())); + } + + private function getLexerOptions(): array { + return ['usedAttributes' => [ + 'comments', 'startLine', 'endLine', 'startTokenPos', 'endTokenPos', 'startFilePos', 'endFilePos', + ]]; + } } diff --git a/test/PhpParser/ParserFactoryTest.php b/test/PhpParser/ParserFactoryTest.php index d50981f2a1..fbdc83ae93 100644 --- a/test/PhpParser/ParserFactoryTest.php +++ b/test/PhpParser/ParserFactoryTest.php @@ -5,6 +5,8 @@ /* This test is very weak, because PHPUnit's assertEquals assertion is way too slow dealing with the * large objects involved here. So we just do some basic instanceof tests instead. */ +use PhpParser\Node\Stmt\Echo_; + class ParserFactoryTest extends \PHPUnit\Framework\TestCase { /** @dataProvider provideTestCreate */ @@ -33,4 +35,26 @@ public function provideTestCreate() { ] ]; } + + /** @dataProvider provideTestLexerAttributes */ + public function testLexerAttributes(Parser $parser) { + $stmts = $parser->parse("assertInstanceOf(Echo_::class, $stmt); + $this->assertCount(1, $stmt->getComments()); + $this->assertSame(1, $stmt->getStartLine()); + $this->assertSame(1, $stmt->getEndLine()); + $this->assertSame(3, $stmt->getStartTokenPos()); + $this->assertSame(6, $stmt->getEndTokenPos()); + $this->assertSame(16, $stmt->getStartFilePos()); + $this->assertSame(26, $stmt->getEndFilePos()); + } + + public function provideTestLexerAttributes() { + $factory = new ParserFactory(); + return [ + [$factory->createForHostVersion()], + [$factory->createForNewestSupportedVersion()], + ]; + } }