Skip to content

Commit

Permalink
Add getElementsByTagName method to nodes
Browse files Browse the repository at this point in the history
  • Loading branch information
meyfa committed Jan 31, 2018
1 parent 936d22c commit 2283a21
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Nodes/SVGNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -263,4 +263,23 @@ public function getViewBox()
* @return void
*/
abstract public function rasterize(SVGRasterizer $rasterizer);

/**
* Returns all descendants of this node (excluding this node) having the
* given tag name. '*' matches all nodes.
*
* Example: getElementsByTagName('rect')
* would return all <rect /> nodes that are descendants of this node.
*
* @param string $tagName The tag name to search for ('*' to match all).
* @param SVGNode[] $result The array to fill. Can be omitted.
*
* @return SVGNode[] An array of matching elements.
*
* @SuppressWarnings("unused")
*/
public function getElementsByTagName($tagName, array &$result = array())
{
return $result;
}
}
12 changes: 12 additions & 0 deletions src/Nodes/SVGNodeContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -196,4 +196,16 @@ private function pregGrepStyle($pattern)
{
return preg_grep($pattern, array_keys($this->containerStyles));
}

public function getElementsByTagName($tagName, array &$result = array())
{
foreach ($this->children as $child) {
if ($tagName === '*' || $child->getName() === $tagName) {
$result[] = $child;
}
$child->getElementsByTagName($tagName, $result);
}

return $result;
}
}
36 changes: 36 additions & 0 deletions tests/Nodes/SVGNodeContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,40 @@ public function testRasterize()
$obj->setStyle('display', 'none');
$obj->rasterize($rast);
}

public function testGetElementsByTagName()
{
$obj = new SVGNodeContainerSubclass();
$obj->addChild(
($root_0 = new \SVG\Nodes\Structures\SVGGroup())->addChild(
$root_0_0 = new \SVG\Nodes\Shapes\SVGLine()
)->addChild(
$root_0_1 = new \SVG\Nodes\Shapes\SVGRect()
)
);
$obj->addChild(
($root_1 = new \SVG\Nodes\Structures\SVGGroup())->addChild(
($root_1_0 = new \SVG\Nodes\Structures\SVGGroup())->addChild(
$root_1_0_0 = new \SVG\Nodes\Shapes\SVGRect()
)
)->addChild(
$root_1_1 = new \SVG\Nodes\Shapes\SVGRect()
)
);

// should not return itself
$this->assertSame(array(), $obj->getElementsByTagName('test_subclass'));
$this->assertNotContains($obj, $obj->getElementsByTagName('*'));

// should return specific tags
$this->assertSame(array(
$root_0_1, $root_1_0_0, $root_1_1,
), $obj->getElementsByTagName('rect'));

// should return all descendants for '*'
$this->assertSame(array(
$root_0, $root_0_0, $root_0_1,
$root_1, $root_1_0, $root_1_0_0, $root_1_1,
), $obj->getElementsByTagName('*'));
}
}

0 comments on commit 2283a21

Please sign in to comment.