Skip to content

Commit bec9ec9

Browse files
committed
Fix replaceChild() method
1 parent 9663472 commit bec9ec9

File tree

1 file changed

+28
-7
lines changed

1 file changed

+28
-7
lines changed

src/PHPHtmlParser/Dom/InnerNode.php

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -231,17 +231,38 @@ public function isChild($id)
231231
*
232232
* @param int $childId
233233
* @param AbstractNode $newChild
234+
*
235+
* @return $this
234236
* @throws ChildNotFoundException
235237
*/
236238
public function replaceChild($childId, AbstractNode $newChild)
237239
{
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);
240+
$oldChild = $this->getChild($childId);
241+
242+
// handle moving next and previous assignments.
243+
$next = $this->children[$oldChild->id()]['next'];
244+
$prev = $this->children[$oldChild->id()]['prev'];
245+
if ( ! is_null($next)) {
246+
$this->children[$next]['prev'] = $newChild->id();
247+
}
248+
if ( ! is_null($prev)) {
249+
$this->children[$prev]['next'] = $newChild->id();
250+
}
251+
252+
// set the new child
253+
$this->children[$newChild->id()] = [
254+
'node' => $newChild,
255+
'next' => $oldChild->nextSibling()->id(),
256+
'prev' => $oldChild->previousSibling()->id(),
257+
];
258+
259+
// remove the old child
260+
unset($this->children[$oldChild->id()]);
261+
262+
//clear any cache
263+
$this->clear();
264+
265+
return $this;
245266
}
246267

247268
/**

0 commit comments

Comments
 (0)