Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
365 lars 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace PHPHtmlParser\Selector;
6
 
7
use PHPHtmlParser\Dom\AbstractNode;
8
use PHPHtmlParser\Dom\Collection;
9
use PHPHtmlParser\Dom\InnerNode;
10
use PHPHtmlParser\Dom\LeafNode;
11
use PHPHtmlParser\Exceptions\ChildNotFoundException;
12
 
13
/**
14
 * Class Selector
15
 *
16
 * @package PHPHtmlParser
17
 */
18
class Selector
19
{
20
 
21
    /**
22
     * @var array
23
     */
24
    protected $selectors = [];
25
 
26
    /**
27
     * @var bool
28
     */
29
    private $depthFirst = false;
30
 
31
    /**
32
     * Constructs with the selector string
33
     * @param string          $selector
34
     * @param ParserInterface $parser
35
     */
36
    public function __construct(string $selector, ParserInterface $parser)
37
    {
38
        $this->selectors = $parser->parseSelectorString($selector);
39
    }
40
 
41
    /**
42
     * Returns the selectors that where found in __construct
43
     * @return array
44
     */
45
    public function getSelectors()
46
    {
47
        return $this->selectors;
48
    }
49
 
50
    /**
51
     * @param bool $status
52
     * @return void
53
     */
54
    public function setDepthFirstFind(bool $status): void
55
    {
56
        $this->depthFirst = $status;
57
    }
58
 
59
    /**
60
     * Attempts to find the selectors starting from the given
61
     * node object.
62
     * @param AbstractNode $node
63
     * @return Collection
64
     * @throws ChildNotFoundException
65
     */
66
    public function find(AbstractNode $node): Collection
67
    {
68
        $results = new Collection;
69
        foreach ($this->selectors as $selector) {
70
            $nodes = [$node];
71
            if (count($selector) == 0) {
72
                continue;
73
            }
74
 
75
            $options = [];
76
            foreach ($selector as $rule) {
77
                if ($rule['alterNext']) {
78
                    $options[] = $this->alterNext($rule);
79
                    continue;
80
                }
81
                $nodes = $this->seek($nodes, $rule, $options);
82
                // clear the options
83
                $options = [];
84
            }
85
 
86
            // this is the final set of nodes
87
            foreach ($nodes as $result) {
88
                $results[] = $result;
89
            }
90
        }
91
 
92
        return $results;
93
    }
94
 
95
 
96
    /**
97
     * Attempts to find all children that match the rule
98
     * given.
99
     * @param array $nodes
100
     * @param array $rule
101
     * @param array $options
102
     * @return array
103
     * @throws ChildNotFoundException
104
     */
105
    protected function seek(array $nodes, array $rule, array $options): array
106
    {
107
        // XPath index
108
        if (array_key_exists('tag', $rule) && array_key_exists('key', $rule)
109
          && is_numeric($rule['key'])
110
        ) {
111
            $count = 0;
112
            /** @var AbstractNode $node */
113
            foreach ($nodes as $node) {
114
                if ($rule['tag'] == '*'
115
                  || $rule['tag'] == $node->getTag()
116
                    ->name()
117
                ) {
118
                    ++$count;
119
                    if ($count == $rule['key']) {
120
                        // found the node we wanted
121
                        return [$node];
122
                    }
123
                }
124
            }
125
 
126
            return [];
127
        }
128
 
129
        $options = $this->flattenOptions($options);
130
 
131
        $return = [];
132
        /** @var InnerNode $node */
133
        foreach ($nodes as $node) {
134
            // check if we are a leaf
135
            if ($node instanceof LeafNode || !$node->hasChildren()
136
            ) {
137
                continue;
138
            }
139
 
140
            $children = [];
141
            $child = $node->firstChild();
142
            while (!is_null($child)) {
143
                // wild card, grab all
144
                if ($rule['tag'] == '*' && is_null($rule['key'])) {
145
                    $return[] = $child;
146
                    $child = $this->getNextChild($node, $child);
147
                    continue;
148
                }
149
 
150
                $pass = $this->checkTag($rule, $child);
151
                if ($pass && !is_null($rule['key'])) {
152
                    $pass = $this->checkKey($rule, $child);
153
                }
154
                if ($pass && !is_null($rule['key']) && !is_null($rule['value'])
155
                  && $rule['value'] != '*'
156
                ) {
157
                    $pass = $this->checkComparison($rule, $child);
158
                }
159
 
160
                if ($pass) {
161
                    // it passed all checks
162
                    $return[] = $child;
163
                } else {
164
                    // this child failed to be matched
165
                    if ($child instanceof InnerNode && $child->hasChildren()
166
                    ) {
167
                        if ($this->depthFirst) {
168
                            if (!isset($options['checkGrandChildren'])
169
                              || $options['checkGrandChildren']
170
                            ) {
171
                                // we have a child that failed but are not leaves.
172
                                $matches = $this->seek([$child], $rule,
173
                                  $options);
174
                                foreach ($matches as $match) {
175
                                    $return[] = $match;
176
                                }
177
                            }
178
                        } else {
179
                            // we still want to check its children
180
                            $children[] = $child;
181
                        }
182
                    }
183
                }
184
 
185
                $child = $this->getNextChild($node, $child);
186
            }
187
 
188
            if ((!isset($options['checkGrandChildren'])
189
                || $options['checkGrandChildren'])
190
              && count($children) > 0
191
            ) {
192
                // we have children that failed but are not leaves.
193
                $matches = $this->seek($children, $rule, $options);
194
                foreach ($matches as $match) {
195
                    $return[] = $match;
196
                }
197
            }
198
        }
199
 
200
        return $return;
201
    }
202
 
203
    /**
204
     * Attempts to match the given arguments with the given operator.
205
     * @param string $operator
206
     * @param string $pattern
207
     * @param string $value
208
     * @return bool
209
     */
210
    protected function match(
211
      string $operator,
212
      string $pattern,
213
      string $value
214
    ): bool {
215
        $value = strtolower($value);
216
        $pattern = strtolower($pattern);
217
        switch ($operator) {
218
            case '=':
219
                return $value === $pattern;
220
            case '!=':
221
                return $value !== $pattern;
222
            case '^=':
223
                return preg_match('/^' . preg_quote($pattern, '/') . '/',
224
                    $value) == 1;
225
            case '$=':
226
                return preg_match('/' . preg_quote($pattern, '/') . '$/',
227
                    $value) == 1;
228
            case '*=':
229
                if ($pattern[0] == '/') {
230
                    return preg_match($pattern, $value) == 1;
231
                }
232
 
233
                return preg_match("/" . $pattern . "/i", $value) == 1;
234
        }
235
 
236
        return false;
237
    }
238
 
239
    /**
240
     * Attempts to figure out what the alteration will be for
241
     * the next element.
242
     * @param array $rule
243
     * @return array
244
     */
245
    protected function alterNext(array $rule): array
246
    {
247
        $options = [];
248
        if ($rule['tag'] == '>') {
249
            $options['checkGrandChildren'] = false;
250
        }
251
 
252
        return $options;
253
    }
254
 
255
    /**
256
     * Flattens the option array.
257
     * @param array $optionsArray
258
     * @return array
259
     */
260
    protected function flattenOptions(array $optionsArray)
261
    {
262
        $options = [];
263
        foreach ($optionsArray as $optionArray) {
264
            foreach ($optionArray as $key => $option) {
265
                $options[$key] = $option;
266
            }
267
        }
268
 
269
        return $options;
270
    }
271
 
272
    /**
273
     * Returns the next child or null if no more children.
274
     * @param AbstractNode $node
275
     * @param AbstractNode $currentChild
276
     * @return AbstractNode|null
277
     */
278
    protected function getNextChild(
279
      AbstractNode $node,
280
      AbstractNode $currentChild
281
    ) {
282
        try {
283
            $child = null;
284
            if ($node instanceof InnerNode) {
285
                // get next child
286
                $child = $node->nextChild($currentChild->id());
287
            }
288
        } catch (ChildNotFoundException $e) {
289
            // no more children
290
            unset($e);
291
            $child = null;
292
        }
293
 
294
        return $child;
295
    }
296
 
297
    /**
298
     * Checks tag condition from rules against node.
299
     * @param array        $rule
300
     * @param AbstractNode $node
301
     * @return bool
302
     */
303
    protected function checkTag(array $rule, AbstractNode $node): bool
304
    {
305
        if (!empty($rule['tag']) && $rule['tag'] != $node->getTag()->name()
306
          && $rule['tag'] != '*'
307
        ) {
308
            return false;
309
        }
310
 
311
        return true;
312
    }
313
 
314
    /**
315
     * Checks key condition from rules against node.
316
     * @param array        $rule
317
     * @param AbstractNode $node
318
     * @return bool
319
     */
320
    protected function checkKey(array $rule, AbstractNode $node): bool
321
    {
322
        if (!is_array($rule['key'])) {
323
            if ($rule['noKey']) {
324
                if (!is_null($node->getAttribute($rule['key']))) {
325
                    return false;
326
                }
327
            } else {
328
                if ($rule['key'] != 'plaintext'
329
                  && !$node->hasAttribute($rule['key'])
330
                ) {
331
                    return false;
332
                }
333
            }
334
        } else {
335
            if ($rule['noKey']) {
336
                foreach ($rule['key'] as $key) {
337
                    if (!is_null($node->getAttribute($key))) {
338
                        return false;
339
                    }
340
                }
341
            } else {
342
                foreach ($rule['key'] as $key) {
343
                    if ($key != 'plaintext'
344
                      && !$node->hasAttribute($key)
345
                    ) {
346
                        return false;
347
                    }
348
                }
349
            }
350
        }
351
 
352
        return true;
353
    }
354
 
355
    /**
356
     * Checks comparison condition from rules against node.
357
     * @param array        $rule
358
     * @param AbstractNode $node
359
     * @return bool
360
     */
361
    public function checkComparison(array $rule, AbstractNode $node): bool
362
    {
363
        if ($rule['key'] == 'plaintext') {
364
            // plaintext search
365
            $nodeValue = $node->text();
366
            $result = $this->checkNodeValue($nodeValue, $rule, $node);
367
        } else {
368
            // normal search
369
            if (!is_array($rule['key'])) {
370
                $nodeValue = $node->getAttribute($rule['key']);
371
                $result = $this->checkNodeValue($nodeValue, $rule, $node);
372
            } else {
373
                $result = true;
374
                foreach ($rule['key'] as $index => $key) {
375
                    $nodeValue = $node->getAttribute($key);
376
                    $result = $result &&
377
                        $this->checkNodeValue($nodeValue, $rule, $node, $index);
378
                }
379
            }
380
        }
381
 
382
        return $result;
383
    }
384
 
385
    /**
386
     * @param string|null  $nodeValue
387
     * @param array        $rule
388
     * @param AbstractNode $node
389
     * @param int|null     $index
390
     * @return bool
391
     */
392
    private function checkNodeValue(
393
        ?string $nodeValue,
394
        array $rule,
395
        AbstractNode $node,
396
        ?int $index = null
397
    ) : bool {
398
        $check = false;
399
        if (
400
            array_key_exists('value', $rule) && !is_array($rule['value']) &&
401
            !is_null($nodeValue) &&
402
            array_key_exists('operator', $rule) && is_string($rule['operator']) &&
403
            array_key_exists('value', $rule) && is_string($rule['value'])
404
        ) {
405
            $check = $this->match($rule['operator'], $rule['value'], $nodeValue);
406
        }
407
 
408
        // handle multiple classes
409
        $key = $rule['key'];
410
        if (
411
            !$check &&
412
            $key == 'class' &&
413
            array_key_exists('value', $rule) && is_array($rule['value'])
414
        ) {
415
            $nodeClasses = explode(' ', $node->getAttribute('class') ?? '');
416
            foreach ($rule['value'] as $value) {
417
                foreach ($nodeClasses as $class) {
418
                    if (
419
                        !empty($class) &&
420
                        array_key_exists('operator', $rule) && is_string($rule['operator'])
421
                    ) {
422
                        $check = $this->match($rule['operator'], $value, $class);
423
                    }
424
                    if ($check) {
425
                        break;
426
                    }
427
                }
428
                if (!$check) {
429
                    break;
430
                }
431
            }
432
        } elseif (
433
            !$check &&
434
            is_array($key) &&
435
            !is_null($nodeValue) &&
436
            array_key_exists('operator', $rule) && is_string($rule['operator']) &&
437
            array_key_exists('value', $rule) && is_string($rule['value'][$index])
438
        ) {
439
            $check = $this->match($rule['operator'], $rule['value'][$index], $nodeValue);
440
        }
441
 
442
        return $check;
443
    }
444
}