Convert Figma logo to code with AI

nikic logoPHP-Parser

A PHP parser written in PHP

16,964
1,091
16,964
42

Top Related Projects

A tool to automatically fix PHP Coding Standards issues

12,802

PHP Static Analysis Tool - discover bugs in your code without running it!

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.

8,596

Instant Upgrades and Automated Refactoring of any PHP 5.3+ code

Quick Overview

PHP-Parser is a powerful PHP parser written in PHP. It provides a set of tools to parse, analyze, and manipulate PHP code, making it useful for various applications such as static analysis, code metrics, and automated refactoring.

Pros

  • Comprehensive parsing capabilities for PHP 5.2 to PHP 8.2
  • Extensive documentation and examples
  • Actively maintained with regular updates
  • Flexible and extensible architecture

Cons

  • Learning curve for complex use cases
  • Performance overhead for large-scale parsing tasks
  • Limited built-in code transformation capabilities
  • Requires PHP 7.0 or higher to run

Code Examples

  1. Parsing PHP code:
use PhpParser\ParserFactory;

$code = '<?php echo "Hello World!";';
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
$ast = $parser->parse($code);
  1. Traversing the Abstract Syntax Tree (AST):
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitorAbstract;

$traverser = new NodeTraverser();
$traverser->addVisitor(new class extends NodeVisitorAbstract {
    public function leaveNode(\PhpParser\Node $node) {
        if ($node instanceof \PhpParser\Node\Scalar\String_) {
            $node->value = strtoupper($node->value);
        }
    }
});

$modifiedAst = $traverser->traverse($ast);
  1. Pretty printing modified code:
use PhpParser\PrettyPrinter;

$prettyPrinter = new PrettyPrinter\Standard();
$modifiedCode = $prettyPrinter->prettyPrintFile($modifiedAst);
echo $modifiedCode;

Getting Started

To start using PHP-Parser, follow these steps:

  1. Install the library using Composer:

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

    require 'vendor/autoload.php';
    
  3. Create a parser instance and start parsing PHP code:

    use PhpParser\ParserFactory;
    
    $parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
    $ast = $parser->parse('<?php echo "Hello, PHP-Parser!";');
    

Now you're ready to work with the Abstract Syntax Tree (AST) generated by PHP-Parser.

Competitor Comparisons

A tool to automatically fix PHP Coding Standards issues

Pros of PHP-CS-Fixer

  • Focuses specifically on code style fixing and formatting
  • Provides a wide range of predefined coding standards (PSR-1, PSR-2, Symfony, etc.)
  • Offers an extensive set of fixers for various coding style issues

Cons of PHP-CS-Fixer

  • Limited to code style fixing and doesn't provide advanced code analysis capabilities
  • May require more configuration to achieve desired results compared to PHP-Parser

Code Comparison

PHP-CS-Fixer (fixing code style):

$fixer = new PhpCsFixer\Fixer\ClassNotation\VisibilityRequiredFixer();
$file = new SplFileInfo('example.php');
$tokens = Tokens::fromCode(file_get_contents($file->getRealPath()));
$fixer->fix($file, $tokens);

PHP-Parser (parsing and analyzing code):

$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
$ast = $parser->parse(file_get_contents('example.php'));
$nodeFinder = new NodeFinder();
$methods = $nodeFinder->findInstanceOf($ast, Node\Stmt\ClassMethod::class);

PHP-CS-Fixer is primarily designed for code style fixing and formatting, offering a wide range of predefined standards and fixers. It's excellent for maintaining consistent coding styles across projects. PHP-Parser, on the other hand, provides a powerful toolkit for parsing PHP code into an Abstract Syntax Tree (AST), enabling advanced code analysis and manipulation. While PHP-CS-Fixer is more focused on style, PHP-Parser offers greater flexibility for complex code analysis tasks.

12,802

PHP Static Analysis Tool - discover bugs in your code without running it!

Pros of PHPStan

  • Focuses on static analysis and error detection in PHP code
  • Provides more advanced type inference and checks
  • Offers a wider range of rules and customization options

Cons of PHPStan

  • Steeper learning curve for configuration and usage
  • May produce false positives in certain scenarios
  • Requires more setup and integration effort

Code Comparison

PHP-Parser (parsing PHP code):

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

PHPStan (analyzing PHP code):

$phpstan = PHPStan\analyseFiles(['path/to/file.php'], $configuration);
$errors = $phpstan->getErrors();

Summary

PHP-Parser is primarily a tool for parsing PHP code into an Abstract Syntax Tree (AST), while PHPStan is a static analysis tool that uses the AST to perform advanced code checks and error detection. PHP-Parser is more focused on providing a foundation for other tools, whereas PHPStan offers a complete solution for code analysis out of the box. Both tools serve different purposes in the PHP ecosystem and can be complementary in certain workflows.

5,537

A static analysis tool for finding errors in PHP applications

Pros of Psalm

  • Focuses on static analysis and type checking, providing more comprehensive code quality insights
  • Offers a wider range of checks and analysis features, including security vulnerability detection
  • Integrates well with popular IDEs and CI/CD pipelines for seamless workflow integration

Cons of Psalm

  • Has a steeper learning curve due to its more complex configuration options
  • May produce more false positives, requiring fine-tuning of configuration
  • Slower performance on large codebases compared to PHP-Parser

Code Comparison

PHP-Parser (parsing PHP code):

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

Psalm (analyzing PHP code):

$config = Config::loadFromXMLFile('psalm.xml');
$project_analyzer = new ProjectAnalyzer($config, new \Psalm\Internal\Provider\FakeFileProvider());
$project_analyzer->check('src');

While PHP-Parser focuses on parsing PHP code into an Abstract Syntax Tree (AST), Psalm uses this AST to perform static analysis and type checking, providing more in-depth code quality insights.

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

  • Focuses on static analysis and error detection in PHP code
  • Provides more comprehensive code analysis and type checking
  • Offers a wider range of checks and can detect more potential issues

Cons of Phan

  • Steeper learning curve and more complex configuration
  • May produce more false positives, requiring fine-tuning
  • Slower performance due to its extensive analysis capabilities

Code Comparison

PHP-Parser (parsing PHP code):

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

Phan (analyzing PHP code):

$config = new Config([
    'directory_list' => ['src/'],
    'minimum_severity' => Issue::SEVERITY_LOW,
]);
$phan = new Phan($config);
$phan->analyzeFiles();

Summary

PHP-Parser is primarily focused on parsing PHP code and generating an Abstract Syntax Tree (AST), making it useful for tasks like code transformation and analysis. Phan, on the other hand, is a static analyzer that leverages PHP-Parser's capabilities to perform in-depth code analysis, detect potential errors, and enforce coding standards. While PHP-Parser is more lightweight and flexible, Phan offers more comprehensive code analysis at the cost of increased complexity and potential false positives.

8,596

Instant Upgrades and Automated Refactoring of any PHP 5.3+ code

Pros of Rector

  • Provides automated refactoring and upgrading capabilities for PHP code
  • Includes a large set of predefined rules for common PHP upgrades and best practices
  • Offers a more user-friendly interface for code transformation tasks

Cons of Rector

  • Has a steeper learning curve for creating custom rules compared to PHP-Parser
  • May have slower performance when processing large codebases due to its higher-level abstractions

Code Comparison

PHP-Parser (parsing and modifying code):

$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
$ast = $parser->parse($code);
$traverser = new NodeTraverser();
$traverser->addVisitor(new class extends NodeVisitorAbstract {
    public function leaveNode(Node $node) {
        if ($node instanceof Node\Expr\Variable && $node->name === 'foo') {
            return new Node\Expr\Variable('bar');
        }
    }
});
$modifiedAst = $traverser->traverse($ast);

Rector (applying a rule):

use Rector\Renaming\Rector\Variable\RenameVariableRector;
use Rector\Config\RectorConfig;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->rule(RenameVariableRector::class);
};

Both PHP-Parser and Rector are powerful tools for working with PHP code, but they serve different purposes. PHP-Parser provides low-level AST manipulation, while Rector offers high-level code refactoring capabilities built on top of PHP-Parser.

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

PHP Parser

Coverage Status

This is a PHP parser written in PHP. Its purpose is to simplify static code analysis and manipulation.

Documentation for version 5.x (current; for running on PHP >= 7.4; for parsing PHP 7.0 to PHP 8.3, with limited support for parsing PHP 5.x).

Documentation for version 4.x (supported; for running on PHP >= 7.0; for parsing PHP 5.2 to PHP 8.3).

Features

The main features provided by this library are:

  • Parsing PHP 7, and PHP 8 code into an abstract syntax tree (AST).
    • Invalid code can be parsed into a partial AST.
    • The AST contains accurate location information.
  • Dumping the AST in human-readable form.
  • Converting an AST back to PHP code.
    • Formatting can be preserved for partially changed ASTs.
  • Infrastructure to traverse and modify ASTs.
  • Resolution of namespaced names.
  • Evaluation of constant expressions.
  • Builders to simplify AST construction for code generation.
  • Converting an AST into JSON and back.

Quick Start

Install the library using composer:

php composer.phar require nikic/php-parser

Parse some PHP code into an AST and dump the result in human-readable form:

<?php
use PhpParser\Error;
use PhpParser\NodeDumper;
use PhpParser\ParserFactory;

$code = <<<'CODE'
<?php

function test($foo)
{
    var_dump($foo);
}
CODE;

$parser = (new ParserFactory())->createForNewestSupportedVersion();
try {
    $ast = $parser->parse($code);
} catch (Error $error) {
    echo "Parse error: {$error->getMessage()}\n";
    return;
}

$dumper = new NodeDumper;
echo $dumper->dump($ast) . "\n";

This dumps an AST looking something like this:

array(
    0: Stmt_Function(
        attrGroups: array(
        )
        byRef: false
        name: Identifier(
            name: test
        )
        params: array(
            0: Param(
                attrGroups: array(
                )
                flags: 0
                type: null
                byRef: false
                variadic: false
                var: Expr_Variable(
                    name: foo
                )
                default: null
            )
        )
        returnType: null
        stmts: array(
            0: Stmt_Expression(
                expr: Expr_FuncCall(
                    name: Name(
                        name: var_dump
                    )
                    args: array(
                        0: Arg(
                            name: null
                            value: Expr_Variable(
                                name: foo
                            )
                            byRef: false
                            unpack: false
                        )
                    )
                )
            )
        )
    )
)

Let's traverse the AST and perform some kind of modification. For example, drop all function bodies:

use PhpParser\Node;
use PhpParser\Node\Stmt\Function_;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitorAbstract;

$traverser = new NodeTraverser();
$traverser->addVisitor(new class extends NodeVisitorAbstract {
    public function enterNode(Node $node) {
        if ($node instanceof Function_) {
            // Clean out the function body
            $node->stmts = [];
        }
    }
});

$ast = $traverser->traverse($ast);
echo $dumper->dump($ast) . "\n";

This gives us an AST where the Function_::$stmts are empty:

array(
    0: Stmt_Function(
        attrGroups: array(
        )
        byRef: false
        name: Identifier(
            name: test
        )
        params: array(
            0: Param(
                attrGroups: array(
                )
                type: null
                byRef: false
                variadic: false
                var: Expr_Variable(
                    name: foo
                )
                default: null
            )
        )
        returnType: null
        stmts: array(
        )
    )
)

Finally, we can convert the new AST back to PHP code:

use PhpParser\PrettyPrinter;

$prettyPrinter = new PrettyPrinter\Standard;
echo $prettyPrinter->prettyPrintFile($ast);

This gives us our original code, minus the var_dump() call inside the function:

<?php

function test($foo)
{
}

For a more comprehensive introduction, see the documentation.

Documentation

  1. Introduction
  2. Usage of basic components

Component documentation:

  • Walking the AST
    • Node visitors
    • Modifying the AST from a visitor
    • Short-circuiting traversals
    • Interleaved visitors
    • Simple node finding API
    • Parent and sibling references
  • Name resolution
    • Name resolver options
    • Name resolution context
  • Pretty printing
    • Converting AST back to PHP code
    • Customizing formatting
    • Formatting-preserving code transformations
  • AST builders
    • Fluent builders for AST nodes
  • Lexer
    • Emulation
    • Tokens, positions and attributes
  • Error handling
    • Column information for errors
    • Error recovery (parsing of syntactically incorrect code)
  • Constant expression evaluation
    • Evaluating constant/property/etc initializers
    • Handling errors and unsupported expressions
  • JSON representation
    • JSON encoding and decoding of ASTs
  • Performance
    • Disabling Xdebug
    • Reusing objects
    • Garbage collection impact
  • Frequently asked questions
    • Parent and sibling references