The phpstan/phpdoc-parser
package is a PHPDoc parser that supports handling of nullable, intersection, and generic types. It operates via an AST (Abstract Syntax Tree), which makes it capable of parsing and modifying PHPDoc content. In addition, the parser also extends its functionality to operate with Doctrine Annotations, when set to true
.
In terms of usage, the phpstan/phpdoc-parser
package can be incorporated in your project by installing it via composer using the command composer require phpstan/phpdoc-parser
. Once installed, it can be imported into your PHP files where necessary. Here is an example of how to parse and read a PHPDoc string:
<?php
require_once __DIR__ . '/vendor/autoload.php';
use PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
use PHPStan\PhpDocParser\Lexer\Lexer;
use PHPStan\PhpDocParser\Parser\ConstExprParser;
use PHPStan\PhpDocParser\Parser\PhpDocParser;
use PHPStan\PhpDocParser\Parser\TokenIterator;
use PHPStan\PhpDocParser\Parser\TypeParser;
// basic setup
$lexer = new Lexer();
$constExprParser = new ConstExprParser();
$typeParser = new TypeParser($constExprParser);
$phpDocParser = new PhpDocParser($typeParser, $constExprParser);
// parsing and reading a PHPDoc string
$tokens = new TokenIterator($lexer->tokenize('/** @param Lorem $a */'));
$phpDocNode = $phpDocParser->parse($tokens); // PhpDocNode
$paramTags = $phpDocNode->getParamTagValues(); // ParamTagValueNode[]
echo $paramTags[0]->parameterName; // '$a'
echo $paramTags[0]->type; // IdentifierTypeNode - 'Lorem'
You can find the documentation for the phpstan/phpdoc-parser
on PHPStan's official documentation pages. This includes the PHPDoc Basics (a list of PHPDoc tags), PHPDoc Types (a list of PHPDoc types), and phpdoc-parser API Reference with all the AST node types, etc. These documentation pages provide a comprehensive understanding of how to effectively use this PHPDoc Parser.