Skip to content

Commit

Permalink
Add SVGNodeContainer::setChild method
Browse files Browse the repository at this point in the history
See #51.
  • Loading branch information
meyfa committed Mar 21, 2018
1 parent 9e50562 commit 48c3980
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 3 deletions.
27 changes: 24 additions & 3 deletions src/Nodes/SVGNodeContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,13 @@ public function addChild(SVGNode $node, $index = null)
* Removes a child node, given either as its instance or as the index it's
* located at, from this container.
*
* @param SVGNode|int $nodeOrIndex The node (or respective index) to remove.
* @param SVGNode|int $child The node (or respective index) to remove.
*
* @return $this This node instance, for call chaining.
*/
public function removeChild($nodeOrIndex)
public function removeChild($child)
{
$index = $this->resolveChildIndex($nodeOrIndex);
$index = $this->resolveChildIndex($child);
if ($index === false) {
return $this;
}
Expand All @@ -84,6 +84,27 @@ public function removeChild($nodeOrIndex)
return $this;
}

/**
* Replaces a child node with another node.
*
* @param SVGNode|int $child The node (or respective index) to replace.
* @param SVGNode $node The replacement node.
*
* @return $this This node instance, for call chaining.
*/
public function setChild($child, SVGNode $node)
{
$index = $this->resolveChildIndex($child);
if ($index === false) {
return $this;
}

$this->removeChild($index);
$this->addChild($node, $index);

return $this;
}

/**
* Resolves a child node to its index. If an index is given, it is returned
* without modification.
Expand Down
29 changes: 29 additions & 0 deletions tests/Nodes/SVGNodeContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,35 @@ public function testRemoveChild()
$this->assertSame($obj, $obj->removeChild($child));
}

public function testSetChild()
{
$obj = new SVGNodeContainerSubclass();
$obj2 = new SVGNodeContainerSubclass();

$child = new SVGNodeContainerSubclass();
$child2 = new SVGNodeContainerSubclass();

$obj->addChild($child);

// should replace by instance
$obj->setChild($child, $child2);
$this->assertSame(1, $obj->countChildren());
$this->assertSame($child2, $obj->getChild(0));

// should replace by index
$obj->setChild(0, $child);
$this->assertSame(1, $obj->countChildren());
$this->assertSame($child, $obj->getChild(0));

// should do nothing if instance does not exist
$obj->setChild(new SVGNodeContainerSubclass(), $child2);
$this->assertSame(1, $obj->countChildren());
$this->assertSame($child, $obj->getChild(0));

// should return same instance
$this->assertSame($obj, $obj->setChild(0, $child2));
}

public function testRasterize()
{
$obj = new SVGNodeContainerSubclass();
Expand Down

0 comments on commit 48c3980

Please sign in to comment.