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

MyIntervals / PHP-CSS-Parser / 13078651759

31 Jan 2025 06:31PM UTC coverage: 45.068%. Remained the same
13078651759

push

github

web-flow
[CLEANUP] Avoid Hungarian notation for `iKey` (#855)

Part of #756

5 of 17 new or added lines in 3 files covered. (29.41%)

1 existing line in 1 file now uncovered.

795 of 1764 relevant lines covered (45.07%)

10.79 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
34
     */
35
    protected $lineNumber;
36

37
    /**
38
     * @var array<array-key, Comment>
39
     */
40
    protected $comments;
41

42
    /**
43
     * @param int $lineNumber
44
     */
45
    public function __construct($lineNumber = 0)
×
46
    {
47
        $this->aRules = [];
×
48
        $this->lineNumber = $lineNumber;
×
49
        $this->comments = [];
×
50
    }
×
51

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

92
    /**
93
     * @return int
94
     */
95
    public function getLineNo()
×
96
    {
97
        return $this->lineNumber;
×
98
    }
99

100
    public function addRule(Rule $rule, ?Rule $oSibling = null): void
×
101
    {
102
        $sRule = $rule->getRule();
×
103
        if (!isset($this->aRules[$sRule])) {
×
104
            $this->aRules[$sRule] = [];
×
105
        }
106

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

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

126
        \array_splice($this->aRules[$sRule], $iPosition, 0, [$rule]);
×
127
    }
×
128

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

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

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

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

254
    public function __toString(): string
×
255
    {
256
        return $this->render(new OutputFormat());
×
257
    }
258

259
    /**
260
     * @return string
261
     */
262
    protected function renderRules(OutputFormat $oOutputFormat)
×
263
    {
264
        $sResult = '';
×
265
        $bIsFirst = true;
×
266
        $oNextLevel = $oOutputFormat->nextLevel();
×
267
        foreach ($this->aRules as $aRules) {
×
268
            foreach ($aRules as $rule) {
×
269
                $sRendered = $oNextLevel->safely(static function () use ($rule, $oNextLevel): string {
270
                    return $rule->render($oNextLevel);
×
271
                });
×
272
                if ($sRendered === null) {
×
273
                    continue;
×
274
                }
275
                if ($bIsFirst) {
×
276
                    $bIsFirst = false;
×
277
                    $sResult .= $oNextLevel->spaceBeforeRules();
×
278
                } else {
279
                    $sResult .= $oNextLevel->spaceBetweenRules();
×
280
                }
281
                $sResult .= $sRendered;
×
282
            }
283
        }
284

285
        if (!$bIsFirst) {
×
286
            // Had some output
287
            $sResult .= $oOutputFormat->spaceAfterRules();
×
288
        }
289

290
        return $oOutputFormat->removeLastSemicolon($sResult);
×
291
    }
292

293
    /**
294
     * @param array<string, Comment> $comments
295
     */
296
    public function addComments(array $comments): void
×
297
    {
298
        $this->comments = \array_merge($this->comments, $comments);
×
299
    }
×
300

301
    /**
302
     * @return array<string, Comment>
303
     */
304
    public function getComments()
×
305
    {
306
        return $this->comments;
×
307
    }
308

309
    /**
310
     * @param array<string, Comment> $comments
311
     */
312
    public function setComments(array $comments): void
×
313
    {
314
        $this->comments = $comments;
×
315
    }
×
316
}
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