Debian Codegraph @

vendor/mck89/peast/lib/Peast/Selector/Node/Combinator.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\Selector\Node;
11
12 use Peast\Selector\Matches;
13 use Peast\Syntax\Utils;
14 use Peast\Traverser;
15
16 /**
17 * Selector combinator class
18 *
19 * @author Marco Marchiò <[email protected]>
20 */
21 class Combinator
22 {
23 /**
24 * Operator
25 *
26 * @var string|null
27 */
28 protected $operator;
29
30 /**
31 * Selector parts
32 *
33 * @var Part\Part[]
34 */
35 protected $parts = array();
36
37 /**
38 * Sets the operator
39 *
40 * @param string $operator Operator
41 * @return $this
42 */
43 public function setOperator($operator)
44 {
45 $this->operator = $operator;
46 return $this;
47 }
48
49 /**
50 * Adds a new selector part
51 *
52 * @param Part\Part $part Part
53 * @return $this
54 */
55 public function addPart(Part\Part $part)
56 {
57 $this->parts[] = $part;
58 return $this;
59 }
60
61 /**
62 * Executes the current group on the given matches
63 *
64 * @param Matches $matches Matches
65 */
66 public function exec(Matches $matches)
67 {
68 $parts = $this->parts;
69 //Sort the parts by priority to execute faster checks first
70 usort($parts, function ($p1, $p2) {
71 $pr1 = $p1->getPriority();
72 $pr2 = $p2->getPriority();
73 if ($pr1 === $pr2) {
74 return 0;
75 } elseif ($pr1 < $pr2) {
76 return -1;
77 } else {
78 return 1;
79 }
80 });
81 $filter = function ($node, $parent) use ($parts) {
82 foreach ($parts as $part) {
83 if (!$part->check($node, $parent)) {
84 return false;
85 }
86 }
87 return true;
88 };
89 switch ($this->operator) {
90 case " ":
91 case ">":
92 $children = $this->operator === ">";
93 $matches->map(function ($curNode) use ($filter, $children) {
94 $ret = array();
95 $curNode->traverse(
96 function ($node, $parent) use ($filter, $children, &$ret) {
97 if ($filter($node, $parent)) {
98 $ret[] = array($node, $parent);
99 }
100 if ($children) {
101 return Traverser::DONT_TRAVERSE_CHILD_NODES;
102 }
103 },
104 array(
105 "skipStartingNode" => true,
106 "passParentNode" => true
107 )
108 );
109 return $ret;
110 });
111 break;
112 case "~":
113 case "+":
114 $adjacent = $this->operator === "+";
115 $matches->map(function ($node, $parent) use ($filter, $adjacent) {
116 $ret = array();
117 $evaluate = false;
118 $props = $parent ? Utils::getExpandedNodeProperties($parent) : array();
119 foreach ($props as $propNode) {
120 if ($evaluate) {
121 if ($propNode && $filter($propNode, $parent)) {
122 $ret[] = array($propNode, $parent);
123 }
124 if ($adjacent) {
125 break;
126 }
127 } elseif ($propNode === $node) {
128 $evaluate = true;
129 }
130 }
131 return $ret;
132 });
133 break;
134 default:
135 $matches->filter($filter);
136 break;
137 }
138 }
139 }