Skip to content
Merged
Show file tree
Hide file tree
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
28 changes: 20 additions & 8 deletions src/PHPHtmlParser/Dom/InnerNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -235,13 +235,25 @@ public function isChild($id)
*/
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);
// Replace key of old child
$keys = array_keys($this->children);
$index = array_search($childId, $keys, true);
$keys[$index] = $newChild->id();
$this->children = array_combine($keys, $this->children);

// Replace old child node with new one
$this->children[$newChild->id()]['node'] = $newChild;

$child = $this->children[$newChild->id()];

// Update previous and next nodes
if ($child['prev'] !== null) {
$this->children[$child['prev']]['next'] = $newChild->id();
}

if ($child['next'] !== null) {
$this->children[$child['next']]['prev'] = $newChild->id();
}
}

/**
Expand Down Expand Up @@ -314,4 +326,4 @@ public function setParent(InnerNode $parent)

return parent::setParent($parent);
}
}
}
56 changes: 52 additions & 4 deletions tests/Node/ParentTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -142,14 +142,62 @@ public function testLastChild()
public function testReplaceChild()
{
$parent = new Node;
$child = new Node;
$child1 = new Node;
$child2 = new Node;
$child3 = new Node;
$parent->addChild($child);
$child4 = new Node;
$parent->addChild($child1);
$parent->addChild($child2);
$parent->replaceChild($child->id(), $child3);
$parent->addChild($child3);

$this->assertFalse($parent->isChild($child->id()));
self::assertAttributeEquals(
[
$child1->id() => [
'next' => $child2->id(),
'prev' => null,
'node' => $child1,
],
$child2->id() => [
'next' => $child3->id(),
'prev' => $child1->id(),
'node' => $child2,
],
$child3->id() => [
'next' => null,
'prev' => $child2->id(),
'node' => $child3,
],
],
'children',
$parent
);

$parent->replaceChild($child2->id(), $child4);

$this->assertFalse($parent->isChild($child2->id()));
$this->assertTrue($parent->isChild($child4->id()));

self::assertAttributeEquals(
[
$child1->id() => [
'next' => $child4->id(),
'prev' => null,
'node' => $child1,
],
$child3->id() => [
'next' => null,
'prev' => $child4->id(),
'node' => $child3,
],
$child4->id() => [
'next' => $child3->id(),
'prev' => $child1->id(),
'node' => $child4,
],
],
'children',
$parent
);
}

public function testSetParentDescendantException()
Expand Down