-
-
Notifications
You must be signed in to change notification settings - Fork 469
/
Copy pathSelector.php
executable file
·110 lines (96 loc) · 3.05 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
<?php
declare(strict_types=1);
namespace PHPHtmlParser\Selector;
use PHPHtmlParser\Contracts\Selector\ParserInterface;
use PHPHtmlParser\Contracts\Selector\SeekerInterface;
use PHPHtmlParser\Contracts\Selector\SelectorInterface;
use PHPHtmlParser\Discovery\SeekerDiscovery;
use PHPHtmlParser\Discovery\SelectorParserDiscovery;
use PHPHtmlParser\Dom\Node\AbstractNode;
use PHPHtmlParser\Dom\Node\Collection;
use PHPHtmlParser\DTO\Selector\ParsedSelectorCollectionDTO;
use PHPHtmlParser\DTO\Selector\RuleDTO;
use PHPHtmlParser\Exceptions\ChildNotFoundException;
/**
* Class Selector.
*/
class Selector implements SelectorInterface
{
/**
* @var ParsedSelectorCollectionDTO
*/
private $ParsedSelectorCollectionDTO;
/**
* @var SeekerInterface
*/
private $seeker;
/**
* Constructs with the selector string.
*/
public function __construct(string $selector, ?ParserInterface $parser = null, ?SeekerInterface $seeker = null)
{
if ($parser == null) {
$parser = SelectorParserDiscovery::find();
}
if ($seeker == null) {
$seeker = SeekerDiscovery::find();
}
$this->ParsedSelectorCollectionDTO = $parser->parseSelectorString($selector);
$this->seeker = $seeker;
}
/**
* Returns the selectors that where found in __construct.
*/
public function getParsedSelectorCollectionDTO(): ParsedSelectorCollectionDTO
{
return $this->ParsedSelectorCollectionDTO;
}
/**
* Attempts to find the selectors starting from the given
* node object.
*
* @throws ChildNotFoundException
*/
public function find(AbstractNode $node): Collection
{
$results = new Collection();
foreach ($this->ParsedSelectorCollectionDTO->getParsedSelectorDTO() as $selector) {
$nodes = [$node];
if (\count($selector->getRules()) == 0) {
continue;
}
$options = [];
$lastRule = null;
foreach ($selector->getRules() as $rule) {
if ($rule->getTag() == '*' && $lastRule && ($lastRule->getTag() == '+' || $lastRule->getTag() == '~')) {
continue;
}
if ($rule->isAlterNext() && $rule->getTag() == '>') {
$options[] = $this->alterNext($rule);
continue;
}
$nodes = $this->seeker->seek($nodes, $rule, $options);
// clear the options
$options = [];
$lastRule = $rule;
}
// this is the final set of nodes
foreach ($nodes as $result) {
$results[] = $result;
}
}
return $results;
}
/**
* Attempts to figure out what the alteration will be for
* the next element.
*/
private function alterNext(RuleDTO $rule): array
{
$options = [];
if ($rule->getTag() == '>') {
$options['checkGrandChildren'] = false;
}
return $options;
}
}