nikic/php-parser
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|
The nikic/php-parser is a potent tool, written in PHP, that simplifies static code analysis and manipulation. Its purpose enlists parsing PHP 7 and PHP 8 code into an abstract syntax tree (AST). This AST includes precise location information for easy code navigation. The library also allows dumping the AST in a human-readable form, converting it back to PHP code, and even traversing and modifying ASTs. Other features include resolution of namespaced names, evaluation of constant expressions, builders to streamline AST construction for code generation, and the conversion of an AST into JSON and back.
To harness the power of nikic/php-parser, the first step is to install it via composer with php composer.phar require nikic/php-parser
. The usage involves creating a new parser, parsing code to an AST, and optionally manipulating the AST before printing it back to PHP.
Code parser:
<?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";
Code manipulation with AST:
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";
Printing the new AST back to PH:
use PhpParser\PrettyPrinter;
$prettyPrinter = new PrettyPrinter\Standard;
echo $prettyPrinter->prettyPrintFile($ast);
The documentation for the nikic/php-parser can be found on GitHub. They've conveniently separated the documentation based on versions namely version 3.x (unsupported), version 4.x (stable), and version 5.x (in development). The documentation provides a comprehensive guide to using the library with detailed introductions, usage of basic components, and a variety of component-specific documentations.