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

MyIntervals / PHP-CSS-Parser / 14786746469

02 May 2025 01:20AM UTC coverage: 56.162% (-0.1%) from 56.257%
14786746469

Pull #1249

github

web-flow
Merge 446736217 into 9dbc6a644
Pull Request #1249: [TASK] Add `RuleSet::removeMatchingRules()`, with deprecation

0 of 9 new or added lines in 1 file covered. (0.0%)

1 existing line in 1 file now uncovered.

998 of 1777 relevant lines covered (56.16%)

7.89 hits per line

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

68.87
/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
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)
8✔
47
    {
48
        $this->setPosition($lineNumber);
8✔
49
    }
8✔
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
6✔
98
    {
99
        $propertyName = $ruleToAdd->getRule();
6✔
100
        if (!isset($this->rules[$propertyName])) {
6✔
101
            $this->rules[$propertyName] = [];
6✔
102
        }
103

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

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

123
        \array_splice($this->rules[$propertyName], $position, 0, [$ruleToAdd]);
6✔
124
    }
6✔
125

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

169
        return $result;
6✔
170
    }
171

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

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

208
        return $result;
×
209
    }
210

211
    /**
212
     * Removes a `Rule` from this `RuleSet` by identity.
213
     *
214
     * @param Rule|string|null $searchPattern
215
     *        `Rule` to remove.
216
     *        Passing a `string` or `null` is deprecated in version 8.9.0, and will no longer work from v9.0.
217
     *        Use `removeMatchingRules()` instead.
218
     */
219
    public function removeRule($searchPattern): void
×
220
    {
221
        if ($searchPattern instanceof Rule) {
×
222
            $nameOfPropertyToRemove = $searchPattern->getRule();
×
223
            if (!isset($this->rules[$nameOfPropertyToRemove])) {
×
224
                return;
×
225
            }
226
            foreach ($this->rules[$nameOfPropertyToRemove] as $key => $rule) {
×
227
                if ($rule === $searchPattern) {
×
228
                    unset($this->rules[$nameOfPropertyToRemove][$key]);
×
229
                }
230
            }
231
        } else {
NEW
232
            $this->removeMatchingRules($searchPattern);
×
233
        }
NEW
234
    }
×
235

236
    /**
237
     * Removes rules by property name or search pattern.
238
     *
239
     * @param string|null $searchPattern
240
     *        pattern to remove. If null, all rules are removed. If the pattern ends in a dash,
241
     *        all rules starting with the pattern are removed as well as one matching the pattern with the dash
242
     *        excluded.
243
     */
NEW
244
    public function removeMatchingRules(?string $searchPattern): void
×
245
    {
NEW
246
        foreach ($this->rules as $propertyName => $rules) {
×
247
            // Either no search rule is given or the search rule matches the found rule exactly
248
            // or the search rule ends in “-” and the found rule starts with the search rule or equals it
249
            // (without the trailing dash).
250
            if (
NEW
251
                $searchPattern === null || $propertyName === $searchPattern
×
NEW
252
                || (\strrpos($searchPattern, '-') === \strlen($searchPattern) - \strlen('-')
×
NEW
253
                    && (\strpos($propertyName, $searchPattern) === 0
×
NEW
254
                        || $propertyName === \substr($searchPattern, 0, -1)))
×
255
            ) {
NEW
256
                unset($this->rules[$propertyName]);
×
257
            }
258
        }
259
    }
×
260

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

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

289
        return $formatter->removeLastSemicolon($result);
5✔
290
    }
291
}
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