From 19073e3e0bb50cbc1cb286077069b3107085206f Mon Sep 17 00:00:00 2001 From: Tom Kaminski Date: Fri, 14 Feb 2025 09:16:52 -0600 Subject: [PATCH] Check for null parent Nodes in the case of orphaned branches --- Crawler.php | 2 +- Tests/AbstractCrawlerTestCase.php | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/Crawler.php b/Crawler.php index ac5a983..005a693 100644 --- a/Crawler.php +++ b/Crawler.php @@ -431,7 +431,7 @@ public function closest(string $selector): ?self $domNode = $this->getNode(0); - while (\XML_ELEMENT_NODE === $domNode->nodeType) { + while (null !== $domNode && \XML_ELEMENT_NODE === $domNode->nodeType) { $node = $this->createSubCrawler($domNode); if ($node->matches($selector)) { return $node; diff --git a/Tests/AbstractCrawlerTestCase.php b/Tests/AbstractCrawlerTestCase.php index 97b16b9..5cdbbbf 100644 --- a/Tests/AbstractCrawlerTestCase.php +++ b/Tests/AbstractCrawlerTestCase.php @@ -1031,6 +1031,29 @@ public function testClosest() $this->assertNull($notFound); } + public function testClosestWithOrphanedNode() + { + $html = <<<'HTML' + + +
+
+
+ + +HTML; + + $crawler = $this->createCrawler($this->getDoctype().$html); + $foo = $crawler->filter('#foo'); + + $fooNode = $foo->getNode(0); + + $fooNode->parentNode->replaceChild($fooNode->ownerDocument->createElement('ol'), $fooNode); + + $body = $foo->closest('body'); + $this->assertNull($body); + } + public function testOuterHtml() { $html = <<<'HTML'