Debian Codegraph @

vendor/mck89/peast/lib/Peast/Selector/Parser.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;
11
12 /**
13 * Selector parser class
14 *
15 * @author Marco Marchiò <[email protected]>
16 */
17 class Parser
18 {
19 /**
20 * Selector string
21 *
22 * @var string
23 */
24 protected $selector;
25
26 /**
27 * Current parser index
28 *
29 * @var int
30 */
31 protected $index = 0;
32
33 /**
34 * Selector length
35 *
36 * @var int
37 */
38 protected $length;
39
40 /**
41 * Whitespaces
42 *
43 * @var array
44 */
45 protected $whitespaces = array(" ", "\t", "\n", "\r", "\f");
46
47 /**
48 * Combinators
49 *
50 * @var array
51 */
52 protected $combinators = array(">", "+", "~");
53
54 /**
55 * Attribute selector operator characters
56 *
57 * @var array
58 */
59 protected $attrOperatorChars = array("=", "<", ">", "^", "$", "*");
60
61 /**
62 * Attribute selector operators
63 *
64 * @var array
65 */
66 protected $attrOperators = array("=", "<", ">", "<=", ">=", "^=", "$=", "*=");
67
68 /**
69 * Valid pseudo selectors. The value indicates the argument type:
70 * - 0: no arguments
71 * - 1: index formula (An+B syntax)
72 * - 2: selector
73 * @var array
74 */
75 protected $validPseudo = array(
76 "pattern" => 0, "statement" => 0, "expression" => 0, "declaration" => 0,
77 "first-child" => 0, "last-child" => 0,
78 "nth-child" => 1, "nth-last-child" => 1,
79 "has" => 2, "is" => 2, "not" => 2
80 );
81
82 /**
83 * Class constructor
84 *
85 * @param string $selector Selector string
86 * @param array $options Options array. See Query class
87 * documentation for available options
88 */
89 public function __construct($selector, $options = array())
90 {
91 $encoding = isset($options["encoding"]) ? $options["encoding"] : null;
92 if ($encoding && !preg_match("/UTF-?8/i", $encoding)) {
93 $selector = mb_convert_encoding($selector, "UTF-8", $encoding);
94 }
95 $this->selector = $selector;
96 $this->length = strlen($selector);
97 }
98
99 /**
100 * Starts the parsing and returns the parsed selector
101 *
102 * @param bool $filter True if the selector must be used for a filter
103 *
104 * @return Node\Selector
105 *
106 * @throws Exception
107 */
108 public function parse($filter = false)
109 {
110 $selector = $this->parseSelector($filter);
111 //Throw an exception if the end has not been reached
112 if (($char = $this->getChar()) !== null) {
113 throw new Exception("Invalid syntax '$char'");
114 }
115 return $selector;
116 }
117
118 /**
119 * Parses a selector
120 *
121 * @param bool $filter True if the selector must be used for a filter
122 *
123 * @return Node\Selector
124 *
125 * @throws Exception
126 */
127 public function parseSelector($filter = false)
128 {
129 $selector = new Node\Selector;
130 do {
131 $first = true;
132 $group = new Node\Group;
133 while (true) {
134 $combinator = $this->consumeCombinator();
135 if (!$first && !$combinator) {
136 break;
137 }
138 $parts = $this->parseSelectorParts();
139 if (!count($parts)) {
140 throw new Exception("Missing selector after combinator");
141 }
142 $first = false;
143 $selCombinator = new Node\Combinator;
144 $selCombinator->setOperator(
145 $combinator ?: ($filter ? null : " ")
146 );
147 foreach ($parts as $part) {
148 $selCombinator->addPart($part);
149 }
150 $group->addCombinator($selCombinator);
151 }
152 $selector->addGroup($group);
153 $this->consumeWhitespaces();
154 } while ($this->consume(","));
155 return $selector;
156 }
157
158 /**
159 * Parses a set of selector pats
160 *
161 * @return array
162 *
163 * @throws Exception
164 */
165 protected function parseSelectorParts()
166 {
167 $parts = array();
168 while (true) {
169 if (
170 ($part = $this->parseSelectorPartType()) ||
171 ($part = $this->parseSelectorPartAttribute()) ||
172 ($part = $this->parseSelectorPartPseudo())
173 ) {
174 $parts[] = $part;
175 } else {
176 break;
177 }
178 }
179 return $parts;
180 }
181
182 /**
183 * Parses a type selector part
184 *
185 * @return Node\Part\Type|null
186 */
187 protected function parseSelectorPartType()
188 {
189 $type = $this->consumeWord();
190 if ($type) {
191 $part = new Node\Part\Type;
192 $part->setType($type);
193 return $part;
194 }
195 return null;
196 }
197
198 /**
199 * Parses an attribute selector part
200 *
201 * @return Node\Part\Attribute|null
202 *
203 * @throws Exception
204 */
205 protected function parseSelectorPartAttribute()
206 {
207 if (!$this->consume("[")) {
208 return null;
209 }
210 $this->consumeWhitespaces();
211 $part = new Node\Part\Attribute;
212 if (!($name = $this->consumeWord())) {
213 throw new Exception("Missing attribute name");
214 }
215 $part->addName($name);
216 while ($this->consume(".")) {
217 if (!($name = $this->consumeWord())) {
218 throw new Exception("Missing attribute name after dot");
219 }
220 $part->addName($name);
221 }
222 $this->consumeWhitespaces();
223 $operator = $this->consumeAny($this->attrOperatorChars);
224 if ($operator) {
225 if (!in_array($operator, $this->attrOperators)) {
226 throw new Exception("Invalid attribute operator '$operator'");
227 }
228 $part->setOperator($operator);
229 $this->consumeWhitespaces();
230 if (!($value = $this->parseLiteral())) {
231 throw new Exception("Missing attribute value");
232 }
233 $part->setValue($value[0]);
234 if ($value[1]) {
235 if ($operator != "=") {
236 throw new Exception(
237 "Only '=' operator is valid for attribute regex match"
238 );
239 }
240 $part->setRegex(true);
241 }
242 $this->consumeWhitespaces();
243 if ($this->consume("i")) {
244 if (!is_string($value[0]) || $value[1]) {
245 throw new Exception(
246 "Case insensitive flag can be used only for string values"
247 );
248 }
249 $part->setCaseInsensitive(true);
250 $this->consumeWhitespaces();
251 }
252 }
253 if (!$this->consume("]")) {
254 throw new Exception("Unterminated attribute selector");
255 }
256 return $part;
257 }
258
259 /**
260 * Parses a pseudo selector part
261 *
262 * @return Node\Part\Pseudo|null
263 *
264 * @throws Exception
265 */
266 protected function parseSelectorPartPseudo()
267 {
268 if (!$this->consume(":")) {
269 return null;
270 }
271 $name = $this->consumeWord("-");
272 if (!isset($this->validPseudo[$name])) {
273 throw new Exception("Unsupported pseudo selector '$name'");
274 }
275 $argsType = $this->validPseudo[$name];
276 $error = false;
277 if ($argsType === 1) {
278 $part = new Node\Part\PseudoIndex;
279 if (!$this->consume("(")) {
280 $error = true;
281 }
282 if (!$error) {
283 $this->consumeWhitespaces();
284 if ($indices = $this->consumeRegex("-?\d*n(?:\+\d+)?|\d+")) {
285 $indices = explode("n", $indices);
286 if (count($indices) === 1) {
287 $part->setOffset((int) $indices[0]);
288 } else {
289 switch ($indices[0]) {
290 case "":
291 $part->setStep(1);
292 break;
293 case "-":
294 $part->setStep(-1);
295 break;
296 default:
297 $part->setStep((int) $indices[0]);
298 break;
299 }
300 if ($indices[1] !== "") {
301 $part->setOffset((int) $indices[1]);
302 }
303 }
304 } elseif (
305 ($word = $this->consumeWord()) &&
306 ($word === "even" || $word === "odd")
307 ) {
308 $part->setStep(2);
309 if ($word === "odd") {
310 $part->setOffset(1);
311 }
312 } else {
313 $error = true;
314 }
315 $this->consumeWhitespaces();
316 if (!$error && !$this->consume(")")) {
317 $error = true;
318 }
319 }
320 } elseif ($argsType === 2) {
321 $part = new Node\Part\PseudoSelector;
322 if (
323 $this->consume("(") &&
324 ($selector = $this->parseSelector($name !== "has")) &&
325 $this->consume(")")
326 ) {
327 $part->setSelector($selector);
328 } else {
329 $error = true;
330 }
331 } else {
332 $part = new Node\Part\PseudoSimple;
333 }
334 if ($error) {
335 throw new Exception(
336 "Invalid argument for pseudo selector '$name'"
337 );
338 }
339 $part->setName($name);
340 return $part;
341 }
342
343 /**
344 * Parses a literal value
345 *
346 * @return array|null
347 *
348 * @throws Exception
349 */
350 protected function parseLiteral()
351 {
352 if (
353 ($literal = $this->parseLiteralBoolNull()) !== 0 ||
354 ($literal = $this->parseLiteralString()) !== null ||
355 ($literal = $this->parseLiteralNumber()) !== null
356 ) {
357 return array($literal, false);
358 } elseif ($literal = $this->parseLiteralRegex()) {
359 return array($literal, true);
360 }
361 return null;
362 }
363
364 /**
365 * Parses a literal boolean or null value
366 *
367 * @return int|bool|null
368 *
369 * @throws Exception
370 */
371 protected function parseLiteralBoolNull()
372 {
373 $word = $this->consumeWord();
374 if (!$word) {
375 return 0;
376 } elseif ($word === "true") {
377 return true;
378 } elseif ($word === "false") {
379 return false;
380 } elseif ($word === "null") {
381 return null;
382 }
383 throw new Exception("Invalid attribute value '$word'");
384 }
385
386 /**
387 * Parses a literal string
388 *
389 * @return string|null
390 *
391 * @throws Exception
392 */
393 protected function parseLiteralString()
394 {
395 if (!($quote = $this->consumeAny(array("'", '"'), true))) {
396 return null;
397 }
398 if (($str = $this->consumeUntil($quote)) === null) {
399 throw new Exception("Unterminated string in attribute value");
400 }
401 return $str;
402 }
403
404 /**
405 * Parses a literal number
406 *
407 * @return int|float|null
408 */
409 protected function parseLiteralNumber()
410 {
411 if (
412 $this->getChar() === "0" &&
413 ($val = $this->consumeRegex("0[xX][a-fA-F]+|0[bB][01]+|0[oO][0-7]+"))
414 ) {
415 $form = strtolower($val[1]);
416 $val = substr($val, 2);
417 if ($form === "x") {
418 return hexdec($val);
419 } elseif ($form === "o") {
420 return octdec($val);
421 }
422 return bindec($val);
423 }
424 $reg = "-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|-?\.\d+(?:[eE][+-]?\d+)?";
425 if (!($val = $this->consumeRegex($reg))) {
426 return null;
427 }
428 return (float) $val;
429 }
430
431 /**
432 * Parses a literal regex
433 *
434 * @return string|null
435 *
436 * @throws Exception
437 */
438 protected function parseLiteralRegex()
439 {
440 if (!($sep = $this->consume("/"))) {
441 return null;
442 }
443 if (($reg = $this->consumeUntil($sep, false, true)) === null) {
444 throw new Exception("Unterminated regex in attribute value");
445 }
446 $modifiers = $this->consumeWord();
447 return $sep . $reg . ($modifiers ?: "");
448 }
449
450 /**
451 * Consumes the given regex
452 *
453 * @param string $regex Regex to consume
454 *
455 * @return mixed|null
456 */
457 protected function consumeRegex($regex)
458 {
459 if ($this->getChar() === null) {
460 return null;
461 }
462 if (!preg_match("#^($regex)#", substr($this->selector, $this->index), $matches)) {
463 return null;
464 }
465 $this->index += strlen($matches[1]);
466 return $matches[1];
467 }
468
469 /**
470 * Consumes all the characters until the given one is reached
471 *
472 * @param string $stop Stop character
473 * @param bool $removeEscapes If false escape characters won't be removed
474 * @param false $includeStop If true stop character will be returned
475 *
476 * @return string|null
477 */
478 protected function consumeUntil($stop, $removeEscapes = true, $includeStop = false)
479 {
480 $buffer = "";
481 $escaped = false;
482 while (($char = $this->getChar()) !== null) {
483 $this->index += 1;
484 if (!$escaped) {
485 if ($char === "\\") {
486 $escaped = true;
487 if (!$removeEscapes) {
488 $buffer .= $char;
489 }
490 continue;
491 } elseif ($char === $stop) {
492 if ($includeStop) {
493 $buffer .= $char;
494 }
495 return $buffer;
496 }
497 }
498 $buffer .= $char;
499 $escaped = false;
500 }
501 return null;
502 }
503
504 /**
505 * Consumes a word composed by characters a-z
506 *
507 * @param null|string $extraChar Extra character to match
508 *
509 * @return string
510 */
511 protected function consumeWord($extraChar = null)
512 {
513 $buffer = "";
514 while ($char = $this->getChar()) {
515 if (
516 ($char >= "a" && $char <= "z") ||
517 ($char >= "A" && $char <= "Z") ||
518 ($extraChar !== null && $char === $extraChar)
519 ) {
520 $buffer .= $char;
521 $this->index += 1;
522 } else {
523 break;
524 }
525 }
526 return $buffer;
527 }
528
529 /**
530 * Consumes a combinator
531 *
532 * @return string|null
533 */
534 protected function consumeCombinator()
535 {
536 //Initial ws can be trimmed if followed by another combinator
537 $ws = $this->consumeWhitespaces();
538 if ($combinator = $this->consumeAny($this->combinators, true)) {
539 $this->consumeWhitespaces();
540 } elseif ($ws) {
541 //If there's no other combinators use the space
542 $combinator = " ";
543 } else {
544 $combinator = null;
545 }
546 return $combinator;
547 }
548
549 /**
550 * Consumes as much whitespaces as possible
551 *
552 * @return string
553 */
554 protected function consumeWhitespaces()
555 {
556 return $this->consumeAny($this->whitespaces);
557 }
558
559 /**
560 * Consumes the given characters
561 *
562 * @param array $chars Characters to consume
563 * @param false $stopAtFirst If true only the first matching character
564 * is consumed
565 *
566 * @return string
567 */
568 protected function consumeAny($chars, $stopAtFirst = false)
569 {
570 $buffer = "";
571 while (($char = $this->getChar()) !== null) {
572 if (in_array($char, $chars)) {
573 $buffer .= $char;
574 $this->index++;
575 if ($stopAtFirst) {
576 break;
577 }
578 } else {
579 break;
580 }
581 }
582 return $buffer;
583 }
584
585 /**
586 * Consumes the current character if it is equal to the
587 * given one
588 *
589 * @param string $char Character to compare
590 *
591 * @return string|null
592 */
593 protected function consume($char)
594 {
595 if ($this->getChar() === $char) {
596 $this->index++;
597 return $char;
598 }
599 return null;
600 }
601
602 /**
603 * Returns the current character or null if the end
604 * have been reached
605 *
606 * @return string|null
607 */
608 protected function getChar()
609 {
610 if ($this->index < $this->length) {
611 return $this->selector[$this->index];
612 }
613 return null;
614 }
615 }