Skip to content

Commit

Permalink
Added the ability to add child elements to the element
Browse files Browse the repository at this point in the history
  • Loading branch information
Imangazaliev committed Mar 5, 2016
1 parent 67dab01 commit baff799
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/DiDom/Element.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace DiDom;

use DOMDocument;
use DOMElement;
use InvalidArgumentException;

class Element
Expand Down Expand Up @@ -39,6 +40,37 @@ public function __construct($name, $value = '', $attributes = [])
}
}

/**
* Adds new child at the end of the children.
*
* @param \DiDom\Element|\DOMElement|array $nodes The appended child.
*
* @return \DiDom\Element
*
* @throws \InvalidArgumentException if the provided argument is not an instance of \DOMElement or \DiDom\Element
*/
public function appendChild($nodes)
{
$nodes = is_array($nodes) ? $nodes : [$nodes];

foreach ($nodes as $node) {
if ($node instanceof Element) {
$node = $node->getNode();
}

if (!$node instanceof DOMElement) {
throw new InvalidArgumentException(sprintf('Argument 1 passed to %s must be an instance of %s\Element or DOMElement, %s given', __METHOD__, __NAMESPACE__, (is_object($node) ? get_class($node) : gettype($node))));
}

$cloned = $node->cloneNode(true);
$newNode = $this->node->ownerDocument->importNode($cloned, true);

$this->node->appendChild($newNode);
}

return $this;
}

/**
* Checks the existence of the item.
*
Expand Down
30 changes: 30 additions & 0 deletions tests/DiDom/ElementTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,36 @@ public function testCreateFromDomElement()
$this->assertEquals($node, $element->getNode());
}

/**
* @expectedException InvalidArgumentException
*/
public function testAppendChildWithInvalidArgument()
{
$element = new Element('span', 'hello');

$element->appendChild('foo');
}

public function testAppendChild()
{
$list = new Element('ul');

$this->assertCount(0, $list->find('li'));

$node = new Element('li', 'foo');
$list->appendChild($node);

$this->assertCount(1, $list->find('li'));

$items = [];
$items[] = new Element('li', 'bar');
$items[] = new Element('li', 'baz');

$list->appendChild($items);

$this->assertCount(3, $list->find('li'));
}

public function testHas()
{
$document = new \DOMDocument();
Expand Down

0 comments on commit baff799

Please sign in to comment.