From 762e112289693fda3b8fc6f039db9d36a50c6e10 Mon Sep 17 00:00:00 2001 From: Caen De Silva Date: Fri, 6 Dec 2024 13:28:14 +0100 Subject: [PATCH 1/2] Use more reliable XPath instead of manual traversal --- .../HtmlTesting/TestableHtmlDocument.php | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/packages/testing/src/Support/HtmlTesting/TestableHtmlDocument.php b/packages/testing/src/Support/HtmlTesting/TestableHtmlDocument.php index 3b90ebb9946..ff4ea3bfdf3 100644 --- a/packages/testing/src/Support/HtmlTesting/TestableHtmlDocument.php +++ b/packages/testing/src/Support/HtmlTesting/TestableHtmlDocument.php @@ -80,21 +80,18 @@ public function getElementUsingQuery(string $selector): TestableHtmlElement */ public function getElementsByClass(string $class): Collection { - $matchingNodes = collect(); - - $traverse = function (TestableHtmlElement $node) use (&$traverse, $class, &$matchingNodes): void { - if (in_array($class, $node->classes, true)) { - $matchingNodes->push($node); - } - - foreach ($node->nodes as $childNode) { - $traverse($childNode); + $xpath = new \DOMXPath($this->document); // Use the existing DOMDocument + $nodeList = $xpath->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $class ')]"); + + $collection = collect(); + foreach ($nodeList as $node) { + // Ensure we are only adding DOMElement objects to the collection. + if ($node instanceof DOMElement) { + $collection->push($this->parseNodeRecursive($node)); } - }; - - $traverse($this->getRootElement()); + } - return $matchingNodes; + return $collection; } /** From 673573cc6164f9cdbc590aeab56de855105b9e6b Mon Sep 17 00:00:00 2001 From: Caen De Silva Date: Fri, 6 Dec 2024 13:30:06 +0100 Subject: [PATCH 2/2] Clean up the code --- .../testing/src/Support/HtmlTesting/TestableHtmlDocument.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/testing/src/Support/HtmlTesting/TestableHtmlDocument.php b/packages/testing/src/Support/HtmlTesting/TestableHtmlDocument.php index ff4ea3bfdf3..463357807ba 100644 --- a/packages/testing/src/Support/HtmlTesting/TestableHtmlDocument.php +++ b/packages/testing/src/Support/HtmlTesting/TestableHtmlDocument.php @@ -6,6 +6,7 @@ use DOMElement; use DOMDocument; +use DOMXPath; use InvalidArgumentException; use Illuminate\Support\Collection; use Illuminate\Testing\Assert as PHPUnit; @@ -80,12 +81,11 @@ public function getElementUsingQuery(string $selector): TestableHtmlElement */ public function getElementsByClass(string $class): Collection { - $xpath = new \DOMXPath($this->document); // Use the existing DOMDocument + $xpath = new DOMXPath($this->document); $nodeList = $xpath->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $class ')]"); $collection = collect(); foreach ($nodeList as $node) { - // Ensure we are only adding DOMElement objects to the collection. if ($node instanceof DOMElement) { $collection->push($this->parseNodeRecursive($node)); }