Merge pull request #186 from mnapoli/clone-nodes

Added a flag to NodeTraverser to avoid cloning nodes
This commit is contained in:
Nikita Popov 2015-03-22 15:19:10 +01:00
commit 879e8dcd6d
2 changed files with 29 additions and 3 deletions

View File

@ -10,10 +10,18 @@ class NodeTraverser implements NodeTraverserInterface
protected $visitors;
/**
* Constructs a node traverser.
* @var bool
*/
public function __construct() {
private $cloneNodes;
/**
* Constructs a node traverser.
*
* @param bool $cloneNodes Should the traverser clone the nodes when traversing the AST
*/
public function __construct($cloneNodes = true) {
$this->visitors = array();
$this->cloneNodes = $cloneNodes;
}
/**
@ -65,7 +73,9 @@ class NodeTraverser implements NodeTraverserInterface
}
protected function traverseNode(Node $node) {
$node = clone $node;
if ($this->cloneNodes) {
$node = clone $node;
}
foreach ($node->getSubNodeNames() as $name) {
$subNode =& $node->$name;

View File

@ -184,4 +184,20 @@ class NodeTraverserTest extends \PHPUnit_Framework_TestCase
$postExpected = array(0 => $visitor1, 2 => $visitor3);
$this->assertAttributeSame($postExpected, 'visitors', $traverser, 'The appropriate visitors are not present after removal');
}
public function testCloneNodesByDefault() {
$stmts = array(new Node\Stmt\Echo_(array(new String_('Foo'), new String_('Bar'))));
$traverser = new NodeTraverser;
$this->assertNotSame($stmts, $traverser->traverse($stmts));
}
public function testCloneNodesDisabled() {
$stmts = array(new Node\Stmt\Echo_(array(new String_('Foo'), new String_('Bar'))));
$traverser = new NodeTraverser(false);
$this->assertSame($stmts, $traverser->traverse($stmts));
}
}