Debian Codegraph @

vendor/mck89/peast/lib/Peast/Query.php

raw
1 <?php
2 /**
3 * This file is part of the Peast package
4 *
5 * (c) Marco Marchiò <[email protected]>
6 *
7 * For the full copyright and license information refer to the LICENSE file
8 * distributed with this source code
9 */
10 namespace Peast;
11
12 /**
13 * Nodes query class
14 *
15 * @author Marco Marchiò <[email protected]>
16 */
17 class Query implements \IteratorAggregate, \Countable
18 {
19 /**
20 * Current matches
21 *
22 * @var Selector\Matches
23 */
24 protected $matches;
25
26 /**
27 * Options array
28 *
29 * @var array
30 */
31 protected $options;
32
33 /**
34 * Class constructor. Available options are:
35 * - encoding: selectors encoding. If not specified the
36 * parser will assume UTF-8.
37 *
38 * @param Syntax\Node\Program $root Root node
39 * @param array $options Options array
40 */
41 public function __construct(Syntax\Node\Program $root, $options = array())
42 {
43 $this->matches = new Selector\Matches();
44 $this->matches->addMatch($root);
45 $this->options = $options;
46 }
47
48 /**
49 * Finds nodes matching the given selector starting from the
50 * current matched nodes, if any, or from the root
51 *
52 * @param string $selector Selector
53 *
54 * @return $this
55 *
56 * @throws Selector\Exception
57 */
58 public function find($selector)
59 {
60 $parser = new Selector\Parser($selector, $this->options);
61 $selector = $parser->parse();
62 $this->matches = $selector->exec($this->matches);
63 return $this;
64 }
65
66 /**
67 * Executes the given selector on the current nodes and filters
68 * out the nodes which don't match
69 *
70 * @param string $selector Selector
71 *
72 * @return $this
73 *
74 * @throws Selector\Exception
75 */
76 public function filter($selector)
77 {
78 $parser = new Selector\Parser($selector, $this->options);
79 $selector = $parser->parse(true);
80 $this->matches->filter(function ($node, $parent) use ($selector) {
81 $newMatch = new Selector\Matches();
82 $newMatch->addMatch($node, $parent);
83 return $selector->exec($newMatch)->getMatches();
84 });
85 return $this;
86 }
87
88 /**
89 * Returns the number of matched nodes
90 *
91 * @return int
92 */
93 #[\ReturnTypeWillChange]
94 public function count()
95 {
96 return $this->matches->count();
97 }
98
99 /**
100 * Returns the node at the given index
101 *
102 * @param int $index Index
103 *
104 * @return array
105 *
106 * @throws \Exception
107 */
108 public function get($index)
109 {
110 return $this->matches->get($index)[0];
111 }
112
113 /**
114 * Returns the nodes iterator
115 *
116 * @return \ArrayIterator
117 */
118 #[\ReturnTypeWillChange]
119 public function getIterator()
120 {
121 return new \ArrayIterator($this->matches->getNodes());
122 }
123 }