Skip to content

Commit 9fa8255

Browse files
Share the sibling index with the queries :has() runs
findsAny() built each per-element and per-sibling traverser with its own PseudoClass, so with #119's index every one re-indexed its sibling list: li:has(~ li:nth-child(1)) over 400 siblings took about 9 s. It now passes its own handler, as is() does, which also lets a nested :has() reuse the parsed-argument cache (about 0.26 s). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent d48cdc0 commit 9fa8255

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

‎src/CSS/DOMTraverser/PseudoClass.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -508,7 +508,7 @@ protected function findsAny(DOMElement $root, DOMElement $scope, array $group, b
508508
foreach ($group as $simpleSelector) {
509509
$copy[] = clone $simpleSelector;
510510
}
511-
$traverser = new DOMTraverser($splos, $self, $scope);
511+
$traverser = new DOMTraverser($splos, $self, $scope, $this);
512512

513513
return count($traverser->findGroups([$copy])->matches()) > 0;
514514
}

‎tests/QueryPath/CSS/PseudoClassTest.php‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -721,6 +721,28 @@ public function testNestedQueriesShareTheSiblingIndex()
721721
$this->assertSame(1, $ps->indexed);
722722
}
723723

724+
/**
725+
* :has() runs a query per element, and per later sibling, which must all reuse one index.
726+
*
727+
* @testWith ["a:has(+ b:nth-child(even))", 50]
728+
* ["a:has(~ b:nth-last-child(1))", 50]
729+
* ["root:has(> b:nth-of-type(50))", 1]
730+
*/
731+
public function testHasQueriesShareTheSiblingIndex($selector, $count)
732+
{
733+
$xml = '<?xml version="1.0"?><root>' . str_repeat('<a/><b/>', 50) . '</root>';
734+
[$ele, $root] = $this->doc($xml, 'root');
735+
736+
$splos = new SplObjectStorage();
737+
$splos->offsetSet($root);
738+
739+
$ps = $this->countingPseudoClass();
740+
$traverser = new DOMTraverser($splos, false, null, $ps);
741+
742+
$this->assertCount($count, $traverser->find($selector)->matches());
743+
$this->assertSame(1, $ps->indexed);
744+
}
745+
724746
public function testNthChildDoesNotReusePositionsFromAnEarlierQuery()
725747
{
726748
$xml = '<?xml version="1.0"?><root><a/><b/><c/></root>';

0 commit comments

Comments
 (0)