Skip to content

Commit 5ed2e83

Browse files
committed
Added replaceNode method
implements paquettg#52
1 parent a06a0ae commit 5ed2e83

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/PHPHtmlParser/Dom/InnerNode.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,7 @@ public function removeChild($id)
181181
* @param int $id
182182
* @return AbstractNode
183183
* @uses $this->getChild()
184+
* @throws ChildNotFoundException
184185
*/
185186
public function nextChild($id)
186187
{
@@ -196,6 +197,7 @@ public function nextChild($id)
196197
* @param int $id
197198
* @return AbstractNode
198199
* @uses $this->getChild()
200+
* @throws ChildNotFoundException
199201
*/
200202
public function previousChild($id)
201203
{
@@ -223,6 +225,25 @@ public function isChild($id)
223225
return false;
224226
}
225227

228+
/**
229+
* Removes the child with id $childId and replace it with the new child
230+
* $newChild.
231+
*
232+
* @param int $childId
233+
* @param AbstractNode $newChild
234+
* @throws ChildNotFoundException
235+
*/
236+
public function replaceChild($childId, AbstractNode $newChild)
237+
{
238+
$oldChild = $this->getChild($childId);
239+
$keys = array_keys($this->children);
240+
$index = array_search($childId, $keys, true);
241+
$keys[$index] = $newChild->id();
242+
$this->children = array_combine($keys, $this->children);
243+
$this->children[$newChild->id()] = $newChild;
244+
unset($oldChild);
245+
}
246+
226247
/**
227248
* Checks if the given node id is a descendant of the
228249
* current node.

tests/Node/ParentTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,19 @@ public function testLastChild()
137137
$this->assertEquals($child3->id(), $parent->lastChild()->id());
138138
}
139139

140+
public function testReplaceChild()
141+
{
142+
$parent = new Node;
143+
$child = new Node;
144+
$child2 = new Node;
145+
$child3 = new Node;
146+
$parent->addChild($child);
147+
$parent->addChild($child2);
148+
$parent->replaceChild($child->id(), $child3);
149+
150+
$this->assertFalse($parent->isChild($child->id()));
151+
}
152+
140153
/**
141154
* @expectedException PHPHtmlParser\Exceptions\CircularException
142155
*/

0 commit comments

Comments
 (0)