Convert Figma logo to code with AI

phpstan logophpdoc-parser

Next-gen phpDoc parser with support for intersection types and generics

1,313
62
1,313
24

Top Related Projects

A PHP parser written in PHP

Annotations Docblock Parser

A tool to automatically fix PHP Coding Standards issues

5,537

A static analysis tool for finding errors in PHP applications

5,528

Phan is a static analyzer for PHP. Phan prefers to avoid false-positives and attempts to prove incorrectness rather than correctness.

Quick Overview

PHPDoc Parser is a PHP library designed to parse and analyze PHPDoc comments in PHP code. It provides a robust set of tools for extracting and working with docblock annotations, type hints, and other metadata from PHP source code.

Pros

  • Highly accurate and reliable parsing of PHPDoc comments
  • Supports a wide range of PHPDoc annotations and type hints
  • Easily integrable with other PHP static analysis tools
  • Actively maintained and regularly updated

Cons

  • Steep learning curve for advanced usage
  • Limited documentation for some complex features
  • May have performance overhead for large codebases
  • Requires PHP 7.2 or higher

Code Examples

  1. Parsing a simple PHPDoc comment:
use PHPStan\PhpDocParser\Lexer\Lexer;
use PHPStan\PhpDocParser\Parser\PhpDocParser;
use PHPStan\PhpDocParser\Parser\TokenIterator;

$lexer = new Lexer();
$parser = new PhpDocParser();

$docComment = '/** @param string $name The user\'s name */';
$tokens = $lexer->tokenize($docComment);
$phpDocNode = $parser->parse(new TokenIterator($tokens));

var_dump($phpDocNode);
  1. Extracting parameter information:
use PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode;

$paramTags = $phpDocNode->getParamTagValues();
foreach ($paramTags as $paramTag) {
    echo "Parameter: " . $paramTag->parameterName . "\n";
    echo "Type: " . $paramTag->type . "\n";
    echo "Description: " . $paramTag->description . "\n";
}
  1. Parsing a complex type:
use PHPStan\PhpDocParser\Parser\TypeParser;

$typeParser = new TypeParser();
$typeString = 'array<int, string|null>';
$typeNode = $typeParser->parse(new TokenIterator($lexer->tokenize($typeString)));

var_dump($typeNode);

Getting Started

To use PHPDoc Parser in your project, follow these steps:

  1. Install the library using Composer:

    composer require phpstan/phpdoc-parser
    
  2. Include the Composer autoloader in your PHP script:

    require 'vendor/autoload.php';
    
  3. Create instances of the Lexer and PhpDocParser:

    use PHPStan\PhpDocParser\Lexer\Lexer;
    use PHPStan\PhpDocParser\Parser\PhpDocParser;
    use PHPStan\PhpDocParser\Parser\TokenIterator;
    
    $lexer = new Lexer();
    $parser = new PhpDocParser();
    
  4. Parse a PHPDoc comment:

    $docComment = '/** @param string $name */';
    $tokens = $lexer->tokenize($docComment);
    $phpDocNode = $parser->parse(new TokenIterator($tokens));
    

You can now work with the parsed PHPDoc node to extract information or perform further analysis.

Competitor Comparisons

A PHP parser written in PHP

Pros of PHP-Parser

  • More comprehensive parsing capabilities, handling full PHP syntax
  • Wider adoption and community support
  • Ability to modify and generate PHP code programmatically

Cons of PHP-Parser

  • Heavier and more complex, potentially overkill for simpler tasks
  • Steeper learning curve due to its extensive feature set
  • May be slower for parsing small code snippets or specific docblocks

Code Comparison

PHP-Parser example:

use PhpParser\ParserFactory;

$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
$ast = $parser->parse('<?php echo "Hello World!";');

phpdoc-parser example:

use PHPStan\PhpDocParser\Lexer\Lexer;
use PHPStan\PhpDocParser\Parser\PhpDocParser;

$lexer = new Lexer();
$parser = new PhpDocParser();
$tokens = $lexer->tokenize('/** @param string $foo */');
$ast = $parser->parse($tokens);

Summary

PHP-Parser is a more robust solution for parsing and manipulating PHP code, offering a wide range of features and capabilities. It's ideal for complex tasks involving full PHP syntax analysis and modification. On the other hand, phpdoc-parser is more focused and lightweight, specifically designed for parsing PHPDoc comments. It's better suited for projects that primarily deal with docblock parsing and don't require full PHP syntax analysis.

Annotations Docblock Parser

Pros of Annotations

  • More mature and widely adopted in the PHP ecosystem
  • Supports a broader range of annotation use cases, including ORM mappings
  • Integrates well with other Doctrine projects and frameworks

Cons of Annotations

  • Heavier and more complex, potentially impacting performance
  • Requires additional configuration and setup
  • Less focused on pure PHPDoc parsing

Code Comparison

Annotations:

/**
 * @ORM\Entity
 * @ORM\Table(name="users")
 */
class User
{
    /** @ORM\Id @ORM\Column(type="integer") */
    private $id;
}

PHPDoc Parser:

/**
 * @var int
 */
private $id;

Key Differences

  • Annotations is designed for a wider range of use cases, including ORM mappings and custom annotations
  • PHPDoc Parser focuses specifically on parsing PHPDoc comments and is more lightweight
  • Annotations requires more setup and configuration, while PHPDoc Parser can be used more easily out of the box
  • PHPDoc Parser is maintained by the PHPStan team and integrates well with their static analysis tools
  • Annotations has a larger community and ecosystem, particularly within the Symfony and Doctrine communities

Use Case Considerations

  • Choose Annotations for projects heavily relying on Doctrine ORM or needing custom annotation support
  • Opt for PHPDoc Parser when focusing on lightweight PHPDoc parsing or integrating with PHPStan
  • Consider PHPDoc Parser for projects prioritizing performance and simplicity in documentation parsing

A tool to automatically fix PHP Coding Standards issues

Pros of PHP-CS-Fixer

  • Comprehensive code style fixing tool with a wide range of rules
  • Highly configurable and customizable
  • Actively maintained with frequent updates and improvements

Cons of PHP-CS-Fixer

  • Larger codebase and more complex setup compared to phpdoc-parser
  • May have a steeper learning curve for beginners
  • Focuses on code style fixing rather than specific PHPDoc parsing

Code Comparison

PHP-CS-Fixer:

$config = new PhpCsFixer\Config();
return $config->setRules([
    '@PSR2' => true,
    'array_syntax' => ['syntax' => 'short'],
    'no_unused_imports' => true,
]);

phpdoc-parser:

$lexer = new Lexer();
$parser = new Parser();
$tokens = $lexer->tokenize('@param int $foo');
$ast = $parser->parse($tokens);

PHP-CS-Fixer is a comprehensive tool for fixing code style issues in PHP projects. It offers a wide range of rules and is highly configurable, making it suitable for large-scale projects with specific coding standards. However, it may be overkill for smaller projects or those primarily focused on PHPDoc parsing.

phpdoc-parser, on the other hand, is a specialized library for parsing PHPDoc comments. It's lightweight and focused on a specific task, making it easier to integrate into projects that only need PHPDoc parsing functionality. However, it lacks the broader code style fixing capabilities of PHP-CS-Fixer.

Choose PHP-CS-Fixer for comprehensive code style management, or phpdoc-parser for focused PHPDoc parsing in smaller projects or as part of a larger toolchain.

5,537

A static analysis tool for finding errors in PHP applications

Pros of Psalm

  • More comprehensive static analysis tool, offering type checking and security analysis
  • Provides automatic code fixes for some issues
  • Integrates with popular IDEs and CI/CD pipelines

Cons of Psalm

  • Steeper learning curve due to more complex configuration options
  • May produce more false positives, requiring fine-tuning
  • Slower performance on large codebases compared to simpler parsers

Code Comparison

PHPDoc Parser:

$parser = new \PHPStan\PhpDocParser\Parser\PhpDocParser(
    new \PHPStan\PhpDocParser\Parser\TypeParser(),
    new \PHPStan\PhpDocParser\Parser\ConstExprParser()
);
$tokens = new \PHPStan\PhpDocParser\Lexer\Lexer()->tokenize($docComment);
$ast = $parser->parse(new \PHPStan\PhpDocParser\Parser\TokenIterator($tokens));

Psalm:

$config = \Psalm\Config::loadFromXMLFile('psalm.xml');
$project_analyzer = new \Psalm\Internal\Analyzer\ProjectAnalyzer(
    $config,
    new \Psalm\Internal\Provider\FileProvider()
);
$project_analyzer->analyzeProject();

While PHPDoc Parser focuses on parsing PHPDoc comments, Psalm offers a more comprehensive analysis of PHP code, including type checking and potential issues detection. PHPDoc Parser is lighter and faster for specific tasks, while Psalm provides a broader range of features at the cost of increased complexity and potential performance overhead.

5,528

Phan is a static analyzer for PHP. Phan prefers to avoid false-positives and attempts to prove incorrectness rather than correctness.

Pros of Phan

  • More comprehensive static analysis tool, covering a wider range of PHP issues
  • Supports advanced features like taint analysis and unused variable detection
  • Highly configurable with numerous options for customization

Cons of Phan

  • Steeper learning curve due to its complexity and extensive feature set
  • Requires more setup and configuration compared to PHPDoc Parser
  • May produce more false positives, requiring careful tuning

Code Comparison

PHPDoc Parser (parsing a PHPDoc comment):

$phpDocString = '/** @param int $foo */';
$ast = $phpDocParser->parse($phpDocString);

Phan (analyzing a PHP file):

$code_base = new CodeBase([$file_path], [], [], []);
$context = (new ContextGenerator())->getContextForFile($code_base, $file_path);
$node = \ast\parse_file($file_path, $version);
Analysis::analyzeNode($code_base, $context, $node);

While PHPDoc Parser focuses specifically on parsing PHPDoc comments, Phan provides a more comprehensive static analysis solution for PHP projects. PHPDoc Parser is lighter and easier to integrate for specific documentation-related tasks, whereas Phan offers a broader range of code quality and security checks at the cost of increased complexity.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

PHPDoc Parser for PHPStan

Build Status Latest Stable Version License PHPStan Enabled

This library phpstan/phpdoc-parser represents PHPDocs with an AST (Abstract Syntax Tree). It supports parsing and modifying PHPDocs.

For the complete list of supported PHPDoc features check out PHPStan documentation. PHPStan is the main (but not the only) user of this library.

This parser also supports parsing Doctrine Annotations. The AST nodes live in the PHPStan\PhpDocParser\Ast\PhpDoc\Doctrine namespace.

Installation

composer require phpstan/phpdoc-parser

Basic usage

<?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\ParserConfig;
use PHPStan\PhpDocParser\Parser\ConstExprParser;
use PHPStan\PhpDocParser\Parser\PhpDocParser;
use PHPStan\PhpDocParser\Parser\TokenIterator;
use PHPStan\PhpDocParser\Parser\TypeParser;

// basic setup

$config = new ParserConfig(usedAttributes: []);
$lexer = new Lexer($config);
$constExprParser = new ConstExprParser($config);
$typeParser = new TypeParser($config, $constExprParser);
$phpDocParser = new PhpDocParser($config, $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'

Format-preserving printer

This component can be used to modify the AST and print it again as close as possible to the original.

It's heavily inspired by format-preserving printer component in nikic/PHP-Parser.

<?php

require_once __DIR__ . '/vendor/autoload.php';

use PHPStan\PhpDocParser\Ast\NodeTraverser;
use PHPStan\PhpDocParser\Ast\NodeVisitor\CloningVisitor;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
use PHPStan\PhpDocParser\Lexer\Lexer;
use PHPStan\PhpDocParser\ParserConfig;
use PHPStan\PhpDocParser\Parser\ConstExprParser;
use PHPStan\PhpDocParser\Parser\PhpDocParser;
use PHPStan\PhpDocParser\Parser\TokenIterator;
use PHPStan\PhpDocParser\Parser\TypeParser;
use PHPStan\PhpDocParser\Printer\Printer;

// basic setup with enabled required lexer attributes

$config = new ParserConfig(usedAttributes: ['lines' => true, 'indexes' => true]);
$lexer = new Lexer($config);
$constExprParser = new ConstExprParser($config);
$typeParser = new TypeParser($config, $constExprParser);
$phpDocParser = new PhpDocParser($config, $typeParser, $constExprParser);

$tokens = new TokenIterator($lexer->tokenize('/** @param Lorem $a */'));
$phpDocNode = $phpDocParser->parse($tokens); // PhpDocNode

$cloningTraverser = new NodeTraverser([new CloningVisitor()]);

/** @var PhpDocNode $newPhpDocNode */
[$newPhpDocNode] = $cloningTraverser->traverse([$phpDocNode]);

// change something in $newPhpDocNode
$newPhpDocNode->getParamTagValues()[0]->type = new IdentifierTypeNode('Ipsum');

// print changed PHPDoc
$printer = new Printer();
$newPhpDoc = $printer->printFormatPreserving($newPhpDocNode, $phpDocNode, $tokens);
echo $newPhpDoc; // '/** @param Ipsum $a */'

Code of Conduct

This project adheres to a Contributor Code of Conduct. By participating in this project and its community, you are expected to uphold this code.

Building

Initially you need to run composer install, or composer update in case you aren't working in a folder which was built before.

Afterwards you can either run the whole build including linting and coding standards using

make

or run only tests using

make tests