-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSelector.php
378 lines (337 loc) · 10.7 KB
/
Selector.php
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
<?php
namespace PHPHtmlParser;
use PHPHtmlParser\Dom\AbstractNode;
use PHPHtmlParser\Dom\Collection;
use PHPHtmlParser\Dom\InnerNode;
use PHPHtmlParser\Dom\LeafNode;
use PHPHtmlParser\Exceptions\ChildNotFoundException;
/**
* Class Selector
*
* @package PHPHtmlParser
*/
class Selector
{
/**
* Pattern of CSS selectors, modified from 'mootools'
*
* @var string
*/
protected $pattern = "/([\w-:\*>]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-:]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is";
protected $selectors = [];
/**
* Constructs with the selector string
*
* @param string $selector
*/
public function __construct($selector)
{
$this->parseSelectorString($selector);
}
/**
* Returns the selectors that where found in __construct
*
* @return array
*/
public function getSelectors()
{
return $this->selectors;
}
/**
* Attempts to find the selectors starting from the given
* node object.
*
* @param AbstractNode $node
* @return Collection
*/
public function find(AbstractNode $node)
{
$results = new Collection;
foreach ($this->selectors as $selector) {
$nodes = [$node];
if (count($selector) == 0) {
continue;
}
$options = [];
foreach ($selector as $rule) {
if ($rule['alterNext']) {
$options[] = $this->alterNext($rule);
continue;
}
$nodes = $this->seek($nodes, $rule, $options);
// clear the options
$options = [];
}
// this is the final set of nodes
foreach ($nodes as $result) {
$results[] = $result;
}
}
return $results;
}
/**
* Parses the selector string
*
* @param string $selector
*/
protected function parseSelectorString($selector)
{
$matches = [];
preg_match_all($this->pattern, trim($selector).' ', $matches, PREG_SET_ORDER);
// skip tbody
$result = [];
foreach ($matches as $match) {
// default values
$tag = strtolower(trim($match[1]));
$operator = '=';
$key = null;
$value = null;
$noKey = false;
$alterNext = false;
// check for elements that alter the behavior of the next element
if ($tag == '>') {
$alterNext = true;
}
// check for id selector
if ( ! empty($match[2])) {
$key = 'id';
$value = $match[2];
}
// check for class selector
if ( ! empty($match[3])) {
$key = 'class';
$value = $match[3];
}
// and final attribute selector
if ( ! empty($match[4])) {
$key = strtolower($match[4]);
}
if ( ! empty($match[5])) {
$operator = $match[5];
}
if ( ! empty($match[6])) {
$value = $match[6];
}
// check for elements that do not have a specified attribute
if (isset($key[0]) && $key[0] == '!') {
$key = substr($key, 1);
$noKey = true;
}
$result[] = [
'tag' => $tag,
'key' => $key,
'value' => $value,
'operator' => $operator,
'noKey' => $noKey,
'alterNext' => $alterNext,
];
if (trim($match[7]) == ',') {
$this->selectors[] = $result;
$result = [];
}
}
// save last results
if (count($result) > 0) {
$this->selectors[] = $result;
}
}
/**
* Attempts to find all children that match the rule
* given.
*
* @param array $nodes
* @param array $rule
* @param array $options
* @return array
* @recursive
*/
protected function seek(array $nodes, array $rule, array $options)
{
// XPath index
if (count($rule['tag']) > 0 &&
count($rule['key']) > 0 &&
is_numeric($rule['key'])
) {
$count = 0;
/** @var AbstractNode $node */
foreach ($nodes as $node) {
if ($rule['tag'] == '*' ||
$rule['tag'] == $node->getTag()->name()
) {
++$count;
if ($count == $rule['key']) {
// found the node we wanted
return [$node];
}
}
}
return [];
}
$options = $this->flattenOptions($options);
$return = [];
/** @var InnerNode $node */
foreach ($nodes as $node) {
// check if we are a leaf
if ($node instanceof LeafNode ||
! $node->hasChildren()
) {
continue;
}
$children = [];
$child = $node->firstChild();
while ( ! is_null($child)) {
// wild card, grab all
if ($rule['tag'] == '*' && is_null($rule['key'])) {
$return[] = $child;
try {
$child = $node->nextChild($child->id());
} catch (ChildNotFoundException $e) {
// no more children
$child = null;
}
continue;
}
$pass = true;
// check tag
if ( ! empty($rule['tag']) && $rule['tag'] != $child->getTag()->name() &&
$rule['tag'] != '*'
) {
// child failed tag check
$pass = false;
}
// check key
if ($pass && ! is_null($rule['key'])) {
if ($rule['noKey']) {
if ( ! is_null($child->getAttribute($rule['key']))) {
$pass = false;
}
} else {
if ($rule['key'] != 'plaintext' &&
is_null($child->getAttribute($rule['key']))
) {
$pass = false;
}
}
}
// compare values
if ($pass && ! is_null($rule['key']) &&
! is_null($rule['value']) && $rule['value'] != '*'
) {
if ($rule['key'] == 'plaintext') {
// plaintext search
$nodeValue = $child->text();
} else {
// normal search
$nodeValue = $child->getAttribute($rule['key']);
}
$check = $this->match($rule['operator'], $rule['value'], $nodeValue);
// handle multiple classes
if ( ! $check && $rule['key'] == 'class') {
$childClasses = explode(' ', $child->getAttribute('class'));
foreach ($childClasses as $class) {
if ( ! empty($class)) {
$check = $this->match($rule['operator'], $rule['value'], $class);
}
if ($check) {
break;
}
}
}
if ( ! $check) {
$pass = false;
}
}
if ($pass) {
// it passed all checks
$return[] = $child;
} else {
// this child failed to be matched
if ($child instanceof InnerNode &&
$child->hasChildren()
) {
// we still want to check its children
$children[] = $child;
}
}
try {
// get next child
$child = $node->nextChild($child->id());
} catch (ChildNotFoundException $e) {
// no more children
$child = null;
}
}
if (( ! isset($options['checkGrandChildren']) ||
$options['checkGrandChildren'])
&& count($children) > 0
) {
// we have children that failed but are not leaves.
$matches = $this->seek($children, $rule, $options);
foreach ($matches as $match) {
$return[] = $match;
}
}
}
return $return;
}
/**
* Attempts to match the given arguments with the given operator.
*
* @param string $operator
* @param string $pattern
* @param string $value
* @return bool
*/
protected function match($operator, $pattern, $value)
{
$value = strtolower($value);
$pattern = strtolower($pattern);
switch ($operator) {
case '=':
return $value === $pattern;
case '!=':
return $value !== $pattern;
case '^=':
return preg_match('/^'.preg_quote($pattern, '/').'/', $value);
case '$=':
return preg_match('/'.preg_quote($pattern, '/').'$/', $value);
case '*=':
if ($pattern[0] == '/') {
return preg_match($pattern, $value);
}
return preg_match("/".$pattern."/i", $value);
}
return false;
}
/**
* Attempts to figure out what the alteration will be for
* the next element.
*
* @param array $rule
* @return array
*/
protected function alterNext($rule)
{
$options = [];
if ($rule['tag'] == '>') {
$options['checkGrandChildren'] = false;
}
return $options;
}
/**
* Flattens the option array.
*
* @param array $optionsArray
* @return array
*/
protected function flattenOptions(array $optionsArray)
{
$options = [];
foreach ($optionsArray as $optionArray) {
foreach ($optionArray as $key => $option) {
$options[$key] = $option;
}
}
return $options;
}
}