Tolerant Mode
Edit pageLast modified: 02 February 2025The "tolerant" analysis mode allows parsing a type grammar containing other arbitrary data.
Such a mode will be convenient to use, for example, for analyzing phpdoc docblocks, separating types from their descriptions.
$parser = new TypeLang\Parser\Parser(
// enable "tolerant" mode
tolerant: true,
);
As an example, let's try to parse the contents of the " @return
" docblock. Similar actions can be implemented for other annotations.
$parser = new TypeLang\Parser\Parser(
tolerant: true,
);
$content = <<<'PHP'
@return Example<T> Returns something very interesting!
PHP;
// There is no need to analyze the "@return" annotation,
// we only get the content:
// "Example<T> Returns something very interesting!"
$content = substr($content, strlen('@return '));
var_dump($parser->parse($content));
TypeLang\Parser\Node\Stmt\NamedTypeNode
{...}
The Parser::$lastProcessedTokenOffset
contains the offset in bytes (in this case 11) at which unparsable content begins (description of " @return
" annotation).
// Next we can get the contents of the docblock description by simply
// getting it by this offset.
$description = substr($content, $parser->lastProcessedTokenOffset);
The $description
will contain:
string("Returns something very interesting!")