forked from GravityPDF/querypath
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueryPathEventHandler.php
More file actions
1493 lines (1383 loc) · 40.6 KB
/
QueryPathEventHandler.php
File metadata and controls
1493 lines (1383 loc) · 40.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/** @file
* This file contains a full implementation of the EventHandler interface.
*
* The tools in this package initiate a CSS selector parsing routine and then
* handle all of the callbacks.
*
* The implementation provided herein adheres to the CSS 3 Selector specification
* with the following caveats:
*
* - The negation (:not()) and containment (:has()) pseudo-classes allow *full*
* selectors and not just simple selectors.
* - There are a variety of additional pseudo-classes supported by this
* implementation that are not part of the spec. Most of the jQuery
* pseudo-classes are supported. The :x-root pseudo-class is also supported.
* - Pseudo-classes that require a User Agent to function have been disabled.
* Thus there is no :hover pseudo-class.
* - All pseudo-elements require the double-colon (::) notation. This breaks
* backward compatibility with the 2.1 spec, but it makes visible the issue
* that pseudo-elements cannot be effectively used with most of the present
* library. They return <b>stdClass objects with a text property</b> (QP > 1.3)
* instead of elements.
* - The pseudo-classes first-of-type, nth-of-type and last-of-type may or may
* not conform to the specification. The spec is unclear.
* - pseudo-class filters of the form -an+b do not function as described in the
* specification. However, they do behave the same way here as they do in
* jQuery.
* - This library DOES provide XML namespace aware tools. Selectors can use
* namespaces to increase specificity.
* - This library does nothing with the CSS 3 Selector specificity rating. Of
* course specificity is preserved (to the best of our abilities), but there
* is no calculation done.
*
* For detailed examples of how the code works and what selectors are supported,
* see the CssEventTests file, which contains the unit tests used for
* testing this implementation.
*
* @author M Butcher <matt@aleph-null.tv>
* @license MIT
*/
namespace QueryPath\CSS;
use DOMDocument;
use DOMElement;
use DOMNode;
use DOMNodeList;
use QueryPath\Exception;
use SplObjectStorage;
use stdClass;
/**
* Handler that tracks progress of a query through a DOM.
*
* The main idea is that we keep a copy of the tree, and then use an
* array to keep track of matches. To handle a list of selectors (using
* the comma separator), we have to track both the currently progressing
* match and the previously matched elements.
*
* To use this handler:
*
* @code
* $filter = '#id'; // Some CSS selector
* $handler = new QueryPathEventHandler(DOMNode $dom);
* $parser = new Parser();
* $parser->parse($filter, $handler);
* $matches = $handler->getMatches();
* @endcode
*
* $matches will be an array of zero or more DOMElement objects.
*
* @ingroup querypath_css
*/
class QueryPathEventHandler implements EventHandler, Traverser
{
protected $dom; // Always points to the top level.
protected $matches; // The matches
protected $alreadyMatched; // Matches found before current selector.
protected $findAnyElement = true;
/**
* Create a new event handler.
*/
public function __construct($dom)
{
$this->alreadyMatched = new SplObjectStorage();
$matches = new SplObjectStorage();
// Array of DOMElements
if (is_array($dom) || $dom instanceof SplObjectStorage) {
//$matches = array();
foreach ($dom as $item) {
if ($item instanceof DOMNode && $item->nodeType == XML_ELEMENT_NODE) {
//$matches[] = $item;
$matches->attach($item);
}
}
//$this->dom = count($matches) > 0 ? $matches[0] : NULL;
if ($matches->count() > 0) {
$matches->rewind();
$this->dom = $matches->current();
} else {
//throw new Exception("Setting DOM to Null");
$this->dom = null;
}
$this->matches = $matches;
} // DOM Document -- we get the root element.
elseif ($dom instanceof DOMDocument) {
$this->dom = $dom->documentElement;
$matches->attach($dom->documentElement);
} // DOM Element -- we use this directly
elseif ($dom instanceof DOMElement) {
$this->dom = $dom;
$matches->attach($dom);
} // NodeList -- We turn this into an array
elseif ($dom instanceof DOMNodeList) {
$a = []; // Not sure why we are doing this....
foreach ($dom as $item) {
if ($item->nodeType == XML_ELEMENT_NODE) {
$matches->attach($item);
$a[] = $item;
}
}
$this->dom = $a;
}
// FIXME: Handle SimpleXML!
// Uh-oh... we don't support anything else.
else {
throw new Exception("Unhandled type: " . get_class($dom));
}
$this->matches = $matches;
}
/**
* Generic finding method.
*
* This is the primary searching method used throughout QueryPath.
*
* @param string $filter
* A valid CSS 3 filter.
*
* @return QueryPathEventHandler
* Returns itself.
* @throws ParseException
*/
public function find($filter): QueryPathEventHandler
{
$parser = new Parser($filter, $this);
$parser->parse();
return $this;
}
/**
* Get the elements that match the evaluated selector.
*
* This should be called after the filter has been parsed.
*
* @return array
* The matched items. This is almost always an array of
* {@link DOMElement} objects. It is always an instance of
* {@link DOMNode} objects.
*/
public function getMatches()
{
//$result = array_merge($this->alreadyMatched, $this->matches);
$result = new SplObjectStorage();
foreach ($this->alreadyMatched as $m) {
$result->attach($m);
}
foreach ($this->matches as $m) {
$result->attach($m);
}
return $result;
}
public function matches()
{
return $this->getMatches();
}
/**
* Find any element with the ID that matches $id.
*
* If this finds an ID, it will immediately quit. Essentially, it doesn't
* enforce ID uniqueness, but it assumes it.
*
* @param $id
* String ID for an element.
*/
public function elementID($id)
{
$found = new SplObjectStorage();
$matches = $this->candidateList();
foreach ($matches as $item) {
// Check if any of the current items has the desired ID.
if ($item->hasAttribute('id') && $item->getAttribute('id') === $id) {
$found->attach($item);
break;
}
}
$this->matches = $found;
$this->findAnyElement = false;
}
// Inherited
public function element($name)
{
$matches = $this->candidateList();
$this->findAnyElement = false;
$found = new SplObjectStorage();
foreach ($matches as $item) {
// Should the existing item be included?
// In some cases (e.g. element is root element)
// it definitely should. But what about other cases?
if ($item->tagName == $name) {
$found->attach($item);
}
// Search for matching kids.
//$nl = $item->getElementsByTagName($name);
//$found = array_merge($found, $this->nodeListToArray($nl));
}
$this->matches = $found;
}
// Inherited
public function elementNS($lname, $namespace = null)
{
$this->findAnyElement = false;
$found = new SplObjectStorage();
$matches = $this->candidateList();
foreach ($matches as $item) {
// Looking up NS URI only works if the XMLNS attributes are declared
// at a level equal to or above the searching doc. Normalizing a doc
// should fix this, but it doesn't. So we have to use a fallback
// detection scheme which basically searches by lname and then
// does a post hoc check on the tagname.
//$nsuri = $item->lookupNamespaceURI($namespace);
$nsuri = $this->dom->lookupNamespaceURI($namespace);
// XXX: Presumably the base item needs to be checked. Spec isn't
// too clear, but there are three possibilities:
// - base should always be checked (what we do here)
// - base should never be checked (only children)
// - base should only be checked if it is the root node
if ($item instanceof DOMNode
&& $item->namespaceURI == $nsuri
&& $lname == $item->localName) {
$found->attach($item);
}
if (! empty($nsuri)) {
$nl = $item->getElementsByTagNameNS($nsuri, $lname);
// If something is found, merge them:
//if (!empty($nl)) $found = array_merge($found, $this->nodeListToArray($nl));
if (! empty($nl)) {
$this->attachNodeList($nl, $found);
}
} else {
//$nl = $item->getElementsByTagName($namespace . ':' . $lname);
$nl = $item->getElementsByTagName($lname);
$tagname = $namespace . ':' . $lname;
$nsmatches = [];
foreach ($nl as $node) {
if ($node->tagName == $tagname) {
//$nsmatches[] = $node;
$found->attach($node);
}
}
// If something is found, merge them:
//if (!empty($nsmatches)) $found = array_merge($found, $nsmatches);
}
}
$this->matches = $found;
}
public function anyElement()
{
$found = new SplObjectStorage();
//$this->findAnyElement = TRUE;
$matches = $this->candidateList();
foreach ($matches as $item) {
$found->attach($item); // Add self
// See issue #20 or section 6.2 of this:
// http://www.w3.org/TR/2009/PR-css3-selectors-20091215/#universal-selector
//$nl = $item->getElementsByTagName('*');
//$this->attachNodeList($nl, $found);
}
$this->matches = $found;
$this->findAnyElement = false;
}
public function anyElementInNS($ns)
{
//$this->findAnyElement = TRUE;
$nsuri = $this->dom->lookupNamespaceURI($ns);
$found = new SplObjectStorage();
if (! empty($nsuri)) {
$matches = $this->candidateList();
foreach ($matches as $item) {
if ($item instanceof DOMNode && $nsuri == $item->namespaceURI) {
$found->attach($item);
}
}
}
$this->matches = $found;//UniqueElementList::get($found);
$this->findAnyElement = false;
}
public function elementClass($name)
{
$found = new SplObjectStorage();
$matches = $this->candidateList();
foreach ($matches as $item) {
if ($item->hasAttribute('class')) {
$classes = explode(' ', $item->getAttribute('class'));
if (in_array($name, $classes)) {
$found->attach($item);
}
}
}
$this->matches = $found;//UniqueElementList::get($found);
$this->findAnyElement = false;
}
public function attribute($name, $value = null, $operation = EventHandler::IS_EXACTLY)
{
$found = new SplObjectStorage();
$matches = $this->candidateList();
foreach ($matches as $item) {
if ($item->hasAttribute($name)) {
if (isset($value)) {
// If a value exists, then we need a match.
if ($this->attrValMatches($value, $item->getAttribute($name), $operation)) {
$found->attach($item);
}
} else {
// If no value exists, then we consider it a match.
$found->attach($item);
}
}
}
$this->matches = $found; //UniqueElementList::get($found);
$this->findAnyElement = false;
}
/**
* Helper function to find all elements with exact matches.
*
* @deprecated All use cases seem to be covered by attribute().
*/
protected function searchForAttr($name, $value = null)
{
$found = new SplObjectStorage();
$matches = $this->candidateList();
foreach ($matches as $candidate) {
if ($candidate->hasAttribute($name)) {
// If value is required, match that, too.
if (isset($value) && $value == $candidate->getAttribute($name)) {
$found->attach($candidate);
} // Otherwise, it's a match on name alone.
else {
$found->attach($candidate);
}
}
}
$this->matches = $found;
}
public function attributeNS($lname, $ns, $value = null, $operation = EventHandler::IS_EXACTLY)
{
$matches = $this->candidateList();
$found = new SplObjectStorage();
if (count($matches) == 0) {
$this->matches = $found;
return;
}
// Get the namespace URI for the given label.
//$uri = $matches[0]->lookupNamespaceURI($ns);
$matches->rewind();
$e = $matches->current();
$uri = $e->lookupNamespaceURI($ns);
foreach ($matches as $item) {
//foreach ($item->attributes as $attr) {
// print "$attr->prefix:$attr->localName ($attr->namespaceURI), Value: $attr->nodeValue\n";
//}
if ($item->hasAttributeNS($uri, $lname)) {
if (isset($value)) {
if ($this->attrValMatches($value, $item->getAttributeNS($uri, $lname), $operation)) {
$found->attach($item);
}
} else {
$found->attach($item);
}
}
}
$this->matches = $found;
$this->findAnyElement = false;
}
/**
* This also supports the following nonstandard pseudo classes:
* - :x-reset/:x-root (reset to the main item passed into the constructor. Less drastic than :root)
* - :odd/:even (shorthand for :nth-child(odd)/:nth-child(even))
*/
public function pseudoClass($name, $value = null)
{
$name = strtolower($name);
// Need to handle known pseudoclasses.
switch ($name) {
case 'visited':
case 'hover':
case 'active':
case 'focus':
case 'animated': // Last 3 are from jQuery
case 'visible':
case 'hidden':
// These require a UA, which we don't have.
case 'target':
// This requires a location URL, which we don't have.
$this->matches = new SplObjectStorage();
break;
case 'indeterminate':
// The assumption is that there is a UA and the format is HTML.
// I don't know if this should is useful without a UA.
throw new NotImplementedException(":indeterminate is not implemented.");
break;
case 'lang':
// No value = exception.
if (! isset($value)) {
throw new NotImplementedException("No handler for lang pseudoclass without value.");
}
$this->lang($value);
break;
case 'link':
$this->searchForAttr('href');
break;
case 'root':
$found = new SplObjectStorage();
if (empty($this->dom)) {
$this->matches = $found;
} elseif (is_array($this->dom)) {
$found->attach($this->dom[0]->ownerDocument->documentElement);
$this->matches = $found;
} elseif ($this->dom instanceof DOMNode) {
$found->attach($this->dom->ownerDocument->documentElement);
$this->matches = $found;
} elseif ($this->dom instanceof DOMNodeList && $this->dom->length > 0) {
$found->attach($this->dom->item(0)->ownerDocument->documentElement);
$this->matches = $found;
} else {
// Hopefully we never get here:
$found->attach($this->dom);
$this->matches = $found;
}
break;
// NON-STANDARD extensions for reseting to the "top" items set in
// the constructor.
case 'x-root':
case 'x-reset':
$this->matches = new SplObjectStorage();
$this->matches->attach($this->dom);
break;
// NON-STANDARD extensions for simple support of even and odd. These
// are supported by jQuery, FF, and other user agents.
case 'even':
$this->nthChild(2, 0);
break;
case 'odd':
$this->nthChild(2, 1);
break;
// Standard child-checking items.
case 'nth-child':
[$aVal, $bVal] = $this->parseAnB($value);
$this->nthChild($aVal, $bVal);
break;
case 'nth-last-child':
[$aVal, $bVal] = $this->parseAnB($value);
$this->nthLastChild($aVal, $bVal);
break;
case 'nth-of-type':
[$aVal, $bVal] = $this->parseAnB($value);
$this->nthOfTypeChild($aVal, $bVal, false);
break;
case 'nth-last-of-type':
[$aVal, $bVal] = $this->parseAnB($value);
$this->nthLastOfTypeChild($aVal, $bVal);
break;
case 'first-child':
$this->nthChild(0, 1);
break;
case 'last-child':
$this->nthLastChild(0, 1);
break;
case 'first-of-type':
$this->firstOfType();
break;
case 'last-of-type':
$this->lastOfType();
break;
case 'only-child':
$this->onlyChild();
break;
case 'only-of-type':
$this->onlyOfType();
break;
case 'empty':
$this->emptyElement();
break;
case 'not':
if (empty($value)) {
throw new ParseException(":not() requires a value.");
}
$this->not($value);
break;
// Additional pseudo-classes defined in jQuery:
case 'lt':
case 'gt':
case 'nth':
case 'eq':
case 'first':
case 'last':
//case 'even':
//case 'odd':
$this->getByPosition($name, $value);
break;
case 'parent':
$matches = $this->candidateList();
$found = new SplObjectStorage();
foreach ($matches as $match) {
if (! empty($match->firstChild)) {
$found->attach($match);
}
}
$this->matches = $found;
break;
case 'enabled':
case 'disabled':
case 'checked':
$this->attribute($name);
break;
case 'text':
case 'radio':
case 'checkbox':
case 'file':
case 'password':
case 'submit':
case 'image':
case 'reset':
case 'button':
$this->attribute('type', $name);
break;
case 'header':
$matches = $this->candidateList();
$found = new SplObjectStorage();
foreach ($matches as $item) {
$tag = $item->tagName;
$f = strtolower(substr($tag, 0, 1));
if ($f == 'h' && strlen($tag) == 2 && ctype_digit(substr($tag, 1, 1))) {
$found->attach($item);
}
}
$this->matches = $found;
break;
case 'has':
$this->has($value);
break;
// Contains == text matches.
// In QP 2.1, this was changed.
case 'contains':
$value = $this->removeQuotes($value);
$matches = $this->candidateList();
$found = new SplObjectStorage();
foreach ($matches as $item) {
if (strpos($item->textContent, $value) !== false) {
$found->attach($item);
}
}
$this->matches = $found;
break;
// Since QP 2.1
case 'contains-exactly':
$value = $this->removeQuotes($value);
$matches = $this->candidateList();
$found = new SplObjectStorage();
foreach ($matches as $item) {
if ($item->textContent == $value) {
$found->attach($item);
}
}
$this->matches = $found;
break;
default:
throw new ParseException("Unknown Pseudo-Class: " . $name);
}
$this->findAnyElement = false;
}
/**
* Remove leading and trailing quotes.
*/
private function removeQuotes($str)
{
$f = substr($str, 0, 1);
$l = substr($str, -1);
if ($f === $l && ($f == '"' || $f == "'")) {
$str = substr($str, 1, -1);
}
return $str;
}
/**
* Pseudo-class handler for a variety of jQuery pseudo-classes.
* Handles lt, gt, eq, nth, first, last pseudo-classes.
*/
private function getByPosition($operator, $pos)
{
$matches = $this->candidateList();
$found = new SplObjectStorage();
if ($matches->count() == 0) {
return;
}
switch ($operator) {
case 'nth':
case 'eq':
if ($matches->count() >= $pos) {
//$found[] = $matches[$pos -1];
foreach ($matches as $match) {
// CSS is 1-based, so we pre-increment.
if ($matches->key() + 1 == $pos) {
$found->attach($match);
break;
}
}
}
break;
case 'first':
if ($matches->count() > 0) {
$matches->rewind(); // This is necessary to init.
$found->attach($matches->current());
}
break;
case 'last':
if ($matches->count() > 0) {
// Spin through iterator.
foreach ($matches as $item) {
}
$found->attach($item);
}
break;
// case 'even':
// for ($i = 1; $i <= count($matches); ++$i) {
// if ($i % 2 == 0) {
// $found[] = $matches[$i];
// }
// }
// break;
// case 'odd':
// for ($i = 1; $i <= count($matches); ++$i) {
// if ($i % 2 == 0) {
// $found[] = $matches[$i];
// }
// }
// break;
case 'lt':
$i = 0;
foreach ($matches as $item) {
if (++$i < $pos) {
$found->attach($item);
}
}
break;
case 'gt':
$i = 0;
foreach ($matches as $item) {
if (++$i > $pos) {
$found->attach($item);
}
}
break;
}
$this->matches = $found;
}
/**
* Parse an an+b rule for CSS pseudo-classes.
*
* @param $rule
* Some rule in the an+b format.
*
* @return
* Array (list($aVal, $bVal)) of the two values.
* @throws ParseException
* If the rule does not follow conventions.
*/
protected function parseAnB($rule)
{
if ($rule == 'even') {
return [2, 0];
} elseif ($rule == 'odd') {
return [2, 1];
} elseif ($rule == 'n') {
return [1, 0];
} elseif (is_numeric($rule)) {
return [0, (int) $rule];
}
$rule = explode('n', $rule);
if (count($rule) == 0) {
throw new ParseException("nth-child value is invalid.");
}
// Each of these is legal: 1, -1, - and <empty>. '-' is shorthand for -1. <empty> is shorthand for 1
$aVal = trim($rule[0]);
if ($aVal === '') {
$aVal = 1;
} elseif ($aVal === '-') {
$aVal = -1;
} else {
$aVal = (int) $aVal;
}
$bVal = ! empty($rule[1]) ? (int) trim($rule[1]) : 0;
return [$aVal, $bVal];
}
/**
* Pseudo-class handler for nth-child and all related pseudo-classes.
*
* @param int $groupSize
* The size of the group (in an+b, this is a).
* @param int $elementInGroup
* The offset in a group. (in an+b this is b).
* @param boolean $lastChild
* Whether counting should begin with the last child. By default, this is false.
* Pseudo-classes that start with the last-child can set this to true.
*/
protected function nthChild($groupSize, $elementInGroup, $lastChild = false)
{
// EXPERIMENTAL: New in Quark. This should be substantially faster
// than the old (jQuery-ish) version. It still has E_STRICT violations
// though.
$parents = new SplObjectStorage();
$matches = new SplObjectStorage();
$index = new SplObjectStorage();
foreach ($this->matches as $item) {
$parent = $item->parentNode;
// Build up an array of all of children of this parent, and store the
// index of each element for reference later. We only need to do this
// once per parent, though.
if (!$parents->contains($parent)) {
$c = 0;
foreach ($parent->childNodes as $child) {
// We only want nodes, and if this call is preceded by an element
// selector, we only want to match elements with the same tag name.
// !!! This last part is a grey area in the CSS 3 Selector spec. It seems
// necessary to make the implementation match the examples in the spec. However,
// jQuery 1.2 does not do this.
if ($child->nodeType === XML_ELEMENT_NODE && ($this->findAnyElement || $child->tagName === $item->tagName)) {
$index->attach($child, ++$c);
}
}
$parents->attach($parent, $c);
}
// If we are looking for the last child, we count from the end of a list.
// Note that we add 1 because CSS indices begin at 1, not 0.
if ($lastChild) {
$indexToMatch = $parents->offsetGet($item->parentNode) - $index->offsetGet($item) + 1;
} // Otherwise we count from the beginning of the list.
else {
$indexToMatch = $index->offsetGet($item);
}
// If group size is 0, then we return element at the right index.
if ($groupSize === 0) {
if ($indexToMatch === $elementInGroup) {
$matches->attach($item);
}
}
// If group size != 0, then we grab nth element from group offset by
// element in group.
else {
if (($indexToMatch - $elementInGroup) % $groupSize == 0
&& ($indexToMatch - $elementInGroup) / $groupSize >= 0) {
$matches->attach($item);
}
}
}
$this->matches = $matches;
}
/**
* Reverse a set of matches.
*
* This is now necessary because internal matches are no longer represented
* as arrays.
*
* @since QueryPath 2.0
*//*
private function reverseMatches() {
// Reverse the candidate list. There must be a better way of doing
// this.
$arr = array();
foreach ($this->matches as $m) array_unshift($arr, $m);
$this->found = new \SplObjectStorage();
foreach ($arr as $item) $this->found->attach($item);
}*/
/**
* Pseudo-class handler for :nth-last-child and related pseudo-classes.
*/
protected function nthLastChild($groupSize, $elementInGroup)
{
// New in Quark.
$this->nthChild($groupSize, $elementInGroup, true);
}
/**
* Get a list of peer elements.
* If $requireSameTag is TRUE, then only peer elements with the same
* tagname as the given element will be returned.
*
* @param $element
* A DomElement.
* @param $requireSameTag
* Boolean flag indicating whether all matches should have the same
* element name (tagName) as $element.
*
* @return
* Array of peer elements.
*//*
protected function listPeerElements($element, $requireSameTag = FALSE) {
$peers = array();
$parent = $element->parentNode;
foreach ($parent->childNodes as $node) {
if ($node->nodeType == XML_ELEMENT_NODE) {
if ($requireSameTag) {
// Need to make sure that the tag matches:
if ($element->tagName == $node->tagName) {
$peers[] = $node;
}
}
else {
$peers[] = $node;
}
}
}
return $peers;
}
*/
/**
* Get the nth child (by index) from matching candidates.
*
* This is used by pseudo-class handlers.
*/
/*
protected function childAtIndex($index, $tagName = NULL) {
$restrictToElement = !$this->findAnyElement;
$matches = $this->candidateList();
$defaultTagName = $tagName;
// XXX: Added in Quark: I believe this should return an empty
// match set if no child was found tat the index.
$this->matches = new \SplObjectStorage();
foreach ($matches as $item) {
$parent = $item->parentNode;
// If a default tag name is supplied, we always use it.
if (!empty($defaultTagName)) {
$tagName = $defaultTagName;
}
// If we are inside of an element selector, we use the
// tag name of the given elements.
elseif ($restrictToElement) {
$tagName = $item->tagName;
}
// Otherwise, we skip the tag name match.
else {
$tagName = NULL;
}
// Loop through all children looking for matches.
$i = 0;
foreach ($parent->childNodes as $child) {
if ($child->nodeType !== XML_ELEMENT_NODE) {
break; // Skip non-elements
}
// If type is set, then we do type comparison
if (!empty($tagName)) {
// Check whether tag name matches the type.
if ($child->tagName == $tagName) {
// See if this is the index we are looking for.
if ($i == $index) {
//$this->matches = new \SplObjectStorage();
$this->matches->attach($child);
return;
}
// If it's not the one we are looking for, increment.
++$i;
}
}
// We don't care about type. Any tagName will match.
else {
if ($i == $index) {
$this->matches->attach($child);
return;
}
++$i;
}
} // End foreach
}
}*/
/**
* Pseudo-class handler for nth-of-type-child.
* Not implemented.
*/
protected function nthOfTypeChild($groupSize, $elementInGroup, $lastChild)
{
// EXPERIMENTAL: New in Quark. This should be substantially faster
// than the old (jQuery-ish) version.
$parents = new SplObjectStorage();
$matches = new SplObjectStorage();
$index = new SplObjectStorage();
foreach ($this->matches as $item) {
$parent = $item->parentNode;
// Build up an array of all of children of this parent, and store the
// index of each element for reference later. We only need to do this
// once per parent, though.
if (!$parents->contains($parent)) {
$c = 0;
foreach ($parent->childNodes as $child) {
// This doesn't totally make sense, since the CSS 3 spec does not require that
// this pseudo-class be adjoined to an element (e.g. ' :nth-of-type' is allowed).
if ($child->nodeType === XML_ELEMENT_NODE && $child->tagName === $item->tagName) {
$index->attach($child, ++$c);
}
}
$parents->attach($parent, $c);
}
// If we are looking for the last child, we count from the end of a list.
// Note that we add 1 because CSS indices begin at 1, not 0.
if ($lastChild) {
$indexToMatch = $parents->offsetGet($item->parentNode) - $index->offsetGet($item) + 1;
} // Otherwise we count from the beginning of the list.
else {
$indexToMatch = $index->offsetGet($item);
}
// If group size is 0, then we return element at the right index.
if ($groupSize === 0) {
if ($indexToMatch === $elementInGroup) {
$matches->attach($item);
}
}
// If group size != 0, then we grab nth element from group offset by
// element in group.
else {
if (($indexToMatch - $elementInGroup) % $groupSize == 0
&& ($indexToMatch - $elementInGroup) / $groupSize >= 0) {
$matches->attach($item);
}
}
}