Skip to content

Commit

Permalink
Use more reliable XPath instead of manual traversal
Browse files Browse the repository at this point in the history
  • Loading branch information
caendesilva committed Dec 6, 2024
1 parent 191ebc4 commit 762e112
Showing 1 changed file with 10 additions and 13 deletions.
23 changes: 10 additions & 13 deletions packages/testing/src/Support/HtmlTesting/TestableHtmlDocument.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down

0 comments on commit 762e112

Please sign in to comment.