PHP-Parser README

The project's README from github.com/nikic/PHP-Parser. As one markdown file: README.md.

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.4, 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:

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:

PHP-Parser (nikic/PHP-Parser)

Searching Database…

这是干什么的?一个用 PHP 写的解析器,能把 PHP 代码转换成抽象语法树(AST)。它的用途是让 PHP 代码的静态分析和代码操作变得更简单。
它是我在自己代码里调用的库,还是现成的分析工具?它是一个库:用 Composer 安装,然后在 PHP 代码里调用。解析、遍历 AST、修改和生成代码都通过它的 API 来完成——它没有独立的可执行程序。
我该怎么上手?先用 php composer.phar require nikic/php-parser 安装,然后按照快速上手指南操作:把代码解析成 AST,以人类可读的形式输出它,或者用节点访问器(node visitor)遍历它,再修改它,最后把它转换回 PHP 代码。
它需要哪个 PHP 版本,能解析哪些 PHP 版本的代码?当前的 5.x 系列要求 PHP >= 7.4,能解析 PHP 7.0 到 PHP 8.4 的代码,对 PHP 5.x 的解析支持有限。较旧的 4.x 系列要求 PHP >= 7.0,能解析 PHP 5.2 到 PHP 8.3 的代码。
如果我给它的代码有语法错误会怎样?它不会在遇到第一个错误时就停下来:有问题的代码也能被解析成一份不完整的 AST。文档还介绍了错误恢复和错误的列号信息,这对做 linter 类工具很有用。
拿到 AST 之后我能用它做什么?可以把它以人类可读的形式输出、转换回 PHP 代码、用节点访问器(node visitor)遍历和修改它、解析命名空间名称、求常量表达式的值、把它和 JSON 互相转换,或者用 builder 来构建 AST 节点以便生成代码。
我能不能改代码又不弄乱它的格式?可以——对于只有部分改动的 AST,可以保留原有的代码格式。README 的快速上手示例里,一个修改过的 AST 被转换回 PHP 代码,结果和原文件一致,只是去掉了 vardump() 调用。
它知道每个节点在源代码里的位置吗?知道,AST 里带有准确的位置信息,错误信息还附带列号——这对精确定位问题和做 IDE 类工具很方便。
Creator
nikic
Size
7.4 MB
Stars
17.5K
Age
15y
Commits · 90 Days