File tree 3 files changed +59
-0
lines changed
3 files changed +59
-0
lines changed Original file line number Diff line number Diff line change @@ -146,6 +146,31 @@ public function it_can_remove(): void
146
146
->shouldReturn (0 );
147
147
}
148
148
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
+
149
174
public function it_is_initializable (): void
150
175
{
151
176
$ this
Original file line number Diff line number Diff line change @@ -313,6 +313,27 @@ static function ($child) use ($nodes) {
313
313
return $ this ;
314
314
}
315
315
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
+
316
337
/**
317
338
* {@inheritdoc}
318
339
*/
Original file line number Diff line number Diff line change @@ -161,6 +161,19 @@ public function level(int $level): Traversable;
161
161
*/
162
162
public function remove (NodeInterface ...$ node ): NodeInterface ;
163
163
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
+
164
177
/**
165
178
* Set the parent.
166
179
*
You can’t perform that action at this time.
0 commit comments