Skip to content

:has() never matches in find(): qp($xml)->find('ul:has(li)') returns nothing #121

Closed

Description

@gravitypdf-bot

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))'); // b

Same 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions