Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix replaceChild() method #120

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 28 additions & 7 deletions src/PHPHtmlParser/Dom/InnerNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -231,17 +231,38 @@ public function isChild($id)
*
* @param int $childId
* @param AbstractNode $newChild
*
* @return $this
* @throws ChildNotFoundException
*/
public function replaceChild($childId, AbstractNode $newChild)
{
$oldChild = $this->getChild($childId);
$keys = array_keys($this->children);
$index = array_search($childId, $keys, true);
$keys[$index] = $newChild->id();
$this->children = array_combine($keys, $this->children);
$this->children[$newChild->id()] = $newChild;
unset($oldChild);
$oldChild = $this->getChild($childId);

// handle moving next and previous assignments.
$next = $this->children[$oldChild->id()]['next'];
$prev = $this->children[$oldChild->id()]['prev'];
if ( ! is_null($next)) {
$this->children[$next]['prev'] = $newChild->id();
}
if ( ! is_null($prev)) {
$this->children[$prev]['next'] = $newChild->id();
}

// set the new child
$this->children[$newChild->id()] = [
'node' => $newChild,
'next' => $oldChild->nextSibling()->id(),
'prev' => $oldChild->previousSibling()->id(),
];

// remove the old child
unset($this->children[$oldChild->id()]);

//clear any cache
$this->clear();

return $this;
}

/**
Expand Down