Skip to content

Commit

Permalink
CloningVisitor
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Apr 20, 2023
1 parent 00d0fcd commit 10553ab
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/Ast/Attribute.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,6 @@ final class Attribute
public const START_INDEX = 'startIndex';
public const END_INDEX = 'endIndex';

public const ORIGINAL_NODE = 'originalNode';

}
20 changes: 20 additions & 0 deletions src/Ast/NodeVisitor/CloningVisitor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php declare(strict_types = 1);

namespace PHPStan\PhpDocParser\Ast\NodeVisitor;

use PHPStan\PhpDocParser\Ast\AbstractNodeVisitor;
use PHPStan\PhpDocParser\Ast\Attribute;
use PHPStan\PhpDocParser\Ast\Node;

final class CloningVisitor extends AbstractNodeVisitor
{

public function enterNode(Node $originalNode)
{
$node = clone $originalNode;
$node->setAttribute(Attribute::ORIGINAL_NODE, $originalNode);

return $node;
}

}
32 changes: 32 additions & 0 deletions tests/PHPStan/Ast/NodeVisitor/CloningVisitorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php declare(strict_types = 1);

namespace PHPStan\PhpDocParser\Ast\NodeVisitor;

use PHPStan\PhpDocParser\Ast\Attribute;
use PHPStan\PhpDocParser\Ast\NodeTraverser;
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode;
use PHPUnit\Framework\TestCase;

class CloningVisitorTest extends TestCase
{

public function testVisitor(): void
{
$visitor = new CloningVisitor();
$traverser = new NodeTraverser([$visitor]);
$identifier = new IdentifierTypeNode('Foo');
$node = new NullableTypeNode($identifier);

$newNodes = $traverser->traverse([$node]);
$this->assertCount(1, $newNodes);
$this->assertInstanceOf(NullableTypeNode::class, $newNodes[0]);
$this->assertNotSame($node, $newNodes[0]);
$this->assertSame($node, $newNodes[0]->getAttribute(Attribute::ORIGINAL_NODE));

$this->assertInstanceOf(IdentifierTypeNode::class, $newNodes[0]->type);
$this->assertNotSame($identifier, $newNodes[0]->type);
$this->assertSame($identifier, $newNodes[0]->type->getAttribute(Attribute::ORIGINAL_NODE));
}

}

0 comments on commit 10553ab

Please sign in to comment.