[Crawler] Add proper validation of node argument of method add

This commit is contained in:
entering 2013-05-03 23:53:35 +01:00 committed by Fabien Potencier
parent a7608d9115
commit 41805c042d
2 changed files with 21 additions and 3 deletions

View File

@ -58,7 +58,9 @@ class Crawler extends \SplObjectStorage
* This method uses the appropriate specialized add*() method based * This method uses the appropriate specialized add*() method based
* on the type of the argument. * on the type of the argument.
* *
* @param null|\DOMNodeList|array|\DOMNode $node A node * @param \DOMNodeList|\DOMNode|array|string|null $node A node
*
* @throws \InvalidArgumentException When node is not the expected type.
* *
* @api * @api
*/ */
@ -66,12 +68,19 @@ class Crawler extends \SplObjectStorage
{ {
if ($node instanceof \DOMNodeList) { if ($node instanceof \DOMNodeList) {
$this->addNodeList($node); $this->addNodeList($node);
} elseif ($node instanceof \DOMNode) {
$this->addNode($node);
} elseif (is_array($node)) { } elseif (is_array($node)) {
$this->addNodes($node); $this->addNodes($node);
} elseif (is_string($node)) { } elseif (is_string($node)) {
$this->addContent($node); $this->addContent($node);
} elseif (is_object($node)) { } elseif ($node !== null) {
$this->addNode($node); throw new \InvalidArgumentException(
sprintf(
'Expecting node to be DOMNodeList|DOMNode|array|string|null, but got %s',
(is_object($node)) ? get_class($node) : gettype($node)
)
);
} }
} }

View File

@ -53,6 +53,15 @@ class CrawlerTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('Foo', $crawler->filterXPath('//body')->text(), '->add() adds nodes from a string'); $this->assertEquals('Foo', $crawler->filterXPath('//body')->text(), '->add() adds nodes from a string');
} }
/**
* @expectedException \InvalidArgumentException
*/
public function testAddInvalidNode()
{
$crawler = new Crawler();
$crawler->add(1);
}
/** /**
* @covers Symfony\Component\DomCrawler\Crawler::addHtmlContent * @covers Symfony\Component\DomCrawler\Crawler::addHtmlContent
*/ */