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

MyIntervals / PHP-CSS-Parser / 21307416638

24 Jan 2026 02:11AM UTC coverage: 71.329% (+0.6%) from 70.738%
21307416638

Pull #1477

github

web-flow
Merge aae04485d into 21bb0eb9f
Pull Request #1477: [TASK] Have `comsumeWhiteSpace()` return the consumed

10 of 12 new or added lines in 4 files covered. (83.33%)

25 existing lines in 1 file now uncovered.

1433 of 2009 relevant lines covered (71.33%)

28.08 hits per line

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

77.78
/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`, so those interfaces must also be implemented.
28
 */
29
class RuleSet implements CSSElement, CSSListItem, Positionable, RuleContainer
30
{
31
    use CommentContainer;
32
    use Position;
33

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

42
    /**
43
     * @param int<1, max>|null $lineNumber
44
     */
45
    public function __construct(?int $lineNumber = null)
354✔
46
    {
47
        $this->setPosition($lineNumber);
354✔
48
    }
354✔
49

50
    /**
51
     * @throws UnexpectedTokenException
52
     * @throws UnexpectedEOFException
53
     *
54
     * @internal since V8.8.0
55
     */
56
    public static function parseRuleSet(ParserState $parserState, RuleSet $ruleSet): void
×
57
    {
58
        while ($parserState->comes(';')) {
×
59
            $parserState->consume(';');
×
60
        }
61
        while (true) {
×
NEW
62
            $commentsBeforeRule = [];
×
NEW
63
            $parserState->consumeWhiteSpace($commentsBeforeRule);
×
64
            if ($parserState->comes('}')) {
×
65
                break;
×
66
            }
67
            $rule = null;
×
68
            if ($parserState->getSettings()->usesLenientParsing()) {
×
69
                try {
70
                    $rule = Rule::parse($parserState, $commentsBeforeRule);
×
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;
×
85
                    }
86
                }
87
            } else {
88
                $rule = Rule::parse($parserState, $commentsBeforeRule);
×
89
            }
90
            if ($rule instanceof Rule) {
×
91
                $ruleSet->addRule($rule);
×
92
            }
93
        }
94
        $parserState->consume('}');
×
95
    }
×
96

97
    /**
98
     * @throws \UnexpectedValueException
99
     *         if the last `Rule` is needed as a basis for setting position, but does not have a valid position,
100
     *         which should never happen
101
     */
102
    public function addRule(Rule $ruleToAdd, ?Rule $sibling = null): void
333✔
103
    {
104
        $propertyName = $ruleToAdd->getRule();
333✔
105
        if (!isset($this->rules[$propertyName])) {
333✔
106
            $this->rules[$propertyName] = [];
333✔
107
        }
108

109
        $position = \count($this->rules[$propertyName]);
333✔
110

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

148
        if ($ruleToAdd->getLineNumber() === null) {
333✔
149
            //this node is added manually, give it the next best line
150
            $columnNumber = $ruleToAdd->getColumnNumber() ?? 0;
310✔
151
            $rules = $this->getRules();
310✔
152
            $rulesCount = \count($rules);
310✔
153
            if ($rulesCount > 0) {
310✔
154
                $last = $rules[$rulesCount - 1];
228✔
155
                $lastsLineNumber = $last->getLineNumber();
228✔
156
                if (!\is_int($lastsLineNumber)) {
228✔
157
                    throw new \UnexpectedValueException(
×
158
                        'A Rule without a line number was found during addRule',
×
159
                        1750718399
×
160
                    );
161
                }
162
                $ruleToAdd->setPosition($lastsLineNumber + 1, $columnNumber);
228✔
163
            } else {
164
                $ruleToAdd->setPosition(1, $columnNumber);
310✔
165
            }
166
        } elseif ($ruleToAdd->getColumnNumber() === null) {
113✔
167
            $ruleToAdd->setPosition($ruleToAdd->getLineNumber(), 0);
38✔
168
        }
169

170
        \array_splice($this->rules[$propertyName], $position, 0, [$ruleToAdd]);
333✔
171
    }
333✔
172

173
    /**
174
     * Returns all rules matching the given rule name
175
     *
176
     * @example $ruleSet->getRules('font') // returns array(0 => $rule, …) or array().
177
     *
178
     * @example $ruleSet->getRules('font-')
179
     *          //returns an array of all rules either beginning with font- or matching font.
180
     *
181
     * @param string|null $searchPattern
182
     *        Pattern to search for. If null, returns all rules.
183
     *        If the pattern ends with a dash, all rules starting with the pattern are returned
184
     *        as well as one matching the pattern with the dash excluded.
185
     *
186
     * @return array<int<0, max>, Rule>
187
     */
188
    public function getRules(?string $searchPattern = null): array
334✔
189
    {
190
        $result = [];
334✔
191
        foreach ($this->rules as $propertyName => $rules) {
334✔
192
            // Either no search rule is given or the search rule matches the found rule exactly
193
            // or the search rule ends in “-” and the found rule starts with the search rule.
194
            if (
195
                $searchPattern === null || $propertyName === $searchPattern
321✔
196
                || (
197
                    \strrpos($searchPattern, '-') === \strlen($searchPattern) - \strlen('-')
27✔
198
                    && (\strpos($propertyName, $searchPattern) === 0
13✔
199
                        || $propertyName === \substr($searchPattern, 0, -1))
321✔
200
                )
201
            ) {
202
                $result = \array_merge($result, $rules);
321✔
203
            }
204
        }
205
        \usort($result, [self::class, 'comparePositionable']);
334✔
206

207
        return $result;
334✔
208
    }
209

210
    /**
211
     * Overrides all the rules of this set.
212
     *
213
     * @param array<Rule> $rules The rules to override with.
214
     */
215
    public function setRules(array $rules): void
346✔
216
    {
217
        $this->rules = [];
346✔
218
        foreach ($rules as $rule) {
346✔
219
            $this->addRule($rule);
291✔
220
        }
221
    }
346✔
222

223
    /**
224
     * Returns all rules matching the given pattern and returns them in an associative array with the rule’s name
225
     * as keys. This method exists mainly for backwards-compatibility and is really only partially useful.
226
     *
227
     * Note: This method loses some information: Calling this (with an argument of `background-`) on a declaration block
228
     * like `{ background-color: green; background-color; rgba(0, 127, 0, 0.7); }` will only yield an associative array
229
     * containing the rgba-valued rule while `getRules()` would yield an indexed array containing both.
230
     *
231
     * @param string|null $searchPattern
232
     *        Pattern to search for. If null, returns all rules. If the pattern ends with a dash,
233
     *        all rules starting with the pattern are returned as well as one matching the pattern with the dash
234
     *        excluded.
235
     *
236
     * @return array<string, Rule>
237
     */
238
    public function getRulesAssoc(?string $searchPattern = null): array
50✔
239
    {
240
        /** @var array<string, Rule> $result */
241
        $result = [];
50✔
242
        foreach ($this->getRules($searchPattern) as $rule) {
50✔
243
            $result[$rule->getRule()] = $rule;
34✔
244
        }
245

246
        return $result;
50✔
247
    }
248

249
    /**
250
     * Removes a `Rule` from this `RuleSet` by identity.
251
     */
252
    public function removeRule(Rule $ruleToRemove): void
22✔
253
    {
254
        $nameOfPropertyToRemove = $ruleToRemove->getRule();
22✔
255
        if (!isset($this->rules[$nameOfPropertyToRemove])) {
22✔
256
            return;
8✔
257
        }
258
        foreach ($this->rules[$nameOfPropertyToRemove] as $key => $rule) {
14✔
259
            if ($rule === $ruleToRemove) {
14✔
260
                unset($this->rules[$nameOfPropertyToRemove][$key]);
10✔
261
            }
262
        }
263
    }
14✔
264

265
    /**
266
     * Removes rules by property name or search pattern.
267
     *
268
     * @param string $searchPattern
269
     *        pattern to remove.
270
     *        If the pattern ends in a dash,
271
     *        all rules starting with the pattern are removed as well as one matching the pattern with the dash
272
     *        excluded.
273
     */
274
    public function removeMatchingRules(string $searchPattern): void
28✔
275
    {
276
        foreach ($this->rules as $propertyName => $rules) {
28✔
277
            // Either the search rule matches the found rule exactly
278
            // or the search rule ends in “-” and the found rule starts with the search rule or equals it
279
            // (without the trailing dash).
280
            if (
281
                $propertyName === $searchPattern
26✔
282
                || (\strrpos($searchPattern, '-') === \strlen($searchPattern) - \strlen('-')
22✔
283
                    && (\strpos($propertyName, $searchPattern) === 0
12✔
284
                        || $propertyName === \substr($searchPattern, 0, -1)))
26✔
285
            ) {
286
                unset($this->rules[$propertyName]);
24✔
287
            }
288
        }
289
    }
28✔
290

291
    public function removeAllRules(): void
4✔
292
    {
293
        $this->rules = [];
4✔
294
    }
4✔
295

296
    /**
297
     * @internal
298
     */
299
    public function render(OutputFormat $outputFormat): string
6✔
300
    {
301
        return $this->renderRules($outputFormat);
6✔
302
    }
303

304
    protected function renderRules(OutputFormat $outputFormat): string
6✔
305
    {
306
        $result = '';
6✔
307
        $isFirst = true;
6✔
308
        $nextLevelFormat = $outputFormat->nextLevel();
6✔
309
        foreach ($this->getRules() as $rule) {
6✔
310
            $nextLevelFormatter = $nextLevelFormat->getFormatter();
5✔
311
            $renderedRule = $nextLevelFormatter->safely(static function () use ($rule, $nextLevelFormat): string {
312
                return $rule->render($nextLevelFormat);
5✔
313
            });
5✔
314
            if ($renderedRule === null) {
5✔
315
                continue;
×
316
            }
317
            if ($isFirst) {
5✔
318
                $isFirst = false;
5✔
319
                $result .= $nextLevelFormatter->spaceBeforeRules();
5✔
320
            } else {
321
                $result .= $nextLevelFormatter->spaceBetweenRules();
4✔
322
            }
323
            $result .= $renderedRule;
5✔
324
        }
325

326
        $formatter = $outputFormat->getFormatter();
6✔
327
        if (!$isFirst) {
6✔
328
            // Had some output
329
            $result .= $formatter->spaceAfterRules();
5✔
330
        }
331

332
        return $formatter->removeLastSemicolon($result);
6✔
333
    }
334

335
    /**
336
     * @return array<string, bool|int|float|string|array<mixed>|null>
337
     *
338
     * @internal
339
     */
340
    public function getArrayRepresentation(): array
1✔
341
    {
342
        throw new \BadMethodCallException('`getArrayRepresentation` is not yet implemented for `' . self::class . '`');
1✔
343
    }
344

345
    /**
346
     * @return int negative if `$first` is before `$second`; zero if they have the same position; positive otherwise
347
     *
348
     * @throws \UnexpectedValueException if either argument does not have a valid position, which should never happen
349
     */
350
    private static function comparePositionable(Positionable $first, Positionable $second): int
178✔
351
    {
352
        $firstsLineNumber = $first->getLineNumber();
178✔
353
        $secondsLineNumber = $second->getLineNumber();
178✔
354
        if (!\is_int($firstsLineNumber) || !\is_int($secondsLineNumber)) {
178✔
355
            throw new \UnexpectedValueException(
×
356
                'A Rule without a line number was passed to comparePositionable',
×
357
                1750637683
×
358
            );
359
        }
360

361
        if ($firstsLineNumber === $secondsLineNumber) {
178✔
362
            $firstsColumnNumber = $first->getColumnNumber();
19✔
363
            $secondsColumnNumber = $second->getColumnNumber();
19✔
364
            if (!\is_int($firstsColumnNumber) || !\is_int($secondsColumnNumber)) {
19✔
365
                throw new \UnexpectedValueException(
×
366
                    'A Rule without a column number was passed to comparePositionable',
×
367
                    1750637761
×
368
                );
369
            }
370
            return $firstsColumnNumber - $secondsColumnNumber;
19✔
371
        }
372

373
        return $firstsLineNumber - $secondsLineNumber;
174✔
374
    }
375

376
    private function hasRule(Rule $rule): bool
66✔
377
    {
378
        foreach ($this->rules as $rulesForAProperty) {
66✔
379
            if (\in_array($rule, $rulesForAProperty, true)) {
66✔
380
                return true;
30✔
381
            }
382
        }
383

384
        return false;
36✔
385
    }
386
}
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