Repository navigation
Description
Description of the bug
With the current engine (CSS\DOMTraverser, used by find() and the qp()/htmlqp()/html5qp() factories), :has() never matches, whatever its argument. The legacy engine (QueryPathEventHandler, used by remove() and replaceAll()) gets the same selectors right, so the two engines disagree:
$xml = '<?xml version="1.0"?><root><ul id="a"><li/><li/></ul><ul id="b"><li/><li/><li/></ul></root>';
qp($xml)->find('ul:has(li)'); // (none) expected: a, b
qp($xml)->remove('ul:has(li)'); // a, b
qp($xml)->find('ul:has(li:nth-child(3))'); // (none) expected: b
qp($xml)->remove('ul:has(li:nth-child(3))'); // bSame result through html5qp(), and for body:has(ul), ul:has(> li), ul:has(li:first-child), ul:has(li:eq(1)). Consequently :not(:has(...)) is always true: find('ul:not(:has(li))') returns every ul.
Cause
PseudoClass::has() (src/CSS/DOMTraverser/PseudoClass.php) builds a DOMTraverser in initialized mode over the node itself:
protected function has($node, $selector): bool
{
$splos = new SPLObjectStorage();
$splos->offsetSet($node);
$traverser = new DOMTraverser($splos, true);
$results = $traverser->find($selector)->matches();
return count($results) > 0;
}Initialized mode treats the supplied nodes as the candidates (the "is this node a match?" question that is() and filter() ask after #72), so ul:has(li) asks whether the ul is an li. CSS :has() asks whether the element has a descendant (or, for a relative selector like > li, a related element) matching the argument, which is a non-initialized search rooted at the node. Verified: changing that line to a descendant search rooted at the node, new DOMTraverser($splos, false, $node), makes every find() result above agree with remove().
That one-line change is not the fix on its own, though: isNot() is defined as ! $this->has(), and :not() genuinely needs the initialized "is this node a match?" semantics (li:not(.x) asks whether the li is .x, not whether it contains one). The fix needs isNot() to keep the current body, with has() switched to the descendant search, plus tests for both.
QueryPath version
main at 95dbf53.
PHP Version and environment
PHP 8.5 CLI (macOS).
Related
- Nested parentheses in
:has()'s argument also throw a parse error; see Doubly nested parentheses in a selector throw "Recursion error detected" (e.g.li:not(:not(:nth-child(1)))) #120. - Move "match these nodes against a selector" into DOMTraverser instead of NodeMatcher #116 proposes consolidating the "match these nodes" helpers, which includes
PseudoClass::has().
Activity