-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathDOMQuery.php
More file actions
4000 lines (3790 loc) · 124 KB
/
DOMQuery.php
File metadata and controls
4000 lines (3790 loc) · 124 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 houses the class formerly called QueryPath.
*
* As of QueryPath 3.0.0, the class was renamed QueryPath::DOMQuery. This
* was done for a few reasons:
* - The library has been refactored, and it made more sense to call the top
* level class QueryPath. This is not the top level class.
* - There have been requests for a JSONQuery class, which would be the
* natural complement of DOMQuery.
*/
namespace QueryPath;
use \QueryPath\CSS\QueryPathEventHandler;
use \QueryPath;
use \Masterminds\HTML5;
/**
* The DOMQuery object is the primary tool in this library.
*
* To create a new DOMQuery, use QueryPath::with() or qp() function.
*
* If you are new to these documents, start at the QueryPath.php page.
* There you will find a quick guide to the tools contained in this project.
*
* A note on serialization: DOMQuery uses DOM classes internally, and those
* do not serialize well at all. In addition, DOMQuery may contain many
* extensions, and there is no guarantee that extensions can serialize. The
* moral of the story: Don't serialize DOMQuery.
*
* @see qp()
* @see QueryPath.php
* @ingroup querypath_core
*/
class DOMQuery implements \QueryPath\Query, \IteratorAggregate, \Countable {
/**
* Default parser flags.
*
* These are flags that will be used if no global or local flags override them.
* @since 2.0
*/
const DEFAULT_PARSER_FLAGS = NULL;
const JS_CSS_ESCAPE_CDATA = '\\1';
const JS_CSS_ESCAPE_CDATA_CCOMMENT = '/* \\1 */';
const JS_CSS_ESCAPE_CDATA_DOUBLESLASH = '// \\1';
const JS_CSS_ESCAPE_NONE = '';
//const IGNORE_ERRORS = 1544; //E_NOTICE | E_USER_WARNING | E_USER_NOTICE;
private $errTypes = 771; //E_ERROR; | E_USER_ERROR;
/**
* The base DOMDocument.
*/
protected $document = NULL;
private $options = array(
'parser_flags' => NULL,
'omit_xml_declaration' => FALSE,
'replace_entities' => FALSE,
'exception_level' => 771, // E_ERROR | E_USER_ERROR | E_USER_WARNING | E_WARNING
'ignore_parser_warnings' => FALSE,
'escape_xhtml_js_css_sections' => self::JS_CSS_ESCAPE_CDATA_CCOMMENT,
);
/**
* The array of matches.
*/
protected $matches = array();
/**
* The last array of matches.
*/
protected $last = array(); // Last set of matches.
private $ext = array(); // Extensions array.
/**
* The number of current matches.
*
* @see count()
*/
public $length = 0;
/**
* Constructor.
*
* Typically, a new DOMQuery is created by QueryPath::with(), QueryPath::withHTML(),
* qp(), or htmlqp().
*
* @param mixed $document
* A document-like object.
* @param string $string
* A CSS 3 Selector
* @param array $options
* An associative array of options.
* @see qp()
*/
public function __construct($document = NULL, $string = NULL, $options = array()) {
$string = trim($string);
$this->options = $options + Options::get() + $this->options;
$parser_flags = isset($options['parser_flags']) ? $options['parser_flags'] : self::DEFAULT_PARSER_FLAGS;
if (!empty($this->options['ignore_parser_warnings'])) {
// Don't convert parser warnings into exceptions.
$this->errTypes = 257; //E_ERROR | E_USER_ERROR;
}
elseif (isset($this->options['exception_level'])) {
// Set the error level at which exceptions will be thrown. By default,
// QueryPath will throw exceptions for
// E_ERROR | E_USER_ERROR | E_WARNING | E_USER_WARNING.
$this->errTypes = $this->options['exception_level'];
}
// Empty: Just create an empty QP.
if (empty($document)) {
$this->document = isset($this->options['encoding']) ? new \DOMDocument('1.0', $this->options['encoding']) : new \DOMDocument();
$this->setMatches(new \SplObjectStorage());
}
// Figure out if document is DOM, HTML/XML, or a filename
elseif (is_object($document)) {
// This is the most frequent object type.
if ($document instanceof \SplObjectStorage) {
$this->matches = $document;
if ($document->count() != 0) {
$first = $this->getFirstMatch();
if (!empty($first->ownerDocument)) {
$this->document = $first->ownerDocument;
}
}
}
elseif ($document instanceof DOMQuery) {
//$this->matches = $document->get(NULL, TRUE);
$this->setMatches($document->get(NULL, TRUE));
if ($this->matches->count() > 0)
$this->document = $this->getFirstMatch()->ownerDocument;
}
elseif ($document instanceof \DOMDocument) {
$this->document = $document;
//$this->matches = $this->matches($document->documentElement);
$this->setMatches($document->documentElement);
}
elseif ($document instanceof \DOMNode) {
$this->document = $document->ownerDocument;
//$this->matches = array($document);
$this->setMatches($document);
}
elseif ($document instanceof \Masterminds\HTML5) {
$this->document = $document;
$this->setMatches($document->documentElement);
}
elseif ($document instanceof \SimpleXMLElement) {
$import = dom_import_simplexml($document);
$this->document = $import->ownerDocument;
//$this->matches = array($import);
$this->setMatches($import);
}
else {
throw new \QueryPath\Exception('Unsupported class type: ' . get_class($document));
}
}
elseif (is_array($document)) {
//trigger_error('Detected deprecated array support', E_USER_NOTICE);
if (!empty($document) && $document[0] instanceof \DOMNode) {
$found = new \SplObjectStorage();
foreach ($document as $item) $found->attach($item);
//$this->matches = $found;
$this->setMatches($found);
$this->document = $this->getFirstMatch()->ownerDocument;
}
}
elseif ($this->isXMLish($document)) {
// $document is a string with XML
$this->document = $this->parseXMLString($document);
$this->setMatches($this->document->documentElement);
}
else {
// $document is a filename
$context = empty($options['context']) ? NULL : $options['context'];
$this->document = $this->parseXMLFile($document, $parser_flags, $context);
$this->setMatches($this->document->documentElement);
}
// Globally set the output option.
if (isset($this->options['format_output']) && $this->options['format_output'] == FALSE) {
$this->document->formatOutput = FALSE;
}
else {
$this->document->formatOutput = TRUE;
}
// Do a find if the second param was set.
if (isset($string) && strlen($string) > 0) {
// We don't issue a find because that creates a new DOMQuery.
//$this->find($string);
$query = new \QueryPath\CSS\DOMTraverser($this->matches);
$query->find($string);
$this->setMatches($query->matches());
}
}
/**
* Get the effective options for the current DOMQuery object.
*
* This returns an associative array of all of the options as set
* for the current DOMQuery object. This includes default options,
* options directly passed in via {@link qp()} or the constructor,
* an options set in the QueryPath::Options object.
*
* The order of merging options is this:
* - Options passed in using qp() are highest priority, and will
* override other options.
* - Options set with QueryPath::Options will override default options,
* but can be overridden by options passed into qp().
* - Default options will be used when no overrides are present.
*
* This function will return the options currently used, with the above option
* overriding having been calculated already.
*
* @return array
* An associative array of options, calculated from defaults and overridden
* options.
* @see qp()
* @see QueryPath::Options::set()
* @see QueryPath::Options::merge()
* @since 2.0
*/
public function getOptions() {
return $this->options;
}
/**
* Select the root element of the document.
*
* This sets the current match to the document's root element. For
* practical purposes, this is the same as:
* @code
* qp($someDoc)->find(':root');
* @endcode
* However, since it doesn't invoke a parser, it has less overhead. It also
* works in cases where the QueryPath has been reduced to zero elements (a
* case that is not handled by find(':root') because there is no element
* whose root can be found).
*
* @param string $selector
* A selector. If this is supplied, QueryPath will navigate to the
* document root and then run the query. (Added in QueryPath 2.0 Beta 2)
* @return \QueryPath\DOMQuery
* The DOMQuery object, wrapping the root element (document element)
* for the current document.
*/
public function top($selector = NULL) {
//$this->setMatches($this->document->documentElement);
//return !empty($selector) ? $this->find($selector) : $this;
return $this->inst($this->document->documentElement, $selector, $this->options);
}
/**
* Given a CSS Selector, find matching items.
*
* @param string $selector
* CSS 3 Selector
* @return \QueryPath\DOMQuery
* @see filter()
* @see is()
* @todo If a find() returns zero matches, then a subsequent find() will
* also return zero matches, even if that find has a selector like :root.
* The reason for this is that the {@link QueryPathEventHandler} does
* not set the root of the document tree if it cannot find any elements
* from which to determine what the root is. The workaround is to use
* {@link top()} to select the root element again.
*/
public function find($selector) {
//$query = new QueryPathEventHandler($this->matches);
$query = new \QueryPath\CSS\DOMTraverser($this->matches);
$query->find($selector);
//$this->setMatches($query->matches());
//return $this;
return $this->inst($query->matches(), NULL , $this->options);
}
public function findInPlace($selector) {
$query = new \QueryPath\CSS\DOMTraverser($this->matches);
$query->find($selector);
$this->setMatches($query->matches());
return $this;
}
/**
* Execute an XPath query and store the results in the QueryPath.
*
* Most methods in this class support CSS 3 Selectors. Sometimes, though,
* XPath provides a finer-grained query language. Use this to execute
* XPath queries.
*
* Beware, though. DOMQuery works best on DOM Elements, but an XPath
* query can return other nodes, strings, and values. These may not work with
* other QueryPath functions (though you will be able to access the
* values with {@link get()}).
*
* @param string $query
* An XPath query.
* @param array $options
* Currently supported options are:
* - 'namespace_prefix': And XML namespace prefix to be used as the default. Used
* in conjunction with 'namespace_uri'
* - 'namespace_uri': The URI to be used as the default namespace URI. Used
* with 'namespace_prefix'
* @return \QueryPath\DOMQuery
* A DOMQuery object wrapping the results of the query.
* @see find()
* @author M Butcher
* @author Xavier Prud'homme
*/
public function xpath($query, $options = array()) {
$xpath = new \DOMXPath($this->document);
// Register a default namespace.
if (!empty($options['namespace_prefix']) && !empty($options['namespace_uri'])) {
$xpath->registerNamespace($options['namespace_prefix'], $options['namespace_uri']);
}
$found = new \SplObjectStorage();
foreach ($this->matches as $item) {
$nl = $xpath->query($query, $item);
if ($nl->length > 0) {
for ($i = 0; $i < $nl->length; ++$i) $found->attach($nl->item($i));
}
}
return $this->inst($found, NULL, $this->options);
//$this->setMatches($found);
//return $this;
}
/**
* Get the number of elements currently wrapped by this object.
*
* Note that there is no length property on this object.
*
* @return int
* Number of items in the object.
* @deprecated QueryPath now implements Countable, so use count().
*/
public function size() {
return $this->matches->count();
}
/**
* Get the number of elements currently wrapped by this object.
*
* Since DOMQuery is Countable, the PHP count() function can also
* be used on a DOMQuery.
*
* @code
* <?php
* count(qp($xml, 'div'));
* ?>
* @endcode
*
* @return int
* The number of matches in the DOMQuery.
*/
public function count() {
return $this->matches->count();
}
/**
* Get one or all elements from this object.
*
* When called with no paramaters, this returns all objects wrapped by
* the DOMQuery. Typically, these are DOMElement objects (unless you have
* used map(), xpath(), or other methods that can select
* non-elements).
*
* When called with an index, it will return the item in the DOMQuery with
* that index number.
*
* Calling this method does not change the DOMQuery (e.g. it is
* non-destructive).
*
* You can use qp()->get() to iterate over all elements matched. You can
* also iterate over qp() itself (DOMQuery implementations must be Traversable).
* In the later case, though, each item
* will be wrapped in a DOMQuery object. To learn more about iterating
* in QueryPath, see {@link examples/techniques.php}.
*
* @param int $index
* If specified, then only this index value will be returned. If this
* index is out of bounds, a NULL will be returned.
* @param boolean $asObject
* If this is TRUE, an SplObjectStorage object will be returned
* instead of an array. This is the preferred method for extensions to use.
* @return mixed
* If an index is passed, one element will be returned. If no index is
* present, an array of all matches will be returned.
* @see eq()
* @see SplObjectStorage
*/
public function get($index = NULL, $asObject = FALSE) {
if (isset($index)) {
return ($this->size() > $index) ? $this->getNthMatch($index) : NULL;
}
// Retain support for legacy.
if (!$asObject) {
$matches = array();
foreach ($this->matches as $m) $matches[] = $m;
return $matches;
}
return $this->matches;
}
/**
* Get the namespace of the current element.
*
* If QP is currently pointed to a list of elements, this will get the
* namespace of the first element.
*/
public function ns() {
return $this->get(0)->namespaceURI;
}
/**
* Get the DOMDocument that we currently work with.
*
* This returns the current DOMDocument. Any changes made to this document will be
* accessible to DOMQuery, as both will share access to the same object.
*
* @return DOMDocument
*/
public function document() {
return $this->document;
}
/**
* On an XML document, load all XIncludes.
*
* @return \QueryPath\DOMQuery
*/
public function xinclude() {
$this->document->xinclude();
return $this;
}
/**
* Get all current elements wrapped in an array.
* Compatibility function for jQuery 1.4, but identical to calling {@link get()}
* with no parameters.
*
* @return array
* An array of DOMNodes (typically DOMElements).
*/
public function toArray() {
return $this->get();
}
/**
* Get/set an attribute.
* - If no parameters are specified, this returns an associative array of all
* name/value pairs.
* - If both $name and $value are set, then this will set the attribute name/value
* pair for all items in this object.
* - If $name is set, and is an array, then
* all attributes in the array will be set for all items in this object.
* - If $name is a string and is set, then the attribute value will be returned.
*
* When an attribute value is retrieved, only the attribute value of the FIRST
* match is returned.
*
* @param mixed $name
* The name of the attribute or an associative array of name/value pairs.
* @param string $value
* A value (used only when setting an individual property).
* @return mixed
* If this was a setter request, return the DOMQuery object. If this was
* an access request (getter), return the string value.
* @see removeAttr()
* @see tag()
* @see hasAttr()
* @see hasClass()
*/
public function attr($name = NULL, $value = NULL) {
// Default case: Return all attributes as an assoc array.
if (is_null($name)) {
if ($this->matches->count() == 0) return NULL;
$ele = $this->getFirstMatch();
$buffer = array();
// This does not appear to be part of the DOM
// spec. Nor is it documented. But it works.
foreach ($ele->attributes as $name => $attrNode) {
$buffer[$name] = $attrNode->value;
}
return $buffer;
}
// multi-setter
if (is_array($name)) {
foreach ($name as $k => $v) {
foreach ($this->matches as $m) $m->setAttribute($k, $v);
}
return $this;
}
// setter
if (isset($value)) {
foreach ($this->matches as $m) $m->setAttribute($name, $value);
return $this;
}
//getter
if ($this->matches->count() == 0) return NULL;
// Special node type handler:
if ($name == 'nodeType') {
return $this->getFirstMatch()->nodeType;
}
// Always return first match's attr.
return $this->getFirstMatch()->getAttribute($name);
}
/**
* Check to see if the given attribute is present.
*
* This returns TRUE if <em>all</em> selected items have the attribute, or
* FALSE if at least one item does not have the attribute.
*
* @param string $attrName
* The attribute name.
* @return boolean
* TRUE if all matches have the attribute, FALSE otherwise.
* @since 2.0
* @see attr()
* @see hasClass()
*/
public function hasAttr($attrName) {
foreach ($this->matches as $match) {
if (!$match->hasAttribute($attrName)) return FALSE;
}
return TRUE;
}
/**
* Set/get a CSS value for the current element(s).
* This sets the CSS value for each element in the DOMQuery object.
* It does this by setting (or getting) the style attribute (without a namespace).
*
* For example, consider this code:
* @code
* <?php
* qp(HTML_STUB, 'body')->css('background-color','red')->html();
* ?>
* @endcode
* This will return the following HTML:
* @code
* <body style="background-color: red"/>
* @endcode
*
* If no parameters are passed into this function, then the current style
* element will be returned unparsed. Example:
* @code
* <?php
* qp(HTML_STUB, 'body')->css('background-color','red')->css();
* ?>
* @endcode
* This will return the following:
* @code
* background-color: red
* @endcode
*
* As of QueryPath 2.1, existing style attributes will be merged with new attributes.
* (In previous versions of QueryPath, a call to css() overwrite the existing style
* values).
*
* @param mixed $name
* If this is a string, it will be used as a CSS name. If it is an array,
* this will assume it is an array of name/value pairs of CSS rules. It will
* apply all rules to all elements in the set.
* @param string $value
* The value to set. This is only set if $name is a string.
* @return \QueryPath\DOMQuery
*/
public function css($name = NULL, $value = '') {
if (empty($name)) {
return $this->attr('style');
}
foreach ($this->matches as $match) {
// Get any existing CSS. //+
$css = array(); //The css is restored in every repetition of the loop, so that it doesn't
//homogenize all of the matches to share ALL their css attributes, only
//the ones indicated in the parameters.
$style = $match->getAttribute('style');
//$style =$this->attr('style');
if (!empty($style)) {
// XXX: Is this sufficient?
$style_array = explode(';', $style);
foreach ($style_array as $item) {
$item = trim($item);
// Skip empty attributes.
if (strlen($item) == 0) continue;
list($css_att, $css_val) = explode(':',$item, 2);
$css[$css_att] = trim($css_val);
}
}
if (is_array($name)) {
// Use array_merge instead of + to preserve order.
$css = array_merge($css, $name);
}
else {
$css[$name] = $value;
}
// Collapse CSS into a string.
$format = '%s: %s;';
$css_string = '';
foreach ($css as $n => $v) {
$css_string .= sprintf($format, $n, trim($v));
}
//$this->attr('style', $css_string); //Deprecated: instead of sharing the same style for all the matches,
// the change in the css will be applied finely for
// each match without homogenization
$match->setAttribute('style', $css_string);
}
return $this;
} //End of css function
/**
* Insert or retrieve a Data URL.
*
* When called with just $attr, it will fetch the result, attempt to decode it, and
* return an array with the MIME type and the application data.
*
* When called with both $attr and $data, it will inject the data into all selected elements
* So @code$qp->dataURL('src', file_get_contents('my.png'), 'image/png')@endcode will inject
* the given PNG image into the selected elements.
*
* The current implementation only knows how to encode and decode Base 64 data.
*
* Note that this is known *not* to work on IE 6, but should render fine in other browsers.
*
* @param string $attr
* The name of the attribute.
* @param mixed $data
* The contents to inject as the data. The value can be any one of the following:
* - A URL: If this is given, then the subsystem will read the content from that URL. THIS
* MUST BE A FULL URL, not a relative path.
* - A string of data: If this is given, then the subsystem will encode the string.
* - A stream or file handle: If this is given, the stream's contents will be encoded
* and inserted as data.
* (Note that we make the assumption here that you would never want to set data to be
* a URL. If this is an incorrect assumption, file a bug.)
* @param string $mime
* The MIME type of the document.
* @param resource $context
* A valid context. Use this only if you need to pass a stream context. This is only necessary
* if $data is a URL. (See {@link stream_context_create()}).
* @return \QueryPath\DOMQuery|string
* If this is called as a setter, this will return a DOMQuery object. Otherwise, it
* will attempt to fetch data out of the attribute and return that.
* @see http://en.wikipedia.org/wiki/Data:_URL
* @see attr()
* @since 2.1
*/
public function dataURL($attr, $data = NULL, $mime = 'application/octet-stream', $context = NULL) {
if (is_null($data)) {
// Attempt to fetch the data
$data = $this->attr($attr);
if (empty($data) || is_array($data) || strpos($data, 'data:') !== 0) {
return;
}
// So 1 and 2 should be MIME types, and 3 should be the base64-encoded data.
$regex = '/^data:([a-zA-Z0-9]+)\/([a-zA-Z0-9]+);base64,(.*)$/';
$matches = array();
preg_match($regex, $data, $matches);
if (!empty($matches)) {
$result = array(
'mime' => $matches[1] . '/' . $matches[2],
'data' => base64_decode($matches[3]),
);
return $result;
}
}
else {
$attVal = \QueryPath::encodeDataURL($data, $mime, $context);
return $this->attr($attr, $attVal);
}
}
/**
* Remove the named attribute from all elements in the current DOMQuery.
*
* This will remove any attribute with the given name. It will do this on each
* item currently wrapped by DOMQuery.
*
* As is the case in jQuery, this operation is not considered destructive.
*
* @param string $name
* Name of the parameter to remove.
* @return \QueryPath\DOMQuery
* The DOMQuery object with the same elements.
* @see attr()
*/
public function removeAttr($name) {
foreach ($this->matches as $m) {
//if ($m->hasAttribute($name))
$m->removeAttribute($name);
}
return $this;
}
/**
* Reduce the matched set to just one.
*
* This will take a matched set and reduce it to just one item -- the item
* at the index specified. This is a destructive operation, and can be undone
* with {@link end()}.
*
* @param $index
* The index of the element to keep. The rest will be
* discarded.
* @return \QueryPath\DOMQuery
* @see get()
* @see is()
* @see end()
*/
public function eq($index) {
return $this->inst($this->getNthMatch($index), NULL, $this->options);
// XXX: Might there be a more efficient way of doing this?
//$this->setMatches($this->getNthMatch($index));
//return $this;
}
/**
* Given a selector, this checks to see if the current set has one or more matches.
*
* Unlike jQuery's version, this supports full selectors (not just simple ones).
*
* @param string $selector
* The selector to search for. As of QueryPath 2.1.1, this also supports passing a
* DOMNode object.
* @return boolean
* TRUE if one or more elements match. FALSE if no match is found.
* @see get()
* @see eq()
*/
public function is($selector) {
if (is_object($selector)) {
if ($selector instanceof \DOMNode) {
return count($this->matches) == 1 && $selector->isSameNode($this->get(0));
}
elseif ($selector instanceof \Traversable) {
if (count($selector) != count($this->matches)) {
return FALSE;
}
// Without $seen, there is an edge case here if $selector contains the same object
// more than once, but the counts are equal. For example, [a, a, a, a] will
// pass an is() on [a, b, c, d]. We use the $seen SPLOS to prevent this.
$seen = new \SplObjectStorage();
foreach ($selector as $item) {
if (!$this->matches->contains($item) || $seen->contains($item)) {
return FALSE;
}
$seen->attach($item);
}
return TRUE;
}
throw new \QueryPath\Exception('Cannot compare an object to a DOMQuery.');
return FALSE;
}
// Testing based on Issue #70.
//fprintf(STDOUT, __FUNCTION__ .' found %d', $this->find($selector)->count());
return $this->branch($selector)->count() > 0;
// Old version:
//foreach ($this->matches as $m) {
//$q = new \QueryPath\CSS\QueryPathEventHandler($m);
//if ($q->find($selector)->getMatches()->count()) {
//return TRUE;
//}
//}
//return FALSE;
}
/**
* Filter a list down to only elements that match the selector.
* Use this, for example, to find all elements with a class, or with
* certain children.
*
* @param string $selector
* The selector to use as a filter.
* @return \QueryPath\DOMQuery
* The DOMQuery with non-matching items filtered out.
* @see filterLambda()
* @see filterCallback()
* @see map()
* @see find()
* @see is()
*/
public function filter($selector) {
$found = new \SplObjectStorage();
$tmp = new \SplObjectStorage();
foreach ($this->matches as $m) {
$tmp->attach($m);
// Seems like this should be right... but it fails unit
// tests. Need to compare to jQuery.
// $query = new \QueryPath\CSS\DOMTraverser($tmp, TRUE, $m);
$query = new \QueryPath\CSS\DOMTraverser($tmp);
$query->find($selector);
if (count($query->matches())) {
$found->attach($m);
}
$tmp->detach($m);
}
return $this->inst($found, NULL, $this->options);
}
/**
* Sort the contents of the QueryPath object.
*
* By default, this does not change the order of the elements in the
* DOM. Instead, it just sorts the internal list. However, if TRUE
* is passed in as the second parameter then QueryPath will re-order
* the DOM, too.
*
* @attention
* DOM re-ordering is done by finding the location of the original first
* item in the list, and then placing the sorted list at that location.
*
* The argument $compartor is a callback, such as a function name or a
* closure. The callback receives two DOMNode objects, which you can use
* as DOMNodes, or wrap in QueryPath objects.
*
* A simple callback:
* @code
* <?php
* $comp = function (\DOMNode $a, \DOMNode $b) {
* if ($a->textContent == $b->textContent) {
* return 0;
* }
* return $a->textContent > $b->textContent ? 1 : -1;
* };
* $qp = QueryPath::with($xml, $selector)->sort($comp);
* ?>
* @endcode
*
* The above sorts the matches into lexical order using the text of each node.
* If you would prefer to work with QueryPath objects instead of DOMNode
* objects, you may prefer something like this:
*
* @code
* <?php
* $comp = function (\DOMNode $a, \DOMNode $b) {
* $qpa = qp($a);
* $qpb = qp($b);
*
* if ($qpa->text() == $qpb->text()) {
* return 0;
* }
* return $qpa->text()> $qpb->text()? 1 : -1;
* };
*
* $qp = QueryPath::with($xml, $selector)->sort($comp);
* ?>
* @endcode
*
* @param callback $comparator
* A callback. This will be called during sorting to compare two DOMNode
* objects.
* @param boolean $modifyDOM
* If this is TRUE, the sorted results will be inserted back into
* the DOM at the position of the original first element.
* @return \QueryPath\DOMQuery
* This object.
*/
public function sort($comparator, $modifyDOM = FALSE) {
// Sort as an array.
$list = iterator_to_array($this->matches);
if (empty($list)) {
return $this;
}
$oldFirst = $list[0];
usort($list, $comparator);
// Copy back into SplObjectStorage.
$found = new \SplObjectStorage();
foreach ($list as $node) {
$found->attach($node);
}
//$this->setMatches($found);
// Do DOM modifications only if necessary.
if ($modifyDOM) {
$placeholder = $oldFirst->ownerDocument->createElement('_PLACEHOLDER_');
$placeholder = $oldFirst->parentNode->insertBefore($placeholder, $oldFirst);
$len = count($list);
for ($i = 0; $i < $len; ++$i) {
$node = $list[$i];
$node = $node->parentNode->removeChild($node);
$placeholder->parentNode->insertBefore($node, $placeholder);
}
$placeholder->parentNode->removeChild($placeholder);
}
return $this->inst($found, NULL, $this->options);
}
/**
* Filter based on a lambda function.
*
* The function string will be executed as if it were the body of a
* function. It is passed two arguments:
* - $index: The index of the item.
* - $item: The current Element.
* If the function returns boolean FALSE, the item will be removed from
* the list of elements. Otherwise it will be kept.
*
* Example:
* @code
* qp('li')->filterLambda('qp($item)->attr("id") == "test"');
* @endcode
*
* The above would filter down the list to only an item whose ID is
* 'text'.
*
* @param string $fn
* Inline lambda function in a string.
* @return \QueryPath\DOMQuery
* @see filter()
* @see map()
* @see mapLambda()
* @see filterCallback()
*/
public function filterLambda($fn) {
$function = create_function('$index, $item', $fn);
$found = new \SplObjectStorage();
$i = 0;
foreach ($this->matches as $item)
if ($function($i++, $item) !== FALSE) $found->attach($item);
return $this->inst($found, NULL, $this->options);
}
/**
* Use regular expressions to filter based on the text content of matched elements.
*
* Only items that match the given regular expression will be kept. All others will
* be removed.
*
* The regular expression is run against the <i>text content</i> (the PCDATA) of the
* elements. This is a way of filtering elements based on their content.
*
* Example:
* @code
* <?xml version="1.0"?>
* <div>Hello <i>World</i></div>
* @endcode
*
* @code
* <?php
* // This will be 1.
* qp($xml, 'div')->filterPreg('/World/')->size();
* ?>
* @endcode
*
* The return value above will be 1 because the text content of @codeqp($xml, 'div')@endcode is
* @codeHello World@endcode.
*
* Compare this to the behavior of the <em>:contains()</em> CSS3 pseudo-class.
*
* @param string $regex
* A regular expression.
* @return \QueryPath\DOMQuery
* @see filter()
* @see filterCallback()
* @see preg_match()
*/
public function filterPreg($regex) {
$found = new \SplObjectStorage();
foreach ($this->matches as $item) {
if (preg_match($regex, $item->textContent) > 0) {
$found->attach($item);
}
}
return $this->inst($found, NULL, $this->options);
}