PHP-Parser icon indicating copy to clipboard operation
PHP-Parser copied to clipboard

Store and retrieve nodes by address

Open onet4 opened this issue 8 years ago • 5 comments

Hi there,

Is it possible to retrieve a node address (path) in visitor class callback methods? I'd like to re-access nodes with cached data.

I'm looking for something like $node->address in the code below. I know such a property does not exist.

class MyNodeAddressCollectionVisitor extends NodeVisitorAbstract
{
    public function leaveNode(Node $node) {

        $nodeAddress = $node->address;

    }
}

Also I'm looking for a way to retrieve a node object by specifying its address,

    $node = $stmts->getNode($nodeAddress);

onet4 avatar Jan 01 '17 08:01 onet4

I don't really understand what you mean by "node address" and how it differs from the node itself.

nikic avatar Jan 01 '17 10:01 nikic

You know DOM nodes can be retrieved with XPath. I'm looking for a mechanism similar to it.

onet4 avatar Jan 01 '17 11:01 onet4

Ah, I see. This library currently doesn't have anything like that.

nikic avatar Jan 01 '17 11:01 nikic

Will be great if it's possible.

onet4 avatar Jan 01 '17 13:01 onet4

There is actually a class that allow you something similar:

$nodeAddress = spl_object_hash($node);
        
$nodeFinder = new PhpParser\NodeFinder;
$foundNode = $nodeFinder->findFirst($nodes, function (Node $node) use ($nodeAddress) {
    return spl_object_hash($node) === $nodeAddress;  
});

TomasVotruba avatar Oct 29 '17 11:10 TomasVotruba