summaryrefslogtreecommitdiff
path: root/lib/querypath/src/QueryPath/CSS/DOMTraverser.php
blob: be8c2afdeb2eb40c13cc7893ccf9012d311301c0 (plain)
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
<?php
/** @file
 * Traverse a DOM.
 */

namespace QueryPath\CSS;

use \QueryPath\CSS\DOMTraverser\Util;
use \QueryPath\CSS\DOMTraverser\PseudoClass;
use \QueryPath\CSS\DOMTraverser\PseudoElement;

/**
 * Traverse a DOM, finding matches to the selector.
 *
 * This traverses a DOMDocument and attempts to find
 * matches to the provided selector.
 *
 * \b How this works
 *
 * This performs a bottom-up search. On the first pass,
 * it attempts to find all of the matching elements for the
 * last simple selector in a selector.
 *
 * Subsequent passes attempt to eliminate matches from the
 * initial matching set.
 *
 * Example:
 *
 * Say we begin with the selector `foo.bar baz`. This is processed
 * as follows:
 *
 * - First, find all baz elements.
 * - Next, for any baz element that does not have foo as an ancestor,
 *   eliminate it from the matches.
 * - Finally, for those that have foo as an ancestor, does that foo
 *   also have a class baz? If not, it is removed from the matches.
 *
 * \b Extrapolation
 *
 * Partial simple selectors are almost always expanded to include an
 * element.
 *
 * Examples:
 *
 * - `:first` is expanded to `*:first`
 * - `.bar` is expanded to `*.bar`.
 * - `.outer .inner` is expanded to `*.outer *.inner`
 *
 * The exception is that IDs are sometimes not expanded, e.g.:
 *
 * - `#myElement` does not get expanded
 * - `#myElement .class` \i may be expanded to `*#myElement *.class`
 *   (which will obviously not perform well).
 */
class DOMTraverser implements Traverser {

  protected $matches = array();
  protected $selector;
  protected $dom;
  protected $initialized = TRUE;
  protected $psHandler;
  protected $scopeNode;

  /**
   * Build a new DOMTraverser.
   *
   * This requires a DOM-like object or collection of DOM nodes.
   */
  public function __construct(\SPLObjectStorage $splos, $initialized = FALSE, $scopeNode = NULL) {

    $this->psHandler = new \QueryPath\CSS\DOMTraverser\PseudoClass();
    $this->initialized = $initialized;

    // Re-use the initial splos
    $this->matches = $splos;

    if (count($splos) != 0) {
      $splos->rewind();
      $first = $splos->current();
      if ($first instanceof \DOMDocument) {
        $this->dom = $first;//->documentElement;
      }
      else {
        $this->dom = $first->ownerDocument;//->documentElement;
      }
      if (empty($scopeNode)) {
        $this->scopeNode = $this->dom->documentElement;
      }
      else {
        $this->scopeNode = $scopeNode;
      }
    }

    // This assumes a DOM. Need to also accomodate the case
    // where we get a set of elements.
    /*
    $this->dom = $dom;
    $this->matches = new \SplObjectStorage();
    $this->matches->attach($this->dom);
     */
  }

  public function debug($msg) {
    fwrite(STDOUT, PHP_EOL . $msg);
  }

  /**
   * Given a selector, find the matches in the given DOM.
   *
   * This is the main function for querying the DOM using a CSS
   * selector.
   *
   * @param string $selector
   *   The selector.
   * @return \SPLObjectStorage
   *   An SPLObjectStorage containing a list of matched
   *   DOMNode objects.
   */
  public function find($selector) {
    // Setup
    $handler = new Selector();
    $parser = new Parser($selector, $handler);
    $parser->parse();
    $this->selector = $handler;

    //$selector = $handler->toArray();
    $found = $this->newMatches();
    foreach ($handler as $selectorGroup) {
      // fprintf(STDOUT, "Selector group.\n");
      // Initialize matches if necessary.
      if ($this->initialized) {
        $candidates = $this->matches;
      }
      else {
        //if (empty($selectorGroup)) {
          // fprintf(STDOUT, "%s", print_r($handler->toArray(), TRUE));
        //}
        $candidates = $this->initialMatch($selectorGroup[0], $this->matches);
        //$this->initialized = TRUE;
      }

      foreach ($candidates as $candidate) {
        // fprintf(STDOUT, "Testing %s against %s.\n", $candidate->tagName, $selectorGroup[0]);
        if ($this->matchesSelector($candidate, $selectorGroup)) {
          // $this->debug('Attaching ' . $candidate->nodeName);
          $found->attach($candidate);
        }
      }
    }
    $this->setMatches($found);


    return $this;
  }

  public function matches() {
    return $this->matches;
  }

  /**
   * Check whether the given node matches the given selector.
   *
   * A selector is a group of one or more simple selectors combined
   * by combinators. This determines if a given selector
   * matches the given node.
   *
   * @attention
   * Evaluation of selectors is done recursively. Thus the length
   * of the selector is limited to the recursion depth allowed by
   * the PHP configuration. This should only cause problems for
   * absolutely huge selectors or for versions of PHP tuned to
   * strictly limit recursion depth.
   *
   * @param object DOMNode
   *   The DOMNode to check.
   * @param array Selector->toArray()
   *   The Selector to check.
   * @return boolean
   *   A boolean TRUE if the node matches, false otherwise.
   */
  public function matchesSelector($node, $selector) {
    return $this->matchesSimpleSelector($node, $selector, 0);
  }

  /**
   * Performs a match check on a SimpleSelector.
   *
   * Where matchesSelector() does a check on an entire selector,
   * this checks only a simple selector (plus an optional
   * combinator).
   *
   * @param object DOMNode
   *   The DOMNode to check.
   * @param object SimpleSelector
   *   The Selector to check.
   * @return boolean
   *   A boolean TRUE if the node matches, false otherwise.
   */
  public function matchesSimpleSelector($node, $selectors, $index) {
    $selector = $selectors[$index];
    // Note that this will short circuit as soon as one of these
    // returns FALSE.
    $result = $this->matchElement($node, $selector->element, $selector->ns)
      && $this->matchAttributes($node, $selector->attributes)
      && $this->matchId($node, $selector->id)
      && $this->matchClasses($node, $selector->classes)
      && $this->matchPseudoClasses($node, $selector->pseudoClasses)
      && $this->matchPseudoElements($node, $selector->pseudoElements);

    $isNextRule = isset($selectors[++$index]);
    // If there is another selector, we process that if there a match
    // hasn't been found.
    /*
    if ($isNextRule && $selectors[$index]->combinator == SimpleSelector::anotherSelector) {
      // We may need to re-initialize the match set for the next selector.
      if (!$this->initialized) {
        $this->initialMatch($selectors[$index]);
      }
      if (!$result) fprintf(STDOUT, "Element: %s, Next selector: %s\n", $node->tagName, $selectors[$index]);
      return $result || $this->matchesSimpleSelector($node, $selectors, $index);
    }
    // If we have a match and we have a combinator, we need to
    // recurse up the tree.
    else*/if ($isNextRule && $result) {
      $result = $this->combine($node, $selectors, $index);
    }

    return $result;
  }

  /**
   * Combine the next selector with the given match
   * using the next combinator.
   *
   * If the next selector is combined with another
   * selector, that will be evaluated too, and so on.
   * So if this function returns TRUE, it means that all
   * child selectors are also matches.
   *
   * @param DOMNode $node
   *   The DOMNode to test.
   * @param array $selectors
   *   The array of simple selectors.
   * @param int $index
   *   The index of the current selector.
   * @return boolean
   *   TRUE if the next selector(s) match.
   */
  public function combine($node, $selectors, $index) {
    $selector = $selectors[$index];
    //$this->debug(implode(' ', $selectors));
    switch ($selector->combinator) {
      case SimpleSelector::adjacent:
        return $this->combineAdjacent($node, $selectors, $index);
      case SimpleSelector::sibling:
        return $this->combineSibling($node, $selectors, $index);
      case SimpleSelector::directDescendant:
        return $this->combineDirectDescendant($node, $selectors, $index);
      case SimpleSelector::anyDescendant:
        return $this->combineAnyDescendant($node, $selectors, $index);
      case SimpleSelector::anotherSelector:
        // fprintf(STDOUT, "Next selector: %s\n", $selectors[$index]);
        return $this->matchesSimpleSelector($node, $selectors, $index);
      ;
    }
    return FALSE;
  }

  /**
   * Process an Adjacent Sibling.
   *
   * The spec does not indicate whether Adjacent should ignore non-Element
   * nodes, so we choose to ignore them.
   *
   * @param DOMNode $node
   *   A DOM Node.
   * @param array $selectors
   *   The selectors array.
   * @param int $index
   *   The current index to the operative simple selector in the selectors
   *   array.
   * @return boolean
   *   TRUE if the combination matches, FALSE otherwise.
   */
  public function combineAdjacent($node, $selectors, $index) {
    while (!empty($node->previousSibling)) {
      $node = $node->previousSibling;
      if ($node->nodeType == XML_ELEMENT_NODE) {
        //$this->debug(sprintf('Testing %s against "%s"', $node->tagName, $selectors[$index]));
        return $this->matchesSimpleSelector($node, $selectors, $index);
      }
    }
    return FALSE;
  }

  /**
   * Check all siblings.
   *
   * According to the spec, this only tests elements LEFT of the provided
   * node.
   *
   * @param DOMNode $node
   *   A DOM Node.
   * @param array $selectors
   *   The selectors array.
   * @param int $index
   *   The current index to the operative simple selector in the selectors
   *   array.
   * @return boolean
   *   TRUE if the combination matches, FALSE otherwise.
   */
  public function combineSibling($node, $selectors, $index) {
    while (!empty($node->previousSibling)) {
      $node = $node->previousSibling;
      if ($node->nodeType == XML_ELEMENT_NODE && $this->matchesSimpleSelector($node, $selectors, $index)) {
        return TRUE;
      }
    }
    return FALSE;
  }

  /**
   * Handle a Direct Descendant combination.
   *
   * Check whether the given node is a rightly-related descendant
   * of its parent node.
   *
   * @param DOMNode $node
   *   A DOM Node.
   * @param array $selectors
   *   The selectors array.
   * @param int $index
   *   The current index to the operative simple selector in the selectors
   *   array.
   * @return boolean
   *   TRUE if the combination matches, FALSE otherwise.
   */
  public function combineDirectDescendant($node, $selectors, $index) {
    $parent = $node->parentNode;
    if (empty($parent)) {
      return FALSE;
    }
    return $this->matchesSimpleSelector($parent, $selectors, $index);
  }

  /**
   * Handle Any Descendant combinations.
   *
   * This checks to see if there are any matching routes from the
   * selector beginning at the present node.
   *
   * @param DOMNode $node
   *   A DOM Node.
   * @param array $selectors
   *   The selectors array.
   * @param int $index
   *   The current index to the operative simple selector in the selectors
   *   array.
   * @return boolean
   *   TRUE if the combination matches, FALSE otherwise.
   */
  public function combineAnyDescendant($node, $selectors, $index) {
    while (!empty($node->parentNode)) {
      $node = $node->parentNode;

      // Catch case where element is child of something
      // else. This should really only happen with a
      // document element.
      if ($node->nodeType != XML_ELEMENT_NODE) {
        continue;
      }

      if ($this->matchesSimpleSelector($node, $selectors, $index)) {
        return TRUE;
      }
    }
  }

  /**
   * Get the intial match set.
   *
   * This should only be executed when not working with
   * an existing match set.
   */
  protected function initialMatch($selector, $matches) {
    $element = $selector->element;

    // If no element is specified, we have to start with the
    // entire document.
    if ($element == NULL) {
      $element = '*';
    }

    // fprintf(STDOUT, "Initial match using %s.\n", $selector);

    // We try to do some optimization here to reduce the
    // number of matches to the bare minimum. This will
    // reduce the subsequent number of operations that
    // must be performed in the query.

    // Experimental: ID queries use XPath to match, since
    // this should give us only a single matched element
    // to work with.
    if (/*$element == '*' &&*/ !empty($selector->id)) {
      // fprintf(STDOUT, "ID Fastrack on %s\n", $selector);
      $initialMatches = $this->initialMatchOnID($selector, $matches);
    }
    // If a namespace is set, find the namespace matches.
    elseif (!empty($selector->ns)) {
      $initialMatches = $this->initialMatchOnElementNS($selector, $matches);
    }
    // If the element is a wildcard, using class can
    // substantially reduce the number of elements that
    // we start with.
    elseif ($element == '*' && !empty($selector->classes)) {
      // fprintf(STDOUT, "Class Fastrack on %s\n", $selector);
      $initialMatches = $this->initialMatchOnClasses($selector, $matches);
    }
    else {
      $initialMatches = $this->initialMatchOnElement($selector, $matches);
    }

    //fprintf(STDOUT, "Found %d nodes.\n", count($this->matches));
    return $initialMatches;
  }

  /**
   * Shortcut for finding initial match by ID.
   *
   * If the element is set to '*' and an ID is
   * set, then this should be used to find by ID,
   * which will drastically reduce the amount of
   * comparison operations done in PHP.
   *
   */
  protected function initialMatchOnID($selector, $matches) {
    $id = $selector->id;
    $found = $this->newMatches();

    // Issue #145: DOMXPath will through an exception if the DOM is
    // not set.
    if (!($this->dom instanceof \DOMDocument)) {
      return $found;
    }
    $baseQuery = ".//*[@id='{$id}']";
    $xpath = new \DOMXPath($this->dom);

    // Now we try to find any matching IDs.
    foreach ($matches as $node) {
      if ($node->getAttribute('id') == $id) {
        $found->attach($node);
      }
      $nl = $this->initialXpathQuery($xpath, $node, $baseQuery);
      $this->attachNodeList($nl, $found);
    }
    // Unset the ID selector.
    $selector->id = NULL;
    return $found;
  }

  /**
   * Shortcut for setting the intial match.
   *
   * This shortcut should only be used when the initial
   * element is '*' and there are classes set.
   *
   * In any other case, the element finding algo is
   * faster and should be used instead.
   */
  protected function initialMatchOnClasses($selector, $matches) {
    $found = $this->newMatches();

    // Issue #145: DOMXPath will through an exception if the DOM is
    // not set.
    if (!($this->dom instanceof \DOMDocument)) {
      return $found;
    }
    $baseQuery = ".//*[@class]";
    $xpath = new \DOMXPath($this->dom);

    // Now we try to find any matching IDs.
    foreach ($matches as $node) {
      // Refactor me!
      if ($node->hasAttribute('class')) {
        $intersect = array_intersect($selector->classes, explode(' ', $node->getAttribute('class')));
        if (count($intersect) == count($selector->classes)) {
          $found->attach($node);
        }
      }

      $nl = $this->initialXpathQuery($xpath, $node, $baseQuery);
      foreach ($nl as $node) {
        $classes = $node->getAttribute('class');
        $classArray = explode(' ', $classes);

        $intersect = array_intersect($selector->classes, $classArray);
        if (count($intersect) == count($selector->classes)) {
          $found->attach($node);
        }
      }
    }

    // Unset the classes selector.
    $selector->classes = array();

    return $found;
  }

  /**
   * Internal xpath query.
   *
   * This is optimized for very specific use, and is not a general
   * purpose function.
   */
  private function initialXpathQuery($xpath, $node, $query) {
      // This works around a bug in which the document element
      // does not correctly search with the $baseQuery.
      if ($node->isSameNode($this->dom->documentElement)) {
        $query = substr($query, 1);
      }

      return $xpath->query($query, $node);
  }

  /**
   * Shortcut for setting the initial match.
   */
  protected function initialMatchOnElement($selector, $matches) {
    $element = $selector->element;
    if (is_null($element)) {
      $element = '*';
    }
    $found = $this->newMatches();
    foreach ($matches as $node) {
      // Capture the case where the initial element is the root element.
      if ($node->tagName == $element
          || $element == '*' && $node->parentNode instanceof \DOMDocument) {
        $found->attach($node);
      }
      $nl = $node->getElementsByTagName($element);
      $this->attachNodeList($nl, $found);
    }

    $selector->element = NULL;
    return $found;
  }

  /**
   * Get elements and filter by namespace.
   */
  protected function initialMatchOnElementNS($selector, $matches) {
    $ns = $selector->ns;

    $elements = $this->initialMatchOnElement($selector, $matches);

    // "any namespace" matches anything.
    if ($ns == '*') {
      return $elements;
    }

    // Loop through and make a list of items that need to be filtered
    // out, then filter them. This is required b/c ObjectStorage iterates
    // wrongly when an item is detached in an access loop.
    $detach = array();
    foreach ($elements as $node) {
      // This lookup must be done PER NODE.
      $nsuri = $node->lookupNamespaceURI($ns);
      if (empty($nsuri) || $node->namespaceURI != $nsuri) {
        $detach[] = $node;
      }
    }
    foreach ($detach as $rem) {
      $elements->detach($rem);
    }
    $selector->ns = NULL;
    return $elements;
  }

  /**
   * Checks to see if the DOMNode matches the given element selector.
   *
   * This handles the following cases:
   *
   * - element (foo)
   * - namespaced element (ns|foo)
   * - namespaced wildcard (ns|*)
   * - wildcard (* or *|*)
   */
  protected function matchElement($node, $element, $ns = NULL) {
    if (empty($element)) {
      return TRUE;
    }

    // Handle namespace.
    if (!empty($ns) && $ns != '*') {
      // Check whether we have a matching NS URI.
      $nsuri = $node->lookupNamespaceURI($ns);
      if(empty($nsuri) || $node->namespaceURI !== $nsuri) {
        return FALSE;
      }
    }

    // Compare local name to given element name.
    return $element == '*' || $node->localName == $element;
  }

  /**
   * Checks to see if the given DOMNode matches an "any element" (*).
   *
   * This does not handle namespaced whildcards.
   */
  /*
  protected function matchAnyElement($node) {
    $ancestors = $this->ancestors($node);

    return count($ancestors) > 0;
  }
   */

  /**
   * Get a list of ancestors to the present node.
   */
  protected function ancestors($node) {
    $buffer = array();
    $parent = $node;
    while (($parent = $parent->parentNode) !== NULL) {
      $buffer[] = $parent;
    }
    return $buffer;
  }

  /**
   * Check to see if DOMNode has all of the given attributes.
   *
   * This can handle namespaced attributes, including namespace
   * wildcards.
   */
  protected function matchAttributes($node, $attributes) {
    if (empty($attributes)) {
      return TRUE;
    }

    foreach($attributes as $attr) {
      $val = isset($attr['value']) ? $attr['value'] : NULL;

      // Namespaced attributes.
      if (isset($attr['ns']) && $attr['ns'] != '*') {
        $nsuri = $node->lookupNamespaceURI($attr['ns']);
        if (empty($nsuri) || !$node->hasAttributeNS($nsuri, $attr['name'])) {
          return FALSE;
        }
        $matches = Util::matchesAttributeNS($node, $attr['name'], $nsuri, $val, $attr['op']);
      }
      elseif (isset($attr['ns']) && $attr['ns'] == '*' && $node->hasAttributes()) {
        // Cycle through all of the attributes in the node. Note that
        // these are DOMAttr objects.
        $matches = FALSE;
        $name = $attr['name'];
        foreach ($node->attributes as $attrNode) {
          if ($attrNode->localName == $name) {
            $nsuri = $attrNode->namespaceURI;
            $matches = Util::matchesAttributeNS($node, $name, $nsuri, $val, $attr['op']);
          }
        }
      }
      // No namespace.
      else {
        $matches = Util::matchesAttribute($node, $attr['name'], $val, $attr['op']);
      }

      if (!$matches) {
        return FALSE;
      }
    }
    return TRUE;
  }
  /**
   * Check that the given DOMNode has the given ID.
   */
  protected function matchId($node, $id) {
    if (empty($id)) {
      return TRUE;
    }
    return $node->hasAttribute('id') && $node->getAttribute('id') == $id;
  }
  /**
   * Check that the given DOMNode has all of the given classes.
   */
  protected function matchClasses($node, $classes) {
    if (empty($classes)) {
      return TRUE;
    }

    if (!$node->hasAttribute('class')) {
      return FALSE;
    }

    $eleClasses = preg_split('/\s+/', $node->getAttribute('class'));
    if (empty($eleClasses)) {
      return FALSE;
    }

    // The intersection should match the given $classes.
    $missing = array_diff($classes, array_intersect($classes, $eleClasses));

    return count($missing) == 0;
  }
  protected function matchPseudoClasses($node, $pseudoClasses) {
    $ret = TRUE;
    foreach ($pseudoClasses as $pseudoClass) {
      $name = $pseudoClass['name'];
      // Avoid E_STRICT violation.
      $value = isset($pseudoClass['value']) ? $pseudoClass['value'] : NULL;
      $ret &= $this->psHandler->elementMatches($name, $node, $this->scopeNode, $value);
    }
    return $ret;
  }
  /**
   * Test whether the given node matches the pseudoElements.
   *
   * If any pseudo-elements are passed, this will test to see
   * <i>if conditions obtain that would allow the pseudo-element
   * to be created</i>. This does not modify the match in any way.
   */
  protected function matchPseudoElements($node, $pseudoElements) {
    if (empty($pseudoElements)) {
      return TRUE;
    }

    foreach ($pseudoElements as $pse) {
      switch ($pse) {
        case 'first-line':
        case 'first-letter':
        case 'before':
        case 'after':
          return strlen($node->textContent) > 0;
        case 'selection':
          throw new \QueryPath\CSS\NotImplementedException("::$name is not implemented.");
      }
    }
  }

  protected function newMatches() {
    return new \SplObjectStorage();
  }

  /**
   * Get the internal match set.
   * Internal utility function.
   */
  protected function getMatches() {
    return $this->matches();
  }

  /**
   * Set the internal match set.
   *
   * Internal utility function.
   */
  protected function setMatches($matches) {
    $this->matches = $matches;
  }

  /**
   * Attach all nodes in a node list to the given \SplObjectStorage.
   */
  public function attachNodeList(\DOMNodeList $nodeList, \SplObjectStorage $splos) {
    foreach ($nodeList as $item) $splos->attach($item);
  }

  public function getDocument() {
    return $this->dom;
  }

}