From d1287358030004ad2c71acf49c6300f0be5fa5cc Mon Sep 17 00:00:00 2001 From: Christophe Coevoet Date: Sat, 3 Oct 2015 01:19:52 +0200 Subject: [PATCH] Fix the crawler refactoring --- src/Symfony/Component/DomCrawler/Crawler.php | 30 ++++++++++--------- .../DomCrawler/Tests/CrawlerTest.php | 10 +++++++ 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/src/Symfony/Component/DomCrawler/Crawler.php b/src/Symfony/Component/DomCrawler/Crawler.php index 4a4d4995533f1..a3c875986a723 100644 --- a/src/Symfony/Component/DomCrawler/Crawler.php +++ b/src/Symfony/Component/DomCrawler/Crawler.php @@ -18,7 +18,7 @@ * * @author Fabien Potencier */ -class Crawler implements \Countable +class Crawler implements \Countable, \IteratorAggregate { /** * @var string The current URI @@ -46,7 +46,7 @@ class Crawler implements \Countable private $document; /** - * @var \DOMNode[] + * @var \DOMElement[] */ private $nodes = array(); @@ -327,25 +327,19 @@ public function addNode(\DOMNode $node) } if (null !== $this->document && $this->document !== $node->ownerDocument) { - @trigger_error('Attaching DOM nodes from multiple documents in a Crawler is deprecated as of 2.8 and will be forbidden in 3.0.', E_USER_DEPRECATED); + throw new \InvalidArgumentException('Attaching DOM nodes from multiple documents in the same crawler is forbidden.'); } if (null === $this->document) { $this->document = $node->ownerDocument; } - $this->nodes[] = $node; - } - - // Serializing and unserializing a crawler creates DOM objects in a corrupted state. DOM elements are not properly serializable. - public function unserialize($serialized) - { - throw new \BadMethodCallException('A Crawler cannot be serialized.'); - } + // Don't add duplicate nodes in the Crawler + if (in_array($node, $this->nodes, true)) { + return; + } - public function serialize() - { - throw new \BadMethodCallException('A Crawler cannot be serialized.'); + $this->nodes[] = $node; } /** @@ -966,6 +960,14 @@ public function count() return count($this->nodes); } + /** + * @return \ArrayIterator + */ + public function getIterator() + { + return new \ArrayIterator($this->nodes); + } + /** * @param \DOMElement $node * @param string $siblingDir diff --git a/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php b/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php index 81dc874c76632..5640e98f0a1f1 100755 --- a/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php +++ b/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php @@ -76,6 +76,16 @@ public function testAddInvalidNode() $crawler->add(new \DOMNode()); } + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Attaching DOM nodes from multiple documents in the same crawler is forbidden. + */ + public function testAddMultipleDocumentNode() + { + $crawler = $this->createTestCrawler(); + $crawler->addHtmlContent('
', 'UTF-8'); + } + /** * @covers Symfony\Component\DomCrawler\Crawler::addHtmlContent */