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

MyIntervals / PHP-CSS-Parser / 13334861064

14 Feb 2025 06:08PM UTC coverage: 50.421%. Remained the same
13334861064

push

github

web-flow
[CLEANUP] Avoid Hungarian notation for `result` (#924)

Part of #756

Co-authored-by: JakeQZ <jake.github@qzdesign.co.uk>

49 of 100 new or added lines in 13 files covered. (49.0%)

2 existing lines in 2 files now uncovered.

958 of 1900 relevant lines covered (50.42%)

11.51 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\Comment;
8
use Sabberworm\CSS\Comment\Commentable;
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\Renderable;
14
use Sabberworm\CSS\Rule\Rule;
15

16
/**
17
 * This class is a container for individual 'Rule's.
18
 *
19
 * The most common form of a rule set is one constrained by a selector, i.e., a `DeclarationBlock`.
20
 * However, unknown `AtRule`s (like `@font-face`) are rule sets as well.
21
 *
22
 * If you want to manipulate a `RuleSet`, use the methods `addRule(Rule $rule)`, `getRules()` and `removeRule($rule)`
23
 * (which accepts either a `Rule` or a rule name; optionally suffixed by a dash to remove all related rules).
24
 */
25
abstract class RuleSet implements Renderable, Commentable
26
{
27
    /**
28
     * @var array<string, Rule>
29
     */
30
    private $aRules;
31

32
    /**
33
     * @var int<0, max>
34
     *
35
     * @internal since 8.8.0
36
     */
37
    protected $lineNumber;
38

39
    /**
40
     * @var array<array-key, Comment>
41
     *
42
     * @internal since 8.8.0
43
     */
44
    protected $comments;
45

46
    /**
47
     * @param int<0, max> $lineNumber
48
     */
49
    public function __construct($lineNumber = 0)
×
50
    {
51
        $this->aRules = [];
×
52
        $this->lineNumber = $lineNumber;
×
53
        $this->comments = [];
×
54
    }
×
55

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

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

106
    public function addRule(Rule $rule, ?Rule $oSibling = null): void
×
107
    {
108
        $sRule = $rule->getRule();
×
109
        if (!isset($this->aRules[$sRule])) {
×
110
            $this->aRules[$sRule] = [];
×
111
        }
112

113
        $iPosition = \count($this->aRules[$sRule]);
×
114

115
        if ($oSibling !== null) {
×
116
            $iSiblingPos = \array_search($oSibling, $this->aRules[$sRule], true);
×
117
            if ($iSiblingPos !== false) {
×
118
                $iPosition = $iSiblingPos;
×
119
                $rule->setPosition($oSibling->getLineNo(), $oSibling->getColNo() - 1);
×
120
            }
121
        }
122
        if ($rule->getLineNo() === 0 && $rule->getColNo() === 0) {
×
123
            //this node is added manually, give it the next best line
124
            $rules = $this->getRules();
×
125
            $pos = \count($rules);
×
126
            if ($pos > 0) {
×
127
                $last = $rules[$pos - 1];
×
128
                $rule->setPosition($last->getLineNo() + 1, 0);
×
129
            }
130
        }
131

132
        \array_splice($this->aRules[$sRule], $iPosition, 0, [$rule]);
×
133
    }
×
134

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

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

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

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

260
    public function __toString(): string
×
261
    {
262
        return $this->render(new OutputFormat());
×
263
    }
264

265
    /**
266
     * @return string
267
     */
268
    protected function renderRules(OutputFormat $outputFormat)
×
269
    {
NEW
270
        $result = '';
×
271
        $bIsFirst = true;
×
272
        $oNextLevel = $outputFormat->nextLevel();
×
273
        foreach ($this->aRules as $aRules) {
×
274
            foreach ($aRules as $rule) {
×
275
                $sRendered = $oNextLevel->safely(static function () use ($rule, $oNextLevel): string {
276
                    return $rule->render($oNextLevel);
×
277
                });
×
278
                if ($sRendered === null) {
×
279
                    continue;
×
280
                }
281
                if ($bIsFirst) {
×
282
                    $bIsFirst = false;
×
NEW
283
                    $result .= $oNextLevel->spaceBeforeRules();
×
284
                } else {
NEW
285
                    $result .= $oNextLevel->spaceBetweenRules();
×
286
                }
NEW
287
                $result .= $sRendered;
×
288
            }
289
        }
290

291
        if (!$bIsFirst) {
×
292
            // Had some output
NEW
293
            $result .= $outputFormat->spaceAfterRules();
×
294
        }
295

NEW
296
        return $outputFormat->removeLastSemicolon($result);
×
297
    }
298

299
    /**
300
     * @param array<string, Comment> $comments
301
     */
302
    public function addComments(array $comments): void
×
303
    {
304
        $this->comments = \array_merge($this->comments, $comments);
×
305
    }
×
306

307
    /**
308
     * @return array<string, Comment>
309
     */
310
    public function getComments()
×
311
    {
312
        return $this->comments;
×
313
    }
314

315
    /**
316
     * @param array<string, Comment> $comments
317
     */
318
    public function setComments(array $comments): void
×
319
    {
320
        $this->comments = $comments;
×
321
    }
×
322
}
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

© 2025 Coveralls, Inc