Reputation: 77
I'm using PHP-Parser to parse PHP codes, and get the AST in Json format. I want to ask how to get the results without Attributes ( startLine, endLine, comment etc.)
Upvotes: 1
Views: 203
Reputation: 10035
Although very expensive computationally, you could traverse the output recursively and remove these attributes.
OR
An alternative approach and maybe easier would be to extend one of the implemented Php Parser classes and override protected function createCommentNopAttributes(array $comments)
to return your desired attributes or in this case none.
For example, say we intend to parse Php7
code we could create our own custom parser
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;
}
}
You can then use your custom parser implementation
<?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();
}
To retrieve
[
{
"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": [
],
}
}
]
Upvotes: 1