Get node offset and length

47 Views Asked by At

I am using the package nikic/php-parser to parse a PHP file that is provide by the user. This file will have some PHP functions and I need to know which one are and the exact offset and length of the definition.

For instance:

Line | Content
   1 | <?php\n
   2 | function x() { }\n
   3 | x();

In this case I have one function called x, and the offset (where the function starts) is 6, and the length is counted until }, in this case is 16.

So I have enabled two attributes on parser: startFilePos and endFilePos, but for some reason it will not give to me that informations.

1

There are 1 best solutions below

0
David Rodrigues On

Okay, now I see...

I am running it like:

$this->parser = (new ParserFactory)->create(ParserFactory::ONLY_PHP7, null, [
    'usedAttributes' => [ 'startFilePos', 'endFilePos' ]
]);

But actually the third parameter is not passed to the Lexer as I have expected, and it supports only a deprecated option throwOnError.

So I applied it directly to the Lexer:

$this->parser = (new ParserFactory)->create(ParserFactory::ONLY_PHP7, new Lexer([
    'usedAttributes' => [ 'startFilePos', 'endFilePos' ]
]));

Now I receives the file offset correctly.