|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace QueryPathTests; |
| 4 | + |
| 5 | +/** |
| 6 | + * find() searches descendants, as jQuery's find() does. |
| 7 | + * |
| 8 | + * A node already in the match set is not a candidate for its own selector. The document |
| 9 | + * element is the one exception, because QueryPath seeds the match set with the document |
| 10 | + * element rather than with the document node. |
| 11 | + */ |
| 12 | +class FindDescendantOnlyTest extends TestCase |
| 13 | +{ |
| 14 | + |
| 15 | + const XML = '<?xml version="1.0"?><root><a id="a1"><a id="a2"/><b id="b1"/></a></root>'; |
| 16 | + |
| 17 | + public function testFindDoesNotMatchTheNodesItStartsFrom(): void |
| 18 | + { |
| 19 | + $a1 = qp(self::XML, '#a1'); |
| 20 | + $this->assertSame('a1', $a1->attr('id')); |
| 21 | + |
| 22 | + // <a id="a1"> is in the match set, so it is not a candidate: only the nested |
| 23 | + // <a id="a2"> is found. |
| 24 | + $found = $a1->find('a'); |
| 25 | + $this->assertCount(1, $found); |
| 26 | + $this->assertSame('a2', $found->attr('id')); |
| 27 | + } |
| 28 | + |
| 29 | + public function testWildcardDoesNotMatchTheNodesItStartsFrom(): void |
| 30 | + { |
| 31 | + $ids = []; |
| 32 | + foreach (qp(self::XML, '#a1')->find('*') as $node) { |
| 33 | + $ids[] = $node->attr('id'); |
| 34 | + } |
| 35 | + |
| 36 | + $this->assertSame(['a2', 'b1'], $ids); |
| 37 | + } |
| 38 | + |
| 39 | + public function testTheDocumentElementIsStillReachable(): void |
| 40 | + { |
| 41 | + // qp() seeds the match set with the document element, which stands in for the |
| 42 | + // document, so a selector naming it has to keep working. |
| 43 | + $this->assertCount(1, qp(self::XML)->find('root')); |
| 44 | + $this->assertSame('root', qp(self::XML)->find('root')->tag()); |
| 45 | + |
| 46 | + $this->assertCount(1, qp(self::XML)->find(':root')); |
| 47 | + } |
| 48 | + |
| 49 | + public function testDescendantsOfTheDocumentElementAreStillFound(): void |
| 50 | + { |
| 51 | + $this->assertCount(2, qp(self::XML)->find('a')); |
| 52 | + $this->assertCount(1, qp(self::XML)->find('b')); |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * filter() is the jQuery-equivalent way to ask whether the nodes in hand match. |
| 57 | + */ |
| 58 | + public function testFilterIsTheWayToMatchTheNodesInHand(): void |
| 59 | + { |
| 60 | + $this->assertCount(1, qp(self::XML, '#a1')->filter('a')); |
| 61 | + $this->assertSame('a1', qp(self::XML, '#a1')->filter('a')->attr('id')); |
| 62 | + } |
| 63 | +} |
0 commit comments