forked from punkave/phpQuery
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphpQueryObject.php
More file actions
3199 lines (3197 loc) · 87.8 KB
/
phpQueryObject.php
File metadata and controls
3199 lines (3197 loc) · 87.8 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
/**
* Class representing phpQuery objects.
*
* @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
* @package phpQuery
* @method phpQueryObject clone() clone()
* @method phpQueryObject empty() empty()
* @method phpQueryObject next() next($selector = null)
* @method phpQueryObject prev() prev($selector = null)
* @property Int $length
*/
class phpQueryObject
implements Iterator, Countable, ArrayAccess {
public $documentID = null;
/**
* DOMDocument class.
*
* @var DOMDocument
*/
public $document = null;
public $charset = null;
/**
*
* @var DOMDocumentWrapper
*/
public $documentWrapper = null;
/**
* XPath interface.
*
* @var DOMXPath
*/
public $xpath = null;
/**
* Stack of selected elements.
* @TODO refactor to ->nodes
* @var array
*/
public $elements = array();
/**
* @access private
*/
protected $elementsBackup = array();
/**
* @access private
*/
protected $previous = null;
/**
* @access private
* @TODO deprecate
*/
protected $root = array();
/**
* Indicated if doument is just a fragment (no <html> tag).
*
* Every document is realy a full document, so even documentFragments can
* be queried against <html>, but getDocument(id)->htmlOuter() will return
* only contents of <body>.
*
* @var bool
*/
public $documentFragment = true;
/**
* Iterator interface helper
* @access private
*/
protected $elementsInterator = array();
/**
* Iterator interface helper
* @access private
*/
protected $valid = false;
/**
* Iterator interface helper
* @access private
*/
protected $current = null;
/**
* Enter description here...
*
* @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
*/
public function __construct($documentID) {
// if ($documentID instanceof self)
// var_dump($documentID->getDocumentID());
$id = $documentID instanceof self
? $documentID->getDocumentID()
: $documentID;
// var_dump($id);
if (! isset(phpQuery::$documents[$id] )) {
// var_dump(phpQuery::$documents);
throw new Exception("Document with ID '{$id}' isn't loaded. Use phpQuery::newDocument(\$html) or phpQuery::newDocumentFile(\$file) first.");
}
$this->documentID = $id;
$this->documentWrapper =& phpQuery::$documents[$id];
$this->document =& $this->documentWrapper->document;
$this->xpath =& $this->documentWrapper->xpath;
$this->charset =& $this->documentWrapper->charset;
$this->documentFragment =& $this->documentWrapper->isDocumentFragment;
// TODO check $this->DOM->documentElement;
// $this->root = $this->document->documentElement;
$this->root =& $this->documentWrapper->root;
// $this->toRoot();
$this->elements = array($this->root);
}
/**
*
* @access private
* @param $attr
* @return unknown_type
*/
public function __get($attr) {
switch($attr) {
// FIXME doesnt work at all ?
case 'length':
return $this->size();
break;
default:
return $this->$attr;
}
}
/**
* Saves actual object to $var by reference.
* Useful when need to break chain.
* @param phpQueryObject $var
* @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
*/
public function toReference(&$var) {
return $var = $this;
}
public function documentFragment($state = null) {
if ($state) {
phpQuery::$documents[$this->getDocumentID()]['documentFragment'] = $state;
return $this;
}
return $this->documentFragment;
}
/**
* @access private
* @TODO documentWrapper
*/
protected function isRoot( $node) {
// return $node instanceof DOMDOCUMENT || $node->tagName == 'html';
return $node instanceof DOMDOCUMENT
|| ($node instanceof DOMELEMENT && $node->tagName == 'html')
|| $this->root->isSameNode($node);
}
/**
* @access private
*/
protected function stackIsRoot() {
return $this->size() == 1 && $this->isRoot($this->elements[0]);
}
/**
* Enter description here...
* NON JQUERY METHOD
*
* Watch out, it doesn't creates new instance, can be reverted with end().
*
* @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
*/
public function toRoot() {
$this->elements = array($this->root);
return $this;
// return $this->newInstance(array($this->root));
}
/**
* Saves object's DocumentID to $var by reference.
* <code>
* $myDocumentId;
* phpQuery::newDocument('<div/>')
* ->getDocumentIDRef($myDocumentId)
* ->find('div')->...
* </code>
*
* @param unknown_type $domId
* @see phpQuery::newDocument
* @see phpQuery::newDocumentFile
* @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
*/
public function getDocumentIDRef(&$documentID) {
$documentID = $this->getDocumentID();
return $this;
}
/**
* Returns object with stack set to document root.
*
* @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
*/
public function getDocument() {
return phpQuery::getDocument($this->getDocumentID());
}
/**
*
* @return DOMDocument
*/
public function getDOMDocument() {
return $this->document;
}
/**
* Get object's Document ID.
*
* @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
*/
public function getDocumentID() {
return $this->documentID;
}
/**
* Unloads whole document from memory.
* CAUTION! None further operations will be possible on this document.
* All objects refering to it will be useless.
*
* @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
*/
public function unloadDocument() {
phpQuery::unloadDocuments($this->getDocumentID());
}
public function isHTML() {
return $this->documentWrapper->isHTML;
}
public function isXHTML() {
return $this->documentWrapper->isXHTML;
}
public function isXML() {
return $this->documentWrapper->isXML;
}
/**
* Enter description here...
*
* @link http://docs.jquery.com/Ajax/serialize
* @return string
*/
public function serialize() {
// serializeArray() returns a flat array of associative arrays with name and value elements,
// which matches what jQuery does. jQuery does that to allow multiple elements with the
// same name, which an object (equivalent to an associative array in PHP) wouldn't.
// OK, but to turn it into a valid query string we can't just call param() and therefore
// http_build_query(), which expects an associative array. To get the "multiple elements with the
// same name" feature and still serialize() properly we have to reimplement
// http_build_query. tom@punkave.com
$s = '';
$flat = $this->serializeArray();
foreach ($flat as $pair)
{
if (strlen($s))
{
$s .= '&';
}
$s .= urlencode($pair['name']);
$s .= '=';
$s .= urlencode($pair['value']);
}
return $s;
}
/**
* Enter description here...
*
* @link http://docs.jquery.com/Ajax/serializeArray
* @return array
*/
public function serializeArray($submit = null) {
$source = $this->filter('form, input, select, textarea')
->find('input, select, textarea')
->andSelf()
->not('form');
$return = array();
// $source->dumpDie();
foreach($source as $input) {
$input = phpQuery::pq($input);
if ($input->is('[disabled]'))
continue;
if (!$input->is('[name]'))
continue;
if ($input->is('[type=checkbox]') && !$input->is('[checked]'))
continue;
// jquery diff
if ($submit && $input->is('[type=submit]')) {
if ($submit instanceof DOMELEMENT && ! $input->elements[0]->isSameNode($submit))
continue;
else if (is_string($submit) && $input->attr('name') != $submit)
continue;
}
$return[] = array(
'name' => $input->attr('name'),
'value' => $input->val(),
);
}
return $return;
}
/**
* @access private
*/
protected function debug($in) {
if (! phpQuery::$debug )
return;
print('<pre>');
print_r($in);
// file debug
// file_put_contents(dirname(__FILE__).'/phpQuery.log', print_r($in, true)."\n", FILE_APPEND);
// quite handy debug trace
// if ( is_array($in))
// print_r(array_slice(debug_backtrace(), 3));
print("</pre>\n");
}
/**
* @access private
*/
protected function isRegexp($pattern) {
return in_array(
$pattern[ mb_strlen($pattern)-1 ],
array('^','*','$')
);
}
/**
* Determines if $char is really a char.
*
* @param string $char
* @return bool
* @todo rewrite me to charcode range ! ;)
* @access private
*/
protected function isChar($char) {
return extension_loaded('mbstring') && phpQuery::$mbstringSupport
? mb_eregi('\w', $char)
: preg_match('@\w@', $char);
}
/**
* @access private
*/
protected function parseSelector($query) {
// clean spaces
// TODO include this inside parsing ?
$query = trim(
preg_replace('@\s+@', ' ',
preg_replace('@\s*(>|\\+|~)\s*@', '\\1', $query)
)
);
$queries = array(array());
if (! $query)
return $queries;
$return =& $queries[0];
$specialChars = array('>',' ');
// $specialCharsMapping = array('/' => '>');
$specialCharsMapping = array();
$strlen = mb_strlen($query);
$classChars = array('.', '-');
$pseudoChars = array('-');
$tagChars = array('*', '|', '-');
// split multibyte string
// http://code.google.com/p/phpquery/issues/detail?id=76
$_query = array();
for ($i=0; $i<$strlen; $i++)
$_query[] = mb_substr($query, $i, 1);
$query = $_query;
// it works, but i dont like it...
$i = 0;
while( $i < $strlen) {
$c = $query[$i];
$tmp = '';
// TAG
if ($this->isChar($c) || in_array($c, $tagChars)) {
while(isset($query[$i])
&& ($this->isChar($query[$i]) || in_array($query[$i], $tagChars))) {
$tmp .= $query[$i];
$i++;
}
$return[] = $tmp;
// IDs
} else if ( $c == '#') {
$i++;
while( isset($query[$i]) && ($this->isChar($query[$i]) || $query[$i] == '-')) {
$tmp .= $query[$i];
$i++;
}
$return[] = '#'.$tmp;
// SPECIAL CHARS
} else if (in_array($c, $specialChars)) {
$return[] = $c;
$i++;
// MAPPED SPECIAL MULTICHARS
// } else if ( $c.$query[$i+1] == '//') {
// $return[] = ' ';
// $i = $i+2;
// MAPPED SPECIAL CHARS
} else if ( isset($specialCharsMapping[$c])) {
$return[] = $specialCharsMapping[$c];
$i++;
// COMMA
} else if ( $c == ',') {
$queries[] = array();
$return =& $queries[ count($queries)-1 ];
$i++;
while( isset($query[$i]) && $query[$i] == ' ')
$i++;
// CLASSES
} else if ($c == '.') {
while( isset($query[$i]) && ($this->isChar($query[$i]) || in_array($query[$i], $classChars))) {
$tmp .= $query[$i];
$i++;
}
$return[] = $tmp;
// ~ General Sibling Selector
} else if ($c == '~') {
$spaceAllowed = true;
$tmp .= $query[$i++];
while( isset($query[$i])
&& ($this->isChar($query[$i])
|| in_array($query[$i], $classChars)
|| $query[$i] == '*'
|| ($query[$i] == ' ' && $spaceAllowed)
)) {
if ($query[$i] != ' ')
$spaceAllowed = false;
$tmp .= $query[$i];
$i++;
}
$return[] = $tmp;
// + Adjacent sibling selectors
} else if ($c == '+') {
$spaceAllowed = true;
$tmp .= $query[$i++];
while( isset($query[$i])
&& ($this->isChar($query[$i])
|| in_array($query[$i], $classChars)
|| $query[$i] == '*'
|| ($spaceAllowed && $query[$i] == ' ')
)) {
if ($query[$i] != ' ')
$spaceAllowed = false;
$tmp .= $query[$i];
$i++;
}
$return[] = $tmp;
// ATTRS
} else if ($c == '[') {
$stack = 1;
$tmp .= $c;
while( isset($query[++$i])) {
$tmp .= $query[$i];
if ( $query[$i] == '[') {
$stack++;
} else if ( $query[$i] == ']') {
$stack--;
if (! $stack )
break;
}
}
$return[] = $tmp;
$i++;
// PSEUDO CLASSES
} else if ($c == ':') {
$stack = 1;
$tmp .= $query[$i++];
while( isset($query[$i]) && ($this->isChar($query[$i]) || in_array($query[$i], $pseudoChars))) {
$tmp .= $query[$i];
$i++;
}
// with arguments ?
if ( isset($query[$i]) && $query[$i] == '(') {
$tmp .= $query[$i];
$stack = 1;
while( isset($query[++$i])) {
$tmp .= $query[$i];
if ( $query[$i] == '(') {
$stack++;
} else if ( $query[$i] == ')') {
$stack--;
if (! $stack )
break;
}
}
$return[] = $tmp;
$i++;
} else {
$return[] = $tmp;
}
} else {
$i++;
}
}
foreach($queries as $k => $q) {
if (isset($q[0])) {
if (isset($q[0][0]) && $q[0][0] == ':')
array_unshift($queries[$k], '*');
if ($q[0] != '>')
array_unshift($queries[$k], ' ');
}
}
return $queries;
}
/**
* Return matched DOM nodes.
*
* @param int $index
* @return array|DOMElement Single DOMElement or array of DOMElement.
*/
public function get($index = null, $callback1 = null, $callback2 = null, $callback3 = null) {
$return = isset($index)
? (isset($this->elements[$index]) ? $this->elements[$index] : null)
: $this->elements;
// pass thou callbacks
$args = func_get_args();
$args = array_slice($args, 1);
foreach($args as $callback) {
if (is_array($return))
foreach($return as $k => $v)
$return[$k] = phpQuery::callbackRun($callback, array($v));
else
$return = phpQuery::callbackRun($callback, array($return));
}
return $return;
}
/**
* Return matched DOM nodes.
* jQuery difference.
*
* @param int $index
* @return array|string Returns string if $index != null
* @todo implement callbacks
* @todo return only arrays ?
* @todo maybe other name...
*/
public function getString($index = null, $callback1 = null, $callback2 = null, $callback3 = null) {
if ($index)
$return = $this->eq($index)->text();
else {
$return = array();
for($i = 0; $i < $this->size(); $i++) {
$return[] = $this->eq($i)->text();
}
}
// pass thou callbacks
$args = func_get_args();
$args = array_slice($args, 1);
foreach($args as $callback) {
$return = phpQuery::callbackRun($callback, array($return));
}
return $return;
}
/**
* Return matched DOM nodes.
* jQuery difference.
*
* @param int $index
* @return array|string Returns string if $index != null
* @todo implement callbacks
* @todo return only arrays ?
* @todo maybe other name...
*/
public function getStrings($index = null, $callback1 = null, $callback2 = null, $callback3 = null) {
if ($index)
$return = $this->eq($index)->text();
else {
$return = array();
for($i = 0; $i < $this->size(); $i++) {
$return[] = $this->eq($i)->text();
}
// pass thou callbacks
$args = func_get_args();
$args = array_slice($args, 1);
}
foreach($args as $callback) {
if (is_array($return))
foreach($return as $k => $v)
$return[$k] = phpQuery::callbackRun($callback, array($v));
else
$return = phpQuery::callbackRun($callback, array($return));
}
return $return;
}
/**
* Returns new instance of actual class.
*
* @param array $newStack Optional. Will replace old stack with new and move old one to history.c
*/
public function newInstance($newStack = null) {
$class = get_class($this);
// support inheritance by passing old object to overloaded constructor
$new = $class != 'phpQuery'
? new $class($this, $this->getDocumentID())
: new phpQueryObject($this->getDocumentID());
$new->previous = $this;
if (is_null($newStack)) {
$new->elements = $this->elements;
if ($this->elementsBackup)
$this->elements = $this->elementsBackup;
} else if (is_string($newStack)) {
$new->elements = phpQuery::pq($newStack, $this->getDocumentID())->stack();
} else {
$new->elements = $newStack;
}
return $new;
}
/**
* Enter description here...
*
* In the future, when PHP will support XLS 2.0, then we would do that this way:
* contains(tokenize(@class, '\s'), "something")
* @param unknown_type $class
* @param unknown_type $node
* @return boolean
* @access private
*/
protected function matchClasses($class, $node) {
// multi-class
if ( mb_strpos($class, '.', 1)) {
$classes = explode('.', substr($class, 1));
$classesCount = count( $classes );
$nodeClasses = explode(' ', $node->getAttribute('class') );
$nodeClassesCount = count( $nodeClasses );
if ( $classesCount > $nodeClassesCount )
return false;
$diff = count(
array_diff(
$classes,
$nodeClasses
)
);
if (! $diff )
return true;
// single-class
} else {
return in_array(
// strip leading dot from class name
substr($class, 1),
// get classes for element as array
explode(' ', $node->getAttribute('class') )
);
}
}
/**
* @access private
*/
protected function runQuery($XQuery, $selector = null, $compare = null) {
if ($compare && ! method_exists($this, $compare))
return false;
$stack = array();
if (! $this->elements)
$this->debug('Stack empty, skipping...');
// var_dump($this->elements[0]->nodeType);
// element, document
foreach($this->stack(array(1, 9, 13)) as $k => $stackNode) {
$detachAfter = false;
// to work on detached nodes we need temporary place them somewhere
// thats because context xpath queries sucks ;]
$testNode = $stackNode;
while ($testNode) {
if (! $testNode->parentNode && ! $this->isRoot($testNode)) {
$this->root->appendChild($testNode);
$detachAfter = $testNode;
break;
}
$testNode = isset($testNode->parentNode)
? $testNode->parentNode
: null;
}
// XXX tmp ?
$xpath = $this->documentWrapper->isXHTML
? $this->getNodeXpath($stackNode, 'html')
: $this->getNodeXpath($stackNode);
// FIXME pseudoclasses-only query, support XML
$query = $XQuery == '//' && $xpath == '/html[1]'
? '//*'
: $xpath.$XQuery;
$this->debug("XPATH: {$query}");
// run query, get elements
$nodes = $this->xpath->query($query);
$this->debug("QUERY FETCHED");
if (! $nodes->length )
$this->debug('Nothing found');
$debug = array();
foreach($nodes as $node) {
$matched = false;
if ( $compare) {
phpQuery::$debug ?
$this->debug("Found: ".$this->whois( $node ).", comparing with {$compare}()")
: null;
$phpQueryDebug = phpQuery::$debug;
phpQuery::$debug = false;
// TODO ??? use phpQuery::callbackRun()
if (call_user_func_array(array($this, $compare), array($selector, $node)))
$matched = true;
phpQuery::$debug = $phpQueryDebug;
} else {
$matched = true;
}
if ( $matched) {
if (phpQuery::$debug)
$debug[] = $this->whois( $node );
$stack[] = $node;
}
}
if (phpQuery::$debug) {
$this->debug("Matched ".count($debug).": ".implode(', ', $debug));
}
if ($detachAfter)
$this->root->removeChild($detachAfter);
}
$this->elements = $stack;
}
/**
* Enter description here...
*
* @return phpQueryObject|QueryTemplatesSource|QueryTemplatesParse|QueryTemplatesSourceQuery
*/
public function find($selectors, $context = null, $noHistory = false) {
if (!$noHistory)
// backup last stack /for end()/
$this->elementsBackup = $this->elements;
// allow to define context
// TODO combine code below with phpQuery::pq() context guessing code
// as generic function
if ($context) {
if (! is_array($context) && $context instanceof DOMELEMENT)
$this->elements = array($context);
else if (is_array($context)) {
$this->elements = array();
foreach ($context as $c)
if ($c instanceof DOMELEMENT)
$this->elements[] = $c;
} else if ( $context instanceof self )
$this->elements = $context->elements;
}
$queries = $this->parseSelector($selectors);
$this->debug(array('FIND', $selectors, $queries));
$XQuery = '';
// remember stack state because of multi-queries
$oldStack = $this->elements;
// here we will be keeping found elements
$stack = array();
foreach($queries as $selector) {
$this->elements = $oldStack;
$delimiterBefore = false;
foreach($selector as $s) {
// TAG
$isTag = extension_loaded('mbstring') && phpQuery::$mbstringSupport
? mb_ereg_match('^[\w|\||-]+$', $s) || $s == '*'
: preg_match('@^[\w|\||-]+$@', $s) || $s == '*';
if ($isTag) {
if ($this->isXML()) {
// namespace support
if (mb_strpos($s, '|') !== false) {
$ns = $tag = null;
list($ns, $tag) = explode('|', $s);
$XQuery .= "$ns:$tag";
} else if ($s == '*') {
$XQuery .= "*";
} else {
$XQuery .= "*[local-name()='$s']";
}
} else {
$XQuery .= $s;
}
// ID
} else if ($s[0] == '#') {
if ($delimiterBefore)
$XQuery .= '*';
$XQuery .= "[@id='".substr($s, 1)."']";
// ATTRIBUTES
} else if ($s[0] == '[') {
if ($delimiterBefore)
$XQuery .= '*';
// strip side brackets
$attr = trim($s, '][');
$execute = false;
// attr with specifed value
if (mb_strpos($s, '=')) {
$value = null;
list($attr, $value) = explode('=', $attr);
$value = trim($value, "'\"");
if ($this->isRegexp($attr)) {
// cut regexp character
$attr = substr($attr, 0, -1);
$execute = true;
$XQuery .= "[@{$attr}]";
} else {
$XQuery .= "[@{$attr}='{$value}']";
}
// attr without specified value
} else {
$XQuery .= "[@{$attr}]";
}
if ($execute) {
$this->runQuery($XQuery, $s, 'is');
$XQuery = '';
if (! $this->length())
break;
}
// CLASSES
} else if ($s[0] == '.') {
// TODO use return $this->find("./self::*[contains(concat(\" \",@class,\" \"), \" $class \")]");
// thx wizDom ;)
if ($delimiterBefore)
$XQuery .= '*';
$XQuery .= '[@class]';
$this->runQuery($XQuery, $s, 'matchClasses');
$XQuery = '';
if (! $this->length() )
break;
// ~ General Sibling Selector
} else if ($s[0] == '~') {
$this->runQuery($XQuery);
$XQuery = '';
$this->elements = $this
->siblings(
substr($s, 1)
)->elements;
if (! $this->length() )
break;
// + Adjacent sibling selectors
} else if ($s[0] == '+') {
// TODO /following-sibling::
$this->runQuery($XQuery);
$XQuery = '';
$subSelector = substr($s, 1);
$subElements = $this->elements;
$this->elements = array();
foreach($subElements as $node) {
// search first DOMElement sibling
$test = $node->nextSibling;
while($test && ! ($test instanceof DOMELEMENT))
$test = $test->nextSibling;
if ($test && $this->is($subSelector, $test))
$this->elements[] = $test;
}
if (! $this->length() )
break;
// PSEUDO CLASSES
} else if ($s[0] == ':') {
// TODO optimization for :first :last
if ($XQuery) {
$this->runQuery($XQuery);
$XQuery = '';
}
if (! $this->length())
break;
$this->pseudoClasses($s);
if (! $this->length())
break;
// DIRECT DESCENDANDS
} else if ($s == '>') {
$XQuery .= '/';
$delimiterBefore = 2;
// ALL DESCENDANDS
} else if ($s == ' ') {
$XQuery .= '//';
$delimiterBefore = 2;
// ERRORS
} else {
phpQuery::debug("Unrecognized token '$s'");
}
$delimiterBefore = $delimiterBefore === 2;
}
// run query if any
if ($XQuery && $XQuery != '//') {
$this->runQuery($XQuery);
$XQuery = '';
}
foreach($this->elements as $node)
if (! $this->elementsContainsNode($node, $stack))
$stack[] = $node;
}
$this->elements = $stack;
return $this->newInstance();
}
/**
* @todo create API for classes with pseudoselectors
* @access private
*/
protected function pseudoClasses($class) {
// TODO clean args parsing ?
$class = ltrim($class, ':');
$haveArgs = mb_strpos($class, '(');
if ($haveArgs !== false) {
$args = substr($class, $haveArgs+1, -1);
$class = substr($class, 0, $haveArgs);
}
switch($class) {
case 'even':
case 'odd':
$stack = array();
foreach($this->elements as $i => $node) {
if ($class == 'even' && ($i%2) == 0)
$stack[] = $node;
else if ( $class == 'odd' && $i % 2 )
$stack[] = $node;
}
$this->elements = $stack;
break;
case 'eq':
$k = intval($args);
$this->elements = isset( $this->elements[$k] )
? array( $this->elements[$k] )
: array();
break;
case 'gt':
$this->elements = array_slice($this->elements, $args+1);
break;
case 'lt':
$this->elements = array_slice($this->elements, 0, $args+1);
break;
case 'first':
if (isset($this->elements[0]))
$this->elements = array($this->elements[0]);
break;
case 'last':
if ($this->elements)
$this->elements = array($this->elements[count($this->elements)-1]);
break;
/*case 'parent':
$stack = array();
foreach($this->elements as $node) {
if ( $node->childNodes->length )
$stack[] = $node;
}
$this->elements = $stack;
break;*/
case 'contains':
$text = trim($args, "\"'");
$stack = array();
foreach($this->elements as $node) {
if (($text) && (mb_stripos($node->textContent, $text) === false))
continue;
$stack[] = $node;
}
$this->elements = $stack;
break;
case 'not':
$selector = self::unQuote($args);
$this->elements = $this->not($selector)->stack();
break;
case 'slice':
// TODO jQuery difference ?
$args = explode(',',
str_replace(', ', ',', trim($args, "\"'"))
);
$start = $args[0];
$end = isset($args[1])
? $args[1]
: null;
if ($end > 0)
$end = $end-$start;
$this->elements = array_slice($this->elements, $start, $end);
break;
case 'has':
$selector = trim($args, "\"'");
$stack = array();
foreach($this->stack(1) as $el) {
if ($this->find($selector, $el, true)->length)
$stack[] = $el;
}
$this->elements = $stack;
break;
case 'submit':
case 'reset':
$this->elements = phpQuery::merge(
$this->map(array($this, 'is'),
"input[type=$class]", new CallbackParam()
),
$this->map(array($this, 'is'),
"button[type=$class]", new CallbackParam()
)
);
break;
// $stack = array();
// foreach($this->elements as $node)
// if ($node->is('input[type=submit]') || $node->is('button[type=submit]'))
// $stack[] = $el;
// $this->elements = $stack;
case 'input':
$this->elements = $this->map(
array($this, 'is'),
'input', new CallbackParam()
)->elements;
break;
case 'password':
case 'checkbox':
case 'radio':
case 'hidden':
case 'image':
case 'file':
$this->elements = $this->map(
array($this, 'is'),
"input[type=$class]", new CallbackParam()
)->elements;
break;
case 'parent':
$this->elements = $this->map(
create_function('$node', '
return $node instanceof DOMELEMENT && $node->childNodes->length
? $node : null;')
)->elements;
break;
case 'empty':
$this->elements = $this->map(
create_function('$node', '
return $node instanceof DOMELEMENT && $node->childNodes->length
? null : $node;')
)->elements;
break;