简体   繁体   English

使用 nikic/PHP-Parser 将节点插入 PHP AST

[英]INSERT node into PHP AST with nikic/PHP-Parser

Im using https://github.com/nikic/PHP-Parser .我使用https://github.com/nikic/PHP-Parser What is a good strategy when wanting to INSERT a node in the AST?想要在 AST 中插入节点时,什么是好的策略? With the traverser I can UPDATE and DELETE nodes easily using a NodeTraverser class.使用遍历器,我可以使用NodeTraverser类轻松更新和删除节点。 But how can I "INSERT before" or "INSERT after" a node?但是我怎样才能“在节点之前插入”或“在节点之后插入”?

Example: When traversing an AST namespace I want to INSERT a Use statement just before the first non-use statement.示例:遍历 AST 命名空间时,我想在第一个非使用语句之前插入Use语句。

I started working with beforeTraverse and afterTraverse to find indexes of arrays but it seems overly complicated.我开始使用beforeTraverseafterTraverse来查找数组的索引,但这似乎过于复杂。 Any ideas?有任何想法吗?

It is possible to replace one node with multiple nodes.可以用多个节点替换一个节点。 This only works inside leaveNode and only if the parent structure is an array.这仅适用于 leaveNode 并且仅当父结构是数组时。

public function leaveNode(Node $node) {
    if ($node instanceof Node\Stmt\Return_ && $node->expr !== null) {
        // Convert "return foo();" into "$retval = foo(); return $retval;"
        $var = new Node\Expr\Variable('retval');
        return [
            new Node\Stmt\Expression(new Node\Expr\Assign($var, $node->expr)),
            new Node\Stmt\Return_($var),
        ];
    }
}

See last section in Modyfing the AST请参阅修改 AST 中的最后一节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM