我正在使用PHP-Parser来解析 PHP 代码,并以 Json 格式获取 AST。我想问如何在没有属性的情况下获得结果(startLine、endLine、comment 等)
问问题
72 次
1 回答
1
尽管计算成本很高,但您可以递归地遍历输出并删除这些属性。
或者
另一种可能更容易的方法是扩展一个已实现的 Php Parser 类并覆盖protected function createCommentNopAttributes(array $comments)
以返回您想要的属性,或者在这种情况下不返回任何属性。
例如,假设我们打算解析Php7
代码,我们可以创建自己的自定义解析器
class MyCustomPhp7Parser extends \PhpParser\Parser\Php7 {
//no need to implement the other methods as we are inheriting from a concrete class
//override method inherited from https://github.com/nikic/PHP-Parser/blob/master/lib/PhpParser/ParserAbstract.php
protected function createCommentNopAttributes(array $comments) {
$attributes = ['comments' => []]; //return data as desired
return $attributes;
}
}
然后您可以使用您的自定义解析器实现
<?php
use PhpParser\ParserFactory;
$code = <<<'CODE'
<?php
/** @param string $msg */
function printLine($msg) {
echo $msg, "\n";
}
CODE;
$parser = new MyCustomPhp7Parser(
new \PhpParser\Lexer\Emulative(), //desired lexer
[] //additional options
);
try {
$stmts = $parser->parse($code);
echo json_encode($stmts, JSON_PRETTY_PRINT), "\n";
} catch (PhpParser\Error $e) {
echo 'Parse Error: ', $e->getMessage();
}
检索
[
{
"nodeType": "Stmt_Function",
"byRef": false,
"name": {
"nodeType": "Identifier",
"name": "printLine",
"attributes": {
"startLine": 4,
"endLine": 4
}
},
"params": [
{
"nodeType": "Param",
"type": null,
"byRef": false,
"variadic": false,
"var": {
"nodeType": "Expr_Variable",
"name": "msg",
"attributes": {
"startLine": 4,
"endLine": 4
}
},
"default": null,
"attributes": {
"startLine": 4,
"endLine": 4
}
}
],
"returnType": null,
"stmts": [
{
"nodeType": "Stmt_Echo",
"exprs": [
{
"nodeType": "Expr_Variable",
"name": "msg",
"attributes": {
"startLine": 5,
"endLine": 5
}
},
{
"nodeType": "Scalar_String",
"value": "\n",
"attributes": {
"startLine": 5,
"endLine": 5,
"kind": 2
}
}
],
"attributes": {
"startLine": 5,
"endLine": 5
}
}
],
"attributes": {
"comments": [
],
}
}
]
于 2020-10-13T03:17:15.210 回答