Debian Codegraph @

vendor/mck89/peast/lib/Peast/Selector/Node/Part/PseudoIndex.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\Part;
11
12 use Peast\Syntax\Node\Node;
13 use Peast\Syntax\Utils;
14
15 /**
16 * Selector part index pseudo class
17 *
18 * @author Marco Marchiò <[email protected]>
19 */
20 class PseudoIndex extends Pseudo
21 {
22 /**
23 * Priority
24 *
25 * @var int
26 */
27 protected $priority = 2;
28
29 /**
30 * Step
31 *
32 * @var int
33 */
34 protected $step = 0;
35
36 /**
37 * Offset
38 *
39 * @var int
40 */
41 protected $offset = 0;
42
43 /**
44 * Sets the step
45 *
46 * @param int $step Step
47 *
48 * @return $this
49 */
50 public function setStep($step)
51 {
52 $this->step = $step;
53 return $this;
54 }
55
56 /**
57 * Sets the offset
58 *
59 * @param int $offset Offset
60 *
61 * @return $this
62 */
63 public function setOffset($offset)
64 {
65 $this->offset = $offset;
66 return $this;
67 }
68
69 /**
70 * Returns true if the selector part matches the given node,
71 * false otherwise
72 *
73 * @param Node $node Node
74 * @param Node $parent Parent node
75 *
76 * @return bool
77 */
78 public function check(Node $node, $parent = null)
79 {
80 $props = Utils::getExpandedNodeProperties($parent);
81 $count = count($props);
82 $reverse = $this->name === "nth-last-child";
83 if ($reverse) {
84 $start = $count - 1 - ($this->offset - 1);
85 $step = $this->step * -1;
86 if ($step > 0) {
87 $reverse = false;
88 }
89 } else {
90 $start = $this->offset - 1;
91 $step = $this->step;
92 if ($step < 0) {
93 $reverse = true;
94 }
95 }
96 //Step 0 will cause an infinite loop, so it must be set to the
97 //number of props so that it will execute only one iteration
98 if (!$step) {
99 $step = $reverse ? -$count : $count;
100 }
101 for ($i = $start; ($reverse && $i >= 0) || (!$reverse && $i < $count); $i += $step) {
102 if (isset($props[$i]) && $props[$i] === $node) {
103 return true;
104 }
105 }
106 return false;
107 }
108 }