Skip to content

Commit

Permalink
Support WeakReferences in ParentConnectingVisitor
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm committed Jan 1, 2025
1 parent 4cac2f2 commit e002a95
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
12 changes: 11 additions & 1 deletion lib/PhpParser/NodeVisitor/ParentConnectingVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,23 @@ final class ParentConnectingVisitor extends NodeVisitorAbstract {
*/
private array $stack = [];

private bool $weakReferences;

public function __construct(bool $weakReferences = false) {
$this->weakReferences = $weakReferences;
}

public function beforeTraverse(array $nodes) {
$this->stack = [];
}

public function enterNode(Node $node) {
if (!empty($this->stack)) {
$node->setAttribute('parent', $this->stack[count($this->stack) - 1]);
$parent = $this->stack[count($this->stack) - 1];
if ($this->weakReferences) {
$parent = \WeakReference::create($parent);
}
$node->setAttribute('parent', $parent);
}

$this->stack[] = $node;
Expand Down
18 changes: 18 additions & 0 deletions test/PhpParser/NodeVisitor/ParentConnectingVisitorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,22 @@ public function testConnectsChildNodeToParentNode(): void {

$this->assertSame('C', $node->getAttribute('parent')->name->toString());
}

public function testWeakReferences(): void {
$ast = (new ParserFactory())->createForNewestSupportedVersion()->parse(
'<?php class C { public function m() {} }'
);

$traverser = new NodeTraverser();

$traverser->addVisitor(new ParentConnectingVisitor(true));

$ast = $traverser->traverse($ast);

$node = (new NodeFinder())->findFirstInstanceof($ast, ClassMethod::class);

$weakReference = $node->getAttribute('parent');
$this->assertInstanceOf(\WeakReference::class, $weakReference);
$this->assertSame('C', $weakReference->get()->name->toString());
}
}

0 comments on commit e002a95

Please sign in to comment.