phpstan/phpdoc-parser
PHPDoc Parser for PHPStan that parses, represents, and modifies PHPDoc blocks as an AST. Supports rich type syntax (unions, generics, shapes, callables, conditional types), constant expressions, and Doctrine annotations, with full API reference for nodes.
Start by installing the package via Composer: composer require phpstan/phpdoc-parser. Then, instantiate the parser pipeline: configure ParserConfig with required attributes (e.g., ['lines' => true, 'indexes' => true] for format-preserving operations), initialize Lexer, ConstExprParser, TypeParser, and PhpDocParser. Parse raw PHPDoc strings using TokenIterator wrapped around tokenized input, then access structured AST nodes (e.g., getParamTagValues(), getType()) for inspection or transformation. The simplest first use case: extract parameter names and types from a docblock to validate or generate documentation.
PhpDocNode to inspect annotations (e.g., @param, @return, @template) and traverse typed nodes like IdentifierTypeNode, GenericTypeNode, or IntersectionTypeNode for static analysis.@param) using NodeTraverser with CloningVisitor, then output modified PHPDocs via Printer::printFormatPreserving()—ideal for code transformers, fixers (like Rector), or linting tools.@ORM\Entity) using the PHPStan\PhpDocParser\Ast\PhpDoc\Doctrine namespace—configure parser with appropriate flags and leverage attribute nodes like DoctrineAnnotationTagValueNode.ConstExprParser or TypeParser for domain-specific PHPDoc extensions (e.g., custom generics or templated types), integrating with downstream tools like IDE plugins or schema validators.lines/indexes in ParserConfig breaks format-preserving printing—always enable them when editing and re-outputting docblocks.textBetweenTagsBelongsToDescription setting or missing EOL token skipping (especially with Doctrine annotations on a single line).getParamTagValues() returns at least one item before accessing index 0; empty or malformed PHPDocs yield empty arrays.NodeTraverser + CloningVisitor to safely modify trees instead of direct property assignment.var_dump($phpDocNode) on parsed nodes to inspect structure, or enable Xdebug tracing to trace parser behavior across TypeParser/ConstExprParser boundaries.TypeParser subclasses and wiring them into your pipeline.How can I help you explore Laravel packages today?