Skip to content

Commit

Permalink
Support WeakReferences in NodeConnectingVisitor
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm committed Jan 1, 2025
1 parent 7d3039c commit 4cac2f2
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
21 changes: 18 additions & 3 deletions lib/PhpParser/NodeVisitor/NodeConnectingVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,34 @@ final class NodeConnectingVisitor extends NodeVisitorAbstract {
*/
private $previous;

private bool $weakReferences;

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

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

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);
}

if ($this->previous !== null && $this->previous->getAttribute('parent') === $node->getAttribute('parent')) {
$node->setAttribute('previous', $this->previous);
$this->previous->setAttribute('next', $node);
if ($this->weakReferences) {
$node->setAttribute('previous', \WeakReference::create($this->previous));
$this->previous->setAttribute('next', \WeakReference::create($node));
} else {
$node->setAttribute('previous', $this->previous);
$this->previous->setAttribute('next', $node);
}
}

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

$this->assertSame(Else_::class, get_class($node->getAttribute('next')));
}

public function testWeakReferences(): void {
$ast = (new ParserFactory())->createForNewestSupportedVersion()->parse(
'<?php if (true) {} else {}'
);

$traverser = new NodeTraverser();

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

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

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

$this->assertInstanceOf(\WeakReference::class, $node->getAttribute('parent'));
$this->assertSame(If_::class, get_class($node->getAttribute('parent')->get()));
$this->assertInstanceOf(\WeakReference::class, $node->getAttribute('previous'));
$this->assertSame(ConstFetch::class, get_class($node->getAttribute('previous')->get()));

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

$this->assertInstanceOf(\WeakReference::class, $node->getAttribute('next'));
$this->assertSame(Else_::class, get_class($node->getAttribute('next')->get()));
}
}

0 comments on commit 4cac2f2

Please sign in to comment.