INSERT node into PHP AST with nikic/PHP-Parser

674 Views Asked by At

Im using https://github.com/nikic/PHP-Parser. What is a good strategy when wanting to INSERT a node in the AST? With the traverser I can UPDATE and DELETE nodes easily using a NodeTraverser class. 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.

I started working with beforeTraverse and afterTraverse to find indexes of arrays but it seems overly complicated. Any ideas?

1

There are 1 best solutions below

1
ajthinking On BEST ANSWER

It is possible to replace one node with multiple nodes. This only works inside leaveNode and only if the parent structure is an array.

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