Skip to content

Commit 2862d4f

Browse files
committed
Add Node::replace() method.
1 parent 90eef49 commit 2862d4f

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

spec/loophp/phptree/Node/ValueNodeSpec.php

+25
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,31 @@ public function it_can_remove(): void
146146
->shouldReturn(0);
147147
}
148148

149+
public function it_can_replace_a_node_with_another_one()
150+
{
151+
$this
152+
->beConstructedWith('root');
153+
154+
$node1 = new ValueNode('A');
155+
$node2 = new ValueNode('B');
156+
$node3 = new ValueNode('C');
157+
158+
$this
159+
->add($node1, $node2, $node3);
160+
161+
$node4 = new ValueNode('D');
162+
163+
$this
164+
->offsetGet(0)
165+
->replace($node4);
166+
167+
$this->shouldHaveSameTextExport('[root[D][B][C]]');
168+
169+
$this
170+
->replace($node4)
171+
->shouldReturn(null);
172+
}
173+
149174
public function it_is_initializable(): void
150175
{
151176
$this

src/Node/Node.php

+21
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,27 @@ static function ($child) use ($nodes) {
313313
return $this;
314314
}
315315

316+
/**
317+
* {@inheritdoc}
318+
*/
319+
public function replace(NodeInterface $node): ?NodeInterface
320+
{
321+
if (null === $parent = $this->getParent()) {
322+
return null;
323+
}
324+
325+
// Find the key of the current node in the parent.
326+
foreach ($parent->children() as $key => $child) {
327+
if ($this === $child) {
328+
$parent[$key] = $node;
329+
330+
return $parent;
331+
}
332+
}
333+
334+
return $this;
335+
}
336+
316337
/**
317338
* {@inheritdoc}
318339
*/

src/Node/NodeInterface.php

+13
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,19 @@ public function level(int $level): Traversable;
161161
*/
162162
public function remove(NodeInterface ...$node): NodeInterface;
163163

164+
/**
165+
* Replace a node with another one and return the parent.
166+
*
167+
* It may also return null if the replace failed.
168+
*
169+
* @param \loophp\phptree\Node\NodeInterface $node
170+
* The replacement node.
171+
*
172+
* @return \loophp\phptree\Node\NodeInterface|null
173+
* The node parent if successful, null otherwise.
174+
*/
175+
public function replace(NodeInterface $node): ?NodeInterface;
176+
164177
/**
165178
* Set the parent.
166179
*

0 commit comments

Comments
 (0)