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

MyIntervals / PHP-CSS-Parser / 14208826831

02 Apr 2025 12:31AM UTC coverage: 49.362% (-4.0%) from 53.315%
14208826831

Pull #1194

github

web-flow
Merge 3a278e027 into 9b526151d
Pull Request #1194: [TASK] Use delegation for `DeclarationBlock` -> `RuleSet`

16 of 26 new or added lines in 3 files covered. (61.54%)

73 existing lines in 1 file now uncovered.

890 of 1803 relevant lines covered (49.36%)

7.37 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\Position\Position;
14
use Sabberworm\CSS\Position\Positionable;
15
use Sabberworm\CSS\Rule\Rule;
16

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

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

41
    /**
42
     * @param int<0, max> $lineNumber
43
     */
UNCOV
44
    public function __construct(int $lineNumber = 0)
×
45
    {
UNCOV
46
        $this->setPosition($lineNumber);
×
UNCOV
47
    }
×
48

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

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

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

UNCOV
104
        if ($sibling !== null) {
×
UNCOV
105
            $siblingPosition = \array_search($sibling, $this->rules[$propertyName], true);
×
UNCOV
106
            if ($siblingPosition !== false) {
×
UNCOV
107
                $position = $siblingPosition;
×
UNCOV
108
                $ruleToAdd->setPosition($sibling->getLineNo(), $sibling->getColNo() - 1);
×
109
            }
110
        }
UNCOV
111
        if ($ruleToAdd->getLineNo() === 0 && $ruleToAdd->getColNo() === 0) {
×
112
            //this node is added manually, give it the next best line
UNCOV
113
            $rules = $this->getRules();
×
UNCOV
114
            $rulesCount = \count($rules);
×
UNCOV
115
            if ($rulesCount > 0) {
×
UNCOV
116
                $last = $rules[$rulesCount - 1];
×
UNCOV
117
                $ruleToAdd->setPosition($last->getLineNo() + 1, 0);
×
118
            }
119
        }
120

UNCOV
121
        \array_splice($this->rules[$propertyName], $position, 0, [$ruleToAdd]);
×
UNCOV
122
    }
×
123

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

UNCOV
167
        return $result;
×
168
    }
169

170
    /**
171
     * Overrides all the rules of this set.
172
     *
173
     * @param array<Rule> $rules The rules to override with.
174
     */
UNCOV
175
    public function setRules(array $rules): void
×
176
    {
UNCOV
177
        $this->rules = [];
×
UNCOV
178
        foreach ($rules as $rule) {
×
UNCOV
179
            $this->addRule($rule);
×
180
        }
UNCOV
181
    }
×
182

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

206
        return $result;
×
207
    }
208

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

252
    /**
253
     * @internal
254
     */
NEW
255
    public function render(OutputFormat $outputFormat): string
×
256
    {
NEW
257
        return $this->renderRules($outputFormat);
×
258
    }
259

UNCOV
260
    protected function renderRules(OutputFormat $outputFormat): string
×
261
    {
UNCOV
262
        $result = '';
×
UNCOV
263
        $isFirst = true;
×
UNCOV
264
        $nextLevelFormat = $outputFormat->nextLevel();
×
UNCOV
265
        foreach ($this->getRules() as $rule) {
×
UNCOV
266
            $nextLevelFormatter = $nextLevelFormat->getFormatter();
×
267
            $renderedRule = $nextLevelFormatter->safely(static function () use ($rule, $nextLevelFormat): string {
UNCOV
268
                return $rule->render($nextLevelFormat);
×
UNCOV
269
            });
×
UNCOV
270
            if ($renderedRule === null) {
×
271
                continue;
×
272
            }
UNCOV
273
            if ($isFirst) {
×
UNCOV
274
                $isFirst = false;
×
UNCOV
275
                $result .= $nextLevelFormatter->spaceBeforeRules();
×
276
            } else {
UNCOV
277
                $result .= $nextLevelFormatter->spaceBetweenRules();
×
278
            }
UNCOV
279
            $result .= $renderedRule;
×
280
        }
281

UNCOV
282
        $formatter = $outputFormat->getFormatter();
×
UNCOV
283
        if (!$isFirst) {
×
284
            // Had some output
UNCOV
285
            $result .= $formatter->spaceAfterRules();
×
286
        }
287

UNCOV
288
        return $formatter->removeLastSemicolon($result);
×
289
    }
290
}
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