Tolerant PHP ParserPHP 解析器
这是一个早期的 PHP 解析器,相当于实现了 PHP 对 PHP 脚本的解析。
示例代码:
<?php
// Autoload required classes
require "vendor/autoload.php";
// Instantiate new parser instance
$parser = new PhpParser\Parser();
// Return and print an AST from string contents
$astNode = $parser->parseSourceFile('<?php /* comment */ echo "hi!"');
var_dump($astNode);
// Gets and prints errors from AST Node. The parser handles errors gracefully,
// so it can be used in IDE usage scenarios (where code is often incomplete).
$errors = PhpParser\Utilities::getDiagnostics($astNode);
var_dump(iterator_to_array($errors));
// Traverse all Node descendants of $astNode
foreach ($astNode->getDescendantNodes() as $descendant) {
if ($descendant instanceof \PhpParser\Node\StringLiteral) {
// Print the Node text (without whitespace or comments)
var_dump($descendant->getText());
// All Nodes link back to their parents, so it's easy to navigate the tree.
$grandParent = $descendant->getParent()->getParent();
var_dump($grandParent->getNodeKindName());
// The AST is fully-representative, and round-trippable to the original source.
// This enables consumers to build reliable formatting and refactoring tools.
var_dump($grandParent->getLeadingCommentAndWhitespaceText());
}
// In addition to retrieving all children or descendants of a Node,
// Nodes expose properties specific to the Node type.
if ($descendant instanceof \PhpParser\Node\Expression\EchoExpression) {
$echoKeywordStartPosition = $descendant->echoKeyword->getStartPosition();
// To cut down on memory consumption, positions are represented as a single integer
// index into the document, but their line and character positions are easily retrieved.
$lineCharacterPosition = \PhpParser\Utilities::getLineCharacterPositionFromPosition(
$echoKeywordStartPosition
);
echo "line: $lineCharacterPosition->line, character: $lineCharacterPosition->character";
}
}评论
