• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

MyIntervals / PHP-CSS-Parser / 15453215599

04 Jun 2025 09:32PM UTC coverage: 57.635% (+0.3%) from 57.327%
15453215599

Pull #1270

github

web-flow
Merge 459e4033e into afdca11ed
Pull Request #1270: [BUGFIX] `AddRule` before sibling with different property name

15 of 15 new or added lines in 1 file covered. (100.0%)

5 existing lines in 1 file now uncovered.

1038 of 1801 relevant lines covered (57.63%)

11.33 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.92
/src/RuleSet/RuleSet.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Sabberworm\CSS\RuleSet;
6

7
use Sabberworm\CSS\Comment\CommentContainer;
8
use Sabberworm\CSS\CSSElement;
9
use Sabberworm\CSS\CSSList\CSSListItem;
10
use Sabberworm\CSS\OutputFormat;
11
use Sabberworm\CSS\Parsing\ParserState;
12
use Sabberworm\CSS\Parsing\UnexpectedEOFException;
13
use Sabberworm\CSS\Parsing\UnexpectedTokenException;
14
use Sabberworm\CSS\Position\Position;
15
use Sabberworm\CSS\Position\Positionable;
16
use Sabberworm\CSS\Rule\Rule;
17

18
/**
19
 * This class is a container for individual 'Rule's.
20
 *
21
 * The most common form of a rule set is one constrained by a selector, i.e., a `DeclarationBlock`.
22
 * However, unknown `AtRule`s (like `@font-face`) are rule sets as well.
23
 *
24
 * If you want to manipulate a `RuleSet`, use the methods `addRule(Rule $rule)`, `getRules()` and `removeRule($rule)`
25
 * (which accepts either a `Rule` or a rule name; optionally suffixed by a dash to remove all related rules).
26
 *
27
 * Note that `CSSListItem` extends both `Commentable` and `Renderable`,
28
 * so those interfaces must also be implemented by concrete subclasses.
29
 */
30
abstract class RuleSet implements CSSElement, CSSListItem, Positionable, RuleContainer
31
{
32
    use CommentContainer;
33
    use Position;
34

35
    /**
36
     * the rules in this rule set, using the property name as the key,
37
     * with potentially multiple rules per property name.
38
     *
39
     * @var array<string, array<int<0, max>, Rule>>
40
     */
41
    private $rules = [];
42

43
    /**
44
     * @param int<0, max> $lineNumber
45
     */
46
    public function __construct(int $lineNumber = 0)
132✔
47
    {
48
        $this->setPosition($lineNumber);
132✔
49
    }
132✔
50

51
    /**
52
     * @throws UnexpectedTokenException
53
     * @throws UnexpectedEOFException
54
     *
55
     * @internal since V8.8.0
56
     */
57
    public static function parseRuleSet(ParserState $parserState, RuleSet $ruleSet): void
6✔
58
    {
59
        while ($parserState->comes(';')) {
6✔
60
            $parserState->consume(';');
×
61
        }
62
        while (true) {
6✔
63
            $commentsBeforeRule = $parserState->consumeWhiteSpace();
6✔
64
            if ($parserState->comes('}')) {
6✔
65
                break;
6✔
66
            }
67
            $rule = null;
6✔
68
            if ($parserState->getSettings()->usesLenientParsing()) {
6✔
69
                try {
70
                    $rule = Rule::parse($parserState, $commentsBeforeRule);
4✔
71
                } catch (UnexpectedTokenException $e) {
×
72
                    try {
73
                        $consumedText = $parserState->consumeUntil(["\n", ';', '}'], true);
×
74
                        // We need to “unfind” the matches to the end of the ruleSet as this will be matched later
75
                        if ($parserState->streql(\substr($consumedText, -1), '}')) {
×
76
                            $parserState->backtrack(1);
×
77
                        } else {
78
                            while ($parserState->comes(';')) {
×
79
                                $parserState->consume(';');
×
80
                            }
81
                        }
82
                    } catch (UnexpectedTokenException $e) {
×
83
                        // We’ve reached the end of the document. Just close the RuleSet.
84
                        return;
4✔
85
                    }
86
                }
87
            } else {
88
                $rule = Rule::parse($parserState, $commentsBeforeRule);
2✔
89
            }
90
            if ($rule instanceof Rule) {
6✔
91
                $ruleSet->addRule($rule);
6✔
92
            }
93
        }
94
        $parserState->consume('}');
6✔
95
    }
6✔
96

97
    public function addRule(Rule $ruleToAdd, ?Rule $sibling = null): void
127✔
98
    {
99
        $propertyName = $ruleToAdd->getRule();
127✔
100
        if (!isset($this->rules[$propertyName])) {
127✔
101
            $this->rules[$propertyName] = [];
127✔
102
        }
103

104
        $position = \count($this->rules[$propertyName]);
127✔
105

106
        if ($sibling !== null) {
127✔
107
            $siblingIsInSet = false;
58✔
108
            $siblingPosition = \array_search($sibling, $this->rules[$propertyName], true);
58✔
109
            if ($siblingPosition !== false) {
58✔
110
                $siblingIsInSet = true;
16✔
111
                $position = $siblingPosition;
16✔
112
            } elseif ($siblingIsInSet = $this->hasRule($sibling)) {
42✔
113
                // Maintain ordering within `$this->rules[$propertyName]`
114
                // by inserting before first `Rule` with a same-or-later position than the sibling.
115
                foreach ($this->rules[$propertyName] as $index => $rule) {
30✔
116
                    if (self::comparePositionable($rule, $sibling) >= 0) {
6✔
117
                        $position = $index;
3✔
118
                        break;
3✔
119
                    }
120
                }
121
            }
122
            if ($siblingIsInSet) {
58✔
123
                // Increment column number of all existing rules on same line, starting at sibling
124
                $siblingLineNumber = $sibling->getLineNumber();
46✔
125
                $siblingColumnNumber = $sibling->getColumnNumber();
46✔
126
                foreach ($this->rules as $rulesForAProperty) {
46✔
127
                    foreach ($rulesForAProperty as $rule) {
46✔
128
                        if (
129
                            $rule->getLineNumber() === $siblingLineNumber &&
46✔
130
                            $rule->getColumnNumber() >= $siblingColumnNumber
46✔
131
                        ) {
132
                            $rule->setPosition($siblingLineNumber, $rule->getColumnNumber() + 1);
46✔
133
                        }
134
                    }
135
                }
136
                $ruleToAdd->setPosition($siblingLineNumber, $siblingColumnNumber);
46✔
137
            }
138
        }
139

140
        if ($ruleToAdd->getLineNumber() === null) {
127✔
141
            //this node is added manually, give it the next best line
142
            $columnNumber = $ruleToAdd->getColumnNumber() ?? 0;
117✔
143
            $rules = $this->getRules();
117✔
144
            $rulesCount = \count($rules);
117✔
145
            if ($rulesCount > 0) {
117✔
146
                $last = $rules[$rulesCount - 1];
88✔
147
                $ruleToAdd->setPosition($last->getLineNo() + 1, $columnNumber);
88✔
148
            } else {
149
                $ruleToAdd->setPosition(1, $columnNumber);
117✔
150
            }
151
        } elseif ($ruleToAdd->getColumnNumber() === null) {
75✔
152
            $ruleToAdd->setPosition($ruleToAdd->getLineNumber(), 0);
12✔
153
        }
154

155
        \array_splice($this->rules[$propertyName], $position, 0, [$ruleToAdd]);
127✔
156
    }
127✔
157

158
    /**
159
     * Returns all rules matching the given rule name
160
     *
161
     * @example $ruleSet->getRules('font') // returns array(0 => $rule, …) or array().
162
     *
163
     * @example $ruleSet->getRules('font-')
164
     *          //returns an array of all rules either beginning with font- or matching font.
165
     *
166
     * @param string|null $searchPattern
167
     *        Pattern to search for. If null, returns all rules.
168
     *        If the pattern ends with a dash, all rules starting with the pattern are returned
169
     *        as well as one matching the pattern with the dash excluded.
170
     *
171
     * @return array<int<0, max>, Rule>
172
     */
173
    public function getRules(?string $searchPattern = null): array
129✔
174
    {
175
        $result = [];
129✔
176
        foreach ($this->rules as $propertyName => $rules) {
129✔
177
            // Either no search rule is given or the search rule matches the found rule exactly
178
            // or the search rule ends in “-” and the found rule starts with the search rule.
179
            if (
180
                $searchPattern === null || $propertyName === $searchPattern
127✔
181
                || (
182
                    \strrpos($searchPattern, '-') === \strlen($searchPattern) - \strlen('-')
1✔
183
                    && (\strpos($propertyName, $searchPattern) === 0
1✔
184
                        || $propertyName === \substr($searchPattern, 0, -1))
127✔
185
                )
186
            ) {
187
                $result = \array_merge($result, $rules);
127✔
188
            }
189
        }
190
        \usort($result, [self::class, 'comparePositionable']);
129✔
191

192
        return $result;
129✔
193
    }
194

195
    /**
196
     * Overrides all the rules of this set.
197
     *
198
     * @param array<Rule> $rules The rules to override with.
199
     */
200
    public function setRules(array $rules): void
124✔
201
    {
202
        $this->rules = [];
124✔
203
        foreach ($rules as $rule) {
124✔
204
            $this->addRule($rule);
107✔
205
        }
206
    }
124✔
207

208
    /**
209
     * Returns all rules matching the given pattern and returns them in an associative array with the rule’s name
210
     * as keys. This method exists mainly for backwards-compatibility and is really only partially useful.
211
     *
212
     * Note: This method loses some information: Calling this (with an argument of `background-`) on a declaration block
213
     * like `{ background-color: green; background-color; rgba(0, 127, 0, 0.7); }` will only yield an associative array
214
     * containing the rgba-valued rule while `getRules()` would yield an indexed array containing both.
215
     *
216
     * @param string|null $searchPattern
217
     *        Pattern to search for. If null, returns all rules. If the pattern ends with a dash,
218
     *        all rules starting with the pattern are returned as well as one matching the pattern with the dash
219
     *        excluded.
220
     *
221
     * @return array<string, Rule>
222
     */
223
    public function getRulesAssoc(?string $searchPattern = null): array
14✔
224
    {
225
        /** @var array<string, Rule> $result */
226
        $result = [];
14✔
227
        foreach ($this->getRules($searchPattern) as $rule) {
14✔
228
            $result[$rule->getRule()] = $rule;
8✔
229
        }
230

231
        return $result;
14✔
232
    }
233

234
    /**
235
     * Removes a `Rule` from this `RuleSet` by identity.
236
     */
UNCOV
237
    public function removeRule(Rule $ruleToRemove): void
×
238
    {
UNCOV
239
        $nameOfPropertyToRemove = $ruleToRemove->getRule();
×
240
        if (!isset($this->rules[$nameOfPropertyToRemove])) {
×
UNCOV
241
            return;
×
242
        }
243
        foreach ($this->rules[$nameOfPropertyToRemove] as $key => $rule) {
×
244
            if ($rule === $ruleToRemove) {
×
UNCOV
245
                unset($this->rules[$nameOfPropertyToRemove][$key]);
×
246
            }
247
        }
248
    }
×
249

250
    /**
251
     * Removes rules by property name or search pattern.
252
     *
253
     * @param string $searchPattern
254
     *        pattern to remove.
255
     *        If the pattern ends in a dash,
256
     *        all rules starting with the pattern are removed as well as one matching the pattern with the dash
257
     *        excluded.
258
     */
259
    public function removeMatchingRules(string $searchPattern): void
14✔
260
    {
261
        foreach ($this->rules as $propertyName => $rules) {
14✔
262
            // Either the search rule matches the found rule exactly
263
            // or the search rule ends in “-” and the found rule starts with the search rule or equals it
264
            // (without the trailing dash).
265
            if (
266
                $propertyName === $searchPattern
13✔
267
                || (\strrpos($searchPattern, '-') === \strlen($searchPattern) - \strlen('-')
11✔
268
                    && (\strpos($propertyName, $searchPattern) === 0
6✔
269
                        || $propertyName === \substr($searchPattern, 0, -1)))
13✔
270
            ) {
271
                unset($this->rules[$propertyName]);
12✔
272
            }
273
        }
274
    }
14✔
275

276
    public function removeAllRules(): void
4✔
277
    {
278
        $this->rules = [];
4✔
279
    }
4✔
280

281
    protected function renderRules(OutputFormat $outputFormat): string
5✔
282
    {
283
        $result = '';
5✔
284
        $isFirst = true;
5✔
285
        $nextLevelFormat = $outputFormat->nextLevel();
5✔
286
        foreach ($this->getRules() as $rule) {
5✔
287
            $nextLevelFormatter = $nextLevelFormat->getFormatter();
5✔
288
            $renderedRule = $nextLevelFormatter->safely(static function () use ($rule, $nextLevelFormat): string {
289
                return $rule->render($nextLevelFormat);
5✔
290
            });
5✔
291
            if ($renderedRule === null) {
5✔
UNCOV
292
                continue;
×
293
            }
294
            if ($isFirst) {
5✔
295
                $isFirst = false;
5✔
296
                $result .= $nextLevelFormatter->spaceBeforeRules();
5✔
297
            } else {
298
                $result .= $nextLevelFormatter->spaceBetweenRules();
1✔
299
            }
300
            $result .= $renderedRule;
5✔
301
        }
302

303
        $formatter = $outputFormat->getFormatter();
5✔
304
        if (!$isFirst) {
5✔
305
            // Had some output
306
            $result .= $formatter->spaceAfterRules();
5✔
307
        }
308

309
        return $formatter->removeLastSemicolon($result);
5✔
310
    }
311

312
    /**
313
     * @return int negative if `$first` is before `$second`; zero if they have the same position; positive otherwise
314
     */
315
    private static function comparePositionable(Positionable $first, Positionable $second): int
90✔
316
    {
317
        if ($first->getLineNo() === $second->getLineNo()) {
90✔
318
            return $first->getColNo() - $second->getColNo();
17✔
319
        }
320
        return $first->getLineNo() - $second->getLineNo();
86✔
321
    }
322

323
    private function hasRule(Rule $rule): bool
42✔
324
    {
325
        foreach ($this->rules as $rulesForAProperty) {
42✔
326
            if (\in_array($rule, $rulesForAProperty, true)) {
42✔
327
                return true;
30✔
328
            }
329
        }
330

331
        return false;
12✔
332
    }
333
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc