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

MyIntervals / PHP-CSS-Parser / 14183020401

31 Mar 2025 10:51PM UTC coverage: 49.179% (-4.0%) from 53.134%
14183020401

Pull #1194

github

web-flow
Merge 4d7831a98 into 36ed5cdf1
Pull Request #1194: [TASK] Use delegation for `DeclarationBlock` -> `RuleSet`

16 of 28 new or added lines in 3 files covered. (57.14%)

73 existing lines in 1 file now uncovered.

899 of 1828 relevant lines covered (49.18%)

6.9 hits per line

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

0.0
/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\CSSList\CSSListItem;
9
use Sabberworm\CSS\OutputFormat;
10
use Sabberworm\CSS\Parsing\ParserState;
11
use Sabberworm\CSS\Parsing\UnexpectedEOFException;
12
use Sabberworm\CSS\Parsing\UnexpectedTokenException;
13
use Sabberworm\CSS\Rule\Rule;
14

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

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

38
    /**
39
     * @var int<0, max>
40
     *
41
     * @internal since 8.8.0
42
     */
43
    protected $lineNumber;
44

45
    /**
46
     * @param int<0, max> $lineNumber
47
     */
UNCOV
48
    public function __construct(int $lineNumber = 0)
×
49
    {
UNCOV
50
        $this->lineNumber = $lineNumber;
×
UNCOV
51
    }
×
52

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

99
    /**
100
     * @return int<0, max>
101
     */
102
    public function getLineNo(): int
×
103
    {
104
        return $this->lineNumber;
×
105
    }
106

UNCOV
107
    public function addRule(Rule $ruleToAdd, ?Rule $sibling = null): void
×
108
    {
UNCOV
109
        $propertyName = $ruleToAdd->getRule();
×
UNCOV
110
        if (!isset($this->rules[$propertyName])) {
×
UNCOV
111
            $this->rules[$propertyName] = [];
×
112
        }
113

UNCOV
114
        $position = \count($this->rules[$propertyName]);
×
115

UNCOV
116
        if ($sibling !== null) {
×
UNCOV
117
            $siblingPosition = \array_search($sibling, $this->rules[$propertyName], true);
×
UNCOV
118
            if ($siblingPosition !== false) {
×
UNCOV
119
                $position = $siblingPosition;
×
UNCOV
120
                $ruleToAdd->setPosition($sibling->getLineNo(), $sibling->getColNo() - 1);
×
121
            }
122
        }
UNCOV
123
        if ($ruleToAdd->getLineNo() === 0 && $ruleToAdd->getColNo() === 0) {
×
124
            //this node is added manually, give it the next best line
UNCOV
125
            $rules = $this->getRules();
×
UNCOV
126
            $rulesCount = \count($rules);
×
UNCOV
127
            if ($rulesCount > 0) {
×
UNCOV
128
                $last = $rules[$rulesCount - 1];
×
UNCOV
129
                $ruleToAdd->setPosition($last->getLineNo() + 1, 0);
×
130
            }
131
        }
132

UNCOV
133
        \array_splice($this->rules[$propertyName], $position, 0, [$ruleToAdd]);
×
UNCOV
134
    }
×
135

136
    /**
137
     * Returns all rules matching the given rule name
138
     *
139
     * @example $ruleSet->getRules('font') // returns array(0 => $rule, …) or array().
140
     *
141
     * @example $ruleSet->getRules('font-')
142
     *          //returns an array of all rules either beginning with font- or matching font.
143
     *
144
     * @param Rule|string|null $searchPattern
145
     *        Pattern to search for. If null, returns all rules.
146
     *        If the pattern ends with a dash, all rules starting with the pattern are returned
147
     *        as well as one matching the pattern with the dash excluded.
148
     *        Passing a `Rule` behaves like calling `getRules($rule->getRule())`.
149
     *
150
     * @return array<int<0, max>, Rule>
151
     */
UNCOV
152
    public function getRules($searchPattern = null): array
×
153
    {
UNCOV
154
        if ($searchPattern instanceof Rule) {
×
155
            $searchPattern = $searchPattern->getRule();
×
156
        }
UNCOV
157
        $result = [];
×
UNCOV
158
        foreach ($this->rules as $propertyName => $rules) {
×
159
            // Either no search rule is given or the search rule matches the found rule exactly
160
            // or the search rule ends in “-” and the found rule starts with the search rule.
161
            if (
UNCOV
162
                !$searchPattern || $propertyName === $searchPattern
×
163
                || (
UNCOV
164
                    \strrpos($searchPattern, '-') === \strlen($searchPattern) - \strlen('-')
×
UNCOV
165
                    && (\strpos($propertyName, $searchPattern) === 0
×
UNCOV
166
                        || $propertyName === \substr($searchPattern, 0, -1))
×
167
                )
168
            ) {
UNCOV
169
                $result = \array_merge($result, $rules);
×
170
            }
171
        }
172
        \usort($result, static function (Rule $first, Rule $second): int {
UNCOV
173
            if ($first->getLineNo() === $second->getLineNo()) {
×
UNCOV
174
                return $first->getColNo() - $second->getColNo();
×
175
            }
UNCOV
176
            return $first->getLineNo() - $second->getLineNo();
×
UNCOV
177
        });
×
178

UNCOV
179
        return $result;
×
180
    }
181

182
    /**
183
     * Overrides all the rules of this set.
184
     *
185
     * @param array<Rule> $rules The rules to override with.
186
     */
UNCOV
187
    public function setRules(array $rules): void
×
188
    {
UNCOV
189
        $this->rules = [];
×
UNCOV
190
        foreach ($rules as $rule) {
×
UNCOV
191
            $this->addRule($rule);
×
192
        }
UNCOV
193
    }
×
194

195
    /**
196
     * Returns all rules matching the given pattern and returns them in an associative array with the rule’s name
197
     * as keys. This method exists mainly for backwards-compatibility and is really only partially useful.
198
     *
199
     * Note: This method loses some information: Calling this (with an argument of `background-`) on a declaration block
200
     * like `{ background-color: green; background-color; rgba(0, 127, 0, 0.7); }` will only yield an associative array
201
     * containing the rgba-valued rule while `getRules()` would yield an indexed array containing both.
202
     *
203
     * @param Rule|string|null $searchPattern
204
     *        Pattern to search for. If null, returns all rules. If the pattern ends with a dash,
205
     *        all rules starting with the pattern are returned as well as one matching the pattern with the dash
206
     *        excluded. Passing a `Rule` behaves like calling `getRules($rule->getRule())`.
207
     *
208
     * @return array<string, Rule>
209
     */
210
    public function getRulesAssoc($searchPattern = null): array
×
211
    {
212
        /** @var array<string, Rule> $result */
213
        $result = [];
×
214
        foreach ($this->getRules($searchPattern) as $rule) {
×
215
            $result[$rule->getRule()] = $rule;
×
216
        }
217

218
        return $result;
×
219
    }
220

221
    /**
222
     * Removes a rule from this RuleSet. This accepts all the possible values that `getRules()` accepts.
223
     *
224
     * If given a Rule, it will only remove this particular rule (by identity).
225
     * If given a name, it will remove all rules by that name.
226
     *
227
     * Note: this is different from pre-v.2.0 behaviour of PHP-CSS-Parser, where passing a Rule instance would
228
     * remove all rules with the same name. To get the old behaviour, use `removeRule($rule->getRule())`.
229
     *
230
     * @param Rule|string|null $searchPattern
231
     *        pattern to remove. If null, all rules are removed. If the pattern ends in a dash,
232
     *        all rules starting with the pattern are removed as well as one matching the pattern with the dash
233
     *        excluded. Passing a Rule behaves matches by identity.
234
     */
235
    public function removeRule($searchPattern): void
×
236
    {
237
        if ($searchPattern instanceof Rule) {
×
238
            $nameOfPropertyToRemove = $searchPattern->getRule();
×
239
            if (!isset($this->rules[$nameOfPropertyToRemove])) {
×
240
                return;
×
241
            }
242
            foreach ($this->rules[$nameOfPropertyToRemove] as $key => $rule) {
×
243
                if ($rule === $searchPattern) {
×
244
                    unset($this->rules[$nameOfPropertyToRemove][$key]);
×
245
                }
246
            }
247
        } else {
248
            foreach ($this->rules as $propertyName => $rules) {
×
249
                // Either no search rule is given or the search rule matches the found rule exactly
250
                // or the search rule ends in “-” and the found rule starts with the search rule or equals it
251
                // (without the trailing dash).
252
                if (
253
                    !$searchPattern || $propertyName === $searchPattern
×
254
                    || (\strrpos($searchPattern, '-') === \strlen($searchPattern) - \strlen('-')
×
255
                        && (\strpos($propertyName, $searchPattern) === 0
×
256
                            || $propertyName === \substr($searchPattern, 0, -1)))
×
257
                ) {
258
                    unset($this->rules[$propertyName]);
×
259
                }
260
            }
261
        }
262
    }
×
263

264
    /**
265
     * @internal
266
     */
NEW
267
    public function render(OutputFormat $outputFormat): string
×
268
    {
NEW
269
        return $this->renderRules($outputFormat);
×
270
    }
271

UNCOV
272
    protected function renderRules(OutputFormat $outputFormat): string
×
273
    {
UNCOV
274
        $result = '';
×
UNCOV
275
        $isFirst = true;
×
UNCOV
276
        $nextLevelFormat = $outputFormat->nextLevel();
×
UNCOV
277
        foreach ($this->getRules() as $rule) {
×
UNCOV
278
            $nextLevelFormatter = $nextLevelFormat->getFormatter();
×
279
            $renderedRule = $nextLevelFormatter->safely(static function () use ($rule, $nextLevelFormat): string {
UNCOV
280
                return $rule->render($nextLevelFormat);
×
UNCOV
281
            });
×
UNCOV
282
            if ($renderedRule === null) {
×
283
                continue;
×
284
            }
UNCOV
285
            if ($isFirst) {
×
UNCOV
286
                $isFirst = false;
×
UNCOV
287
                $result .= $nextLevelFormatter->spaceBeforeRules();
×
288
            } else {
UNCOV
289
                $result .= $nextLevelFormatter->spaceBetweenRules();
×
290
            }
UNCOV
291
            $result .= $renderedRule;
×
292
        }
293

UNCOV
294
        $formatter = $outputFormat->getFormatter();
×
UNCOV
295
        if (!$isFirst) {
×
296
            // Had some output
UNCOV
297
            $result .= $formatter->spaceAfterRules();
×
298
        }
299

UNCOV
300
        return $formatter->removeLastSemicolon($result);
×
301
    }
302
}
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