Skip to content

Commit 10553ab

Browse files
committed
CloningVisitor
1 parent 00d0fcd commit 10553ab

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

Diff for: src/Ast/Attribute.php

+2
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,6 @@ final class Attribute
1111
public const START_INDEX = 'startIndex';
1212
public const END_INDEX = 'endIndex';
1313

14+
public const ORIGINAL_NODE = 'originalNode';
15+
1416
}

Diff for: src/Ast/NodeVisitor/CloningVisitor.php

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\PhpDocParser\Ast\NodeVisitor;
4+
5+
use PHPStan\PhpDocParser\Ast\AbstractNodeVisitor;
6+
use PHPStan\PhpDocParser\Ast\Attribute;
7+
use PHPStan\PhpDocParser\Ast\Node;
8+
9+
final class CloningVisitor extends AbstractNodeVisitor
10+
{
11+
12+
public function enterNode(Node $originalNode)
13+
{
14+
$node = clone $originalNode;
15+
$node->setAttribute(Attribute::ORIGINAL_NODE, $originalNode);
16+
17+
return $node;
18+
}
19+
20+
}

Diff for: tests/PHPStan/Ast/NodeVisitor/CloningVisitorTest.php

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\PhpDocParser\Ast\NodeVisitor;
4+
5+
use PHPStan\PhpDocParser\Ast\Attribute;
6+
use PHPStan\PhpDocParser\Ast\NodeTraverser;
7+
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
8+
use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode;
9+
use PHPUnit\Framework\TestCase;
10+
11+
class CloningVisitorTest extends TestCase
12+
{
13+
14+
public function testVisitor(): void
15+
{
16+
$visitor = new CloningVisitor();
17+
$traverser = new NodeTraverser([$visitor]);
18+
$identifier = new IdentifierTypeNode('Foo');
19+
$node = new NullableTypeNode($identifier);
20+
21+
$newNodes = $traverser->traverse([$node]);
22+
$this->assertCount(1, $newNodes);
23+
$this->assertInstanceOf(NullableTypeNode::class, $newNodes[0]);
24+
$this->assertNotSame($node, $newNodes[0]);
25+
$this->assertSame($node, $newNodes[0]->getAttribute(Attribute::ORIGINAL_NODE));
26+
27+
$this->assertInstanceOf(IdentifierTypeNode::class, $newNodes[0]->type);
28+
$this->assertNotSame($identifier, $newNodes[0]->type);
29+
$this->assertSame($identifier, $newNodes[0]->type->getAttribute(Attribute::ORIGINAL_NODE));
30+
}
31+
32+
}

0 commit comments

Comments
 (0)