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

MyIntervals / PHP-CSS-Parser / 15836833539

23 Jun 2025 10:53PM UTC coverage: 58.052% (-0.05%) from 58.102%
15836833539

Pull #1284

github

web-flow
Merge 5d8c1e2c4 into b0ce7af89
Pull Request #1284: [TASK] Update `RuleSet::addRule` to use `getLineNumber`

3 of 6 new or added lines in 1 file covered. (50.0%)

1049 of 1807 relevant lines covered (58.05%)

16.69 hits per line

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

91.18
/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)
349✔
47
    {
48
        $this->setPosition($lineNumber);
349✔
49
    }
349✔
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
    /**
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
334✔
103
    {
104
        $propertyName = $ruleToAdd->getRule();
334✔
105
        if (!isset($this->rules[$propertyName])) {
334✔
106
            $this->rules[$propertyName] = [];
334✔
107
        }
108

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

111
        if ($sibling !== null) {
334✔
112
            $siblingIsInSet = false;
82✔
113
            $siblingPosition = \array_search($sibling, $this->rules[$propertyName], true);
82✔
114
            if ($siblingPosition !== false) {
82✔
115
                $siblingIsInSet = true;
16✔
116
                $position = $siblingPosition;
16✔
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) {
82✔
131
                // Increment column number of all existing rules on same line, starting at sibling
132
                $siblingLineNumber = $sibling->getLineNumber();
46✔
133
                $siblingColumnNumber = $sibling->getColumnNumber();
46✔
134
                foreach ($this->rules as $rulesForAProperty) {
46✔
135
                    foreach ($rulesForAProperty as $rule) {
46✔
136
                        if (
137
                            $rule->getLineNumber() === $siblingLineNumber &&
46✔
138
                            $rule->getColumnNumber() >= $siblingColumnNumber
46✔
139
                        ) {
140
                            $rule->setPosition($siblingLineNumber, $rule->getColumnNumber() + 1);
46✔
141
                        }
142
                    }
143
                }
144
                $ruleToAdd->setPosition($siblingLineNumber, $siblingColumnNumber);
46✔
145
            }
146
        }
147

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

170
        \array_splice($this->rules[$propertyName], $position, 0, [$ruleToAdd]);
334✔
171
    }
334✔
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
322✔
196
                || (
197
                    \strrpos($searchPattern, '-') === \strlen($searchPattern) - \strlen('-')
28✔
198
                    && (\strpos($propertyName, $searchPattern) === 0
14✔
199
                        || $propertyName === \substr($searchPattern, 0, -1))
322✔
200
                )
201
            ) {
202
                $result = \array_merge($result, $rules);
322✔
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
341✔
216
    {
217
        $this->rules = [];
341✔
218
        foreach ($rules as $rule) {
341✔
219
            $this->addRule($rule);
287✔
220
        }
221
    }
341✔
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
    protected function renderRules(OutputFormat $outputFormat): string
5✔
297
    {
298
        $result = '';
5✔
299
        $isFirst = true;
5✔
300
        $nextLevelFormat = $outputFormat->nextLevel();
5✔
301
        foreach ($this->getRules() as $rule) {
5✔
302
            $nextLevelFormatter = $nextLevelFormat->getFormatter();
5✔
303
            $renderedRule = $nextLevelFormatter->safely(static function () use ($rule, $nextLevelFormat): string {
304
                return $rule->render($nextLevelFormat);
5✔
305
            });
5✔
306
            if ($renderedRule === null) {
5✔
307
                continue;
×
308
            }
309
            if ($isFirst) {
5✔
310
                $isFirst = false;
5✔
311
                $result .= $nextLevelFormatter->spaceBeforeRules();
5✔
312
            } else {
313
                $result .= $nextLevelFormatter->spaceBetweenRules();
1✔
314
            }
315
            $result .= $renderedRule;
5✔
316
        }
317

318
        $formatter = $outputFormat->getFormatter();
5✔
319
        if (!$isFirst) {
5✔
320
            // Had some output
321
            $result .= $formatter->spaceAfterRules();
5✔
322
        }
323

324
        return $formatter->removeLastSemicolon($result);
5✔
325
    }
326

327
    /**
328
     * @return int negative if `$first` is before `$second`; zero if they have the same position; positive otherwise
329
     */
330
    private static function comparePositionable(Positionable $first, Positionable $second): int
176✔
331
    {
332
        if ($first->getLineNo() === $second->getLineNo()) {
176✔
333
            return $first->getColNo() - $second->getColNo();
21✔
334
        }
335
        return $first->getLineNo() - $second->getLineNo();
171✔
336
    }
337

338
    private function hasRule(Rule $rule): bool
66✔
339
    {
340
        foreach ($this->rules as $rulesForAProperty) {
66✔
341
            if (\in_array($rule, $rulesForAProperty, true)) {
66✔
342
                return true;
30✔
343
            }
344
        }
345

346
        return false;
36✔
347
    }
348
}
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