Skip to content

Commit

Permalink
Add support for adding children at specific index
Browse files Browse the repository at this point in the history
See #51.
  • Loading branch information
meyfa committed Mar 21, 2018
1 parent 770f1e8 commit 9e50562
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
17 changes: 11 additions & 6 deletions src/Nodes/SVGNodeContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,16 @@ public function __construct()
}

/**
* Adds an SVGNode instance to the end of this container's child list.
* Does nothing if it already exists.
* Inserts an SVGNode instance at the given index, or, if no index is given,
* at the end of the child list.
* Does nothing if the node already exists in this container.
*
* @param SVGNode $node The node to add to this container's children.
* @param SVGNode $node The node to add to this container's children.
* @param int $index The position to insert at (optional).
*
* @return $this This node instance, for call chaining.
*/
public function addChild(SVGNode $node)
public function addChild(SVGNode $node, $index = null)
{
if ($node === $this || $node->parent === $this) {
return $this;
Expand All @@ -45,8 +47,11 @@ public function addChild(SVGNode $node)
$node->parent->removeChild($node);
}

$this->children[] = $node;
$node->parent = $this;
$index = ($index !== null) ? $index : count($this->children);

// insert and set new parent
array_splice($this->children, $index, 0, array($node));
$node->parent = $this;

if ($node instanceof SVGStyle) {
// if node is SVGStyle then add rules to container's style
Expand Down
11 changes: 11 additions & 0 deletions tests/Nodes/SVGNodeContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ public function testAddChild()
{
$obj = new SVGNodeContainerSubclass();
$obj2 = new SVGNodeContainerSubclass();

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

// should add the child
$obj->addChild($child);
Expand All @@ -45,6 +48,14 @@ public function testAddChild()
$this->assertSame($obj, $obj->addChild($child));
$this->assertSame($obj, $obj->addChild($child));
$this->assertSame($obj, $obj->addChild($obj));

// should add at the given position
$obj->addChild($child, 0);
$obj->addChild($child2, 0);
$obj->addChild($child3, 2);
$this->assertSame($child2, $obj->getChild(0));
$this->assertSame($child, $obj->getChild(1));
$this->assertSame($child3, $obj->getChild(2));
}

public function testRemoveChild()
Expand Down

0 comments on commit 9e50562

Please sign in to comment.