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

MyIntervals / PHP-CSS-Parser / 13101106817

02 Feb 2025 05:49PM UTC coverage: 45.347%. Remained the same
13101106817

Pull #872

github

web-flow
Merge 41c399d3f into 5fe6db9f4
Pull Request #872: [CLEANUP] Avoid Hungarian notation in `CSSList`

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

1 existing line in 1 file now uncovered.

804 of 1773 relevant lines covered (45.35%)

12.18 hits per line

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

0.0
/src/CSSList/CSSList.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Sabberworm\CSS\CSSList;
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\SourceException;
12
use Sabberworm\CSS\Parsing\UnexpectedEOFException;
13
use Sabberworm\CSS\Parsing\UnexpectedTokenException;
14
use Sabberworm\CSS\Property\AtRule;
15
use Sabberworm\CSS\Property\Charset;
16
use Sabberworm\CSS\Property\CSSNamespace;
17
use Sabberworm\CSS\Property\Import;
18
use Sabberworm\CSS\Property\Selector;
19
use Sabberworm\CSS\Renderable;
20
use Sabberworm\CSS\RuleSet\AtRuleSet;
21
use Sabberworm\CSS\RuleSet\DeclarationBlock;
22
use Sabberworm\CSS\RuleSet\RuleSet;
23
use Sabberworm\CSS\Settings;
24
use Sabberworm\CSS\Value\CSSString;
25
use Sabberworm\CSS\Value\URL;
26
use Sabberworm\CSS\Value\Value;
27

28
/**
29
 * This is the most generic container available. It can contain `DeclarationBlock`s (rule sets with a selector),
30
 * `RuleSet`s as well as other `CSSList` objects.
31
 *
32
 * It can also contain `Import` and `Charset` objects stemming from at-rules.
33
 */
34
abstract class CSSList implements Renderable, Commentable
35
{
36
    /**
37
     * @var array<array-key, Comment>
38
     */
39
    protected $comments;
40

41
    /**
42
     * @var array<int, RuleSet|CSSList|Import|Charset>
43
     */
44
    protected $contents;
45

46
    /**
47
     * @var int
48
     */
49
    protected $lineNumber;
50

51
    /**
52
     * @param int $lineNumber
53
     */
54
    public function __construct($lineNumber = 0)
×
55
    {
56
        $this->comments = [];
×
57
        $this->contents = [];
×
58
        $this->lineNumber = $lineNumber;
×
59
    }
×
60

61
    /**
62
     * @throws UnexpectedTokenException
63
     * @throws SourceException
64
     */
65
    public static function parseList(ParserState $parserState, CSSList $list): void
×
66
    {
NEW
67
        $isRoot = $list instanceof Document;
×
68
        if (\is_string($parserState)) {
×
69
            $parserState = new ParserState($parserState, Settings::create());
×
70
        }
71
        $usesLenientParsing = $parserState->getSettings()->bLenientParsing;
×
72
        $comments = [];
×
73
        while (!$parserState->isEnd()) {
×
74
            $comments = \array_merge($comments, $parserState->consumeWhiteSpace());
×
75
            $listItem = null;
×
76
            if ($usesLenientParsing) {
×
77
                try {
78
                    $listItem = self::parseListItem($parserState, $list);
×
79
                } catch (UnexpectedTokenException $e) {
×
80
                    $listItem = false;
×
81
                }
82
            } else {
83
                $listItem = self::parseListItem($parserState, $list);
×
84
            }
85
            if ($listItem === null) {
×
86
                // List parsing finished
87
                return;
×
88
            }
89
            if ($listItem) {
×
90
                $listItem->addComments($comments);
×
91
                $list->append($listItem);
×
92
            }
93
            $comments = $parserState->consumeWhiteSpace();
×
94
        }
95
        $list->addComments($comments);
×
NEW
96
        if (!$isRoot && !$usesLenientParsing) {
×
97
            throw new SourceException('Unexpected end of document', $parserState->currentLine());
×
98
        }
99
    }
×
100

101
    /**
102
     * @return AtRuleBlockList|KeyFrame|Charset|CSSNamespace|Import|AtRuleSet|DeclarationBlock|false|null
103
     *
104
     * @throws SourceException
105
     * @throws UnexpectedEOFException
106
     * @throws UnexpectedTokenException
107
     */
108
    private static function parseListItem(ParserState $parserState, CSSList $list)
×
109
    {
NEW
110
        $isRoot = $list instanceof Document;
×
111
        if ($parserState->comes('@')) {
×
NEW
112
            $atRule = self::parseAtRule($parserState);
×
NEW
113
            if ($atRule instanceof Charset) {
×
NEW
114
                if (!$isRoot) {
×
115
                    throw new UnexpectedTokenException(
×
116
                        '@charset may only occur in root document',
×
117
                        '',
×
118
                        'custom',
×
119
                        $parserState->currentLine()
×
120
                    );
121
                }
122
                if (\count($list->getContents()) > 0) {
×
123
                    throw new UnexpectedTokenException(
×
124
                        '@charset must be the first parseable token in a document',
×
125
                        '',
×
126
                        'custom',
×
127
                        $parserState->currentLine()
×
128
                    );
129
                }
NEW
130
                $parserState->setCharset($atRule->getCharset());
×
131
            }
NEW
132
            return $atRule;
×
133
        } elseif ($parserState->comes('}')) {
×
NEW
134
            if ($isRoot) {
×
135
                if ($parserState->getSettings()->bLenientParsing) {
×
136
                    return DeclarationBlock::parse($parserState);
×
137
                } else {
138
                    throw new SourceException('Unopened {', $parserState->currentLine());
×
139
                }
140
            } else {
141
                // End of list
142
                return null;
×
143
            }
144
        } else {
145
            return DeclarationBlock::parse($parserState, $list);
×
146
        }
147
    }
148

149
    /**
150
     * @return AtRuleBlockList|KeyFrame|Charset|CSSNamespace|Import|AtRuleSet|null
151
     *
152
     * @throws SourceException
153
     * @throws UnexpectedTokenException
154
     * @throws UnexpectedEOFException
155
     */
156
    private static function parseAtRule(ParserState $parserState)
×
157
    {
158
        $parserState->consume('@');
×
159
        $identifier = $parserState->parseIdentifier();
×
NEW
160
        $identifierLineNumber = $parserState->currentLine();
×
161
        $parserState->consumeWhiteSpace();
×
162
        if ($identifier === 'import') {
×
163
            $location = URL::parse($parserState);
×
164
            $parserState->consumeWhiteSpace();
×
165
            $mediaQuery = null;
×
166
            if (!$parserState->comes(';')) {
×
167
                $mediaQuery = \trim($parserState->consumeUntil([';', ParserState::EOF]));
×
168
                if ($mediaQuery === '') {
×
169
                    $mediaQuery = null;
×
170
                }
171
            }
172
            $parserState->consumeUntil([';', ParserState::EOF], true, true);
×
NEW
173
            return new Import($location, $mediaQuery, $identifierLineNumber);
×
174
        } elseif ($identifier === 'charset') {
×
NEW
175
            $charsetString = CSSString::parse($parserState);
×
176
            $parserState->consumeWhiteSpace();
×
177
            $parserState->consumeUntil([';', ParserState::EOF], true, true);
×
NEW
178
            return new Charset($charsetString, $identifierLineNumber);
×
179
        } elseif (self::identifierIs($identifier, 'keyframes')) {
×
NEW
180
            $result = new KeyFrame($identifierLineNumber);
×
181
            $result->setVendorKeyFrame($identifier);
×
182
            $result->setAnimationName(\trim($parserState->consumeUntil('{', false, true)));
×
183
            CSSList::parseList($parserState, $result);
×
184
            if ($parserState->comes('}')) {
×
185
                $parserState->consume('}');
×
186
            }
187
            return $result;
×
188
        } elseif ($identifier === 'namespace') {
×
189
            $sPrefix = null;
×
NEW
190
            $url = Value::parsePrimitiveValue($parserState);
×
191
            if (!$parserState->comes(';')) {
×
NEW
192
                $sPrefix = $url;
×
NEW
193
                $url = Value::parsePrimitiveValue($parserState);
×
194
            }
195
            $parserState->consumeUntil([';', ParserState::EOF], true, true);
×
196
            if ($sPrefix !== null && !\is_string($sPrefix)) {
×
NEW
197
                throw new UnexpectedTokenException('Wrong namespace prefix', $sPrefix, 'custom', $identifierLineNumber);
×
198
            }
NEW
199
            if (!($url instanceof CSSString || $url instanceof URL)) {
×
200
                throw new UnexpectedTokenException(
×
201
                    'Wrong namespace url of invalid type',
×
202
                    $url,
203
                    'custom',
×
204
                    $identifierLineNumber
205
                );
206
            }
NEW
207
            return new CSSNamespace($url, $sPrefix, $identifierLineNumber);
×
208
        } else {
209
            // Unknown other at rule (font-face or such)
NEW
210
            $arguments = \trim($parserState->consumeUntil('{', false, true));
×
NEW
211
            if (\substr_count($arguments, '(') != \substr_count($arguments, ')')) {
×
212
                if ($parserState->getSettings()->bLenientParsing) {
×
213
                    return null;
×
214
                } else {
215
                    throw new SourceException('Unmatched brace count in media query', $parserState->currentLine());
×
216
                }
217
            }
NEW
218
            $useRuleSet = true;
×
NEW
219
            foreach (\explode('/', AtRule::BLOCK_RULES) as $blockRuleName) {
×
NEW
220
                if (self::identifierIs($identifier, $blockRuleName)) {
×
NEW
221
                    $useRuleSet = false;
×
UNCOV
222
                    break;
×
223
                }
224
            }
NEW
225
            if ($useRuleSet) {
×
NEW
226
                $atRule = new AtRuleSet($identifier, $arguments, $identifierLineNumber);
×
NEW
227
                RuleSet::parseRuleSet($parserState, $atRule);
×
228
            } else {
NEW
229
                $atRule = new AtRuleBlockList($identifier, $arguments, $identifierLineNumber);
×
NEW
230
                CSSList::parseList($parserState, $atRule);
×
231
                if ($parserState->comes('}')) {
×
232
                    $parserState->consume('}');
×
233
                }
234
            }
NEW
235
            return $atRule;
×
236
        }
237
    }
238

239
    /**
240
     * Tests an identifier for a given value. Since identifiers are all keywords, they can be vendor-prefixed.
241
     * We need to check for these versions too.
242
     *
243
     * @param string $identifier
244
     */
NEW
245
    private static function identifierIs($identifier, string $match): bool
×
246
    {
NEW
247
        return (\strcasecmp($identifier, $match) === 0)
×
NEW
248
            ?: \preg_match("/^(-\\w+-)?$match$/i", $identifier) === 1;
×
249
    }
250

251
    /**
252
     * @return int
253
     */
254
    public function getLineNo()
×
255
    {
256
        return $this->lineNumber;
×
257
    }
258

259
    /**
260
     * Prepends an item to the list of contents.
261
     *
262
     * @param RuleSet|CSSList|Import|Charset $item
263
     */
264
    public function prepend($item): void
×
265
    {
266
        \array_unshift($this->contents, $item);
×
267
    }
×
268

269
    /**
270
     * Appends an item to the list of contents.
271
     *
272
     * @param RuleSet|CSSList|Import|Charset $item
273
     */
274
    public function append($item): void
×
275
    {
276
        $this->contents[] = $item;
×
277
    }
×
278

279
    /**
280
     * Splices the list of contents.
281
     *
282
     * @param int $offset
283
     * @param int $length
284
     * @param array<int, RuleSet|CSSList|Import|Charset> $replacement
285
     */
NEW
286
    public function splice($offset, $length = null, $replacement = null): void
×
287
    {
NEW
288
        \array_splice($this->contents, $offset, $length, $replacement);
×
289
    }
×
290

291
    /**
292
     * Inserts an item in the CSS list before its sibling. If the desired sibling cannot be found,
293
     * the item is appended at the end.
294
     *
295
     * @param RuleSet|CSSList|Import|Charset $item
296
     * @param RuleSet|CSSList|Import|Charset $sibling
297
     */
298
    public function insertBefore($item, $sibling): void
×
299
    {
300
        if (\in_array($sibling, $this->contents, true)) {
×
301
            $this->replace($sibling, [$item, $sibling]);
×
302
        } else {
303
            $this->append($item);
×
304
        }
305
    }
×
306

307
    /**
308
     * Removes an item from the CSS list.
309
     *
310
     * @param RuleSet|Import|Charset|CSSList $itemToRemove
311
     *        May be a `RuleSet` (most likely a `DeclarationBlock`), an `Import`,
312
     *        a `Charset` or another `CSSList` (most likely a `MediaQuery`)
313
     *
314
     * @return bool whether the item was removed
315
     */
316
    public function remove($itemToRemove)
×
317
    {
318
        $key = \array_search($itemToRemove, $this->contents, true);
×
319
        if ($key !== false) {
×
320
            unset($this->contents[$key]);
×
321
            return true;
×
322
        }
323
        return false;
×
324
    }
325

326
    /**
327
     * Replaces an item from the CSS list.
328
     *
329
     * @param RuleSet|Import|Charset|CSSList $oldItem
330
     *        May be a `RuleSet` (most likely a `DeclarationBlock`), an `Import`, a `Charset`
331
     *        or another `CSSList` (most likely a `MediaQuery`)
332
     *
333
     * @return bool
334
     */
335
    public function replace($oldItem, $newItem)
×
336
    {
337
        $key = \array_search($oldItem, $this->contents, true);
×
338
        if ($key !== false) {
×
339
            if (\is_array($newItem)) {
×
340
                \array_splice($this->contents, $key, 1, $newItem);
×
341
            } else {
342
                \array_splice($this->contents, $key, 1, [$newItem]);
×
343
            }
344
            return true;
×
345
        }
346
        return false;
×
347
    }
348

349
    /**
350
     * @param array<int, RuleSet|Import|Charset|CSSList> $contents
351
     */
352
    public function setContents(array $contents): void
×
353
    {
354
        $this->contents = [];
×
355
        foreach ($contents as $content) {
×
356
            $this->append($content);
×
357
        }
358
    }
×
359

360
    /**
361
     * Removes a declaration block from the CSS list if it matches all given selectors.
362
     *
363
     * @param DeclarationBlock|array<array-key, Selector>|string $selectors the selectors to match
364
     * @param bool $removeAll whether to stop at the first declaration block found or remove all blocks
365
     */
NEW
366
    public function removeDeclarationBlockBySelector($selectors, $removeAll = false): void
×
367
    {
NEW
368
        if ($selectors instanceof DeclarationBlock) {
×
NEW
369
            $selectors = $selectors->getSelectors();
×
370
        }
NEW
371
        if (!\is_array($selectors)) {
×
NEW
372
            $selectors = \explode(',', $selectors);
×
373
        }
NEW
374
        foreach ($selectors as $key => &$selector) {
×
NEW
375
            if (!($selector instanceof Selector)) {
×
NEW
376
                if (!Selector::isValid($selector)) {
×
377
                    throw new UnexpectedTokenException(
×
378
                        "Selector did not match '" . Selector::SELECTOR_VALIDATION_RX . "'.",
×
379
                        $selector,
380
                        'custom'
×
381
                    );
382
                }
NEW
383
                $selector = new Selector($selector);
×
384
            }
385
        }
386
        foreach ($this->contents as $key => $item) {
×
387
            if (!($item instanceof DeclarationBlock)) {
×
388
                continue;
×
389
            }
NEW
390
            if ($item->getSelectors() == $selectors) {
×
391
                unset($this->contents[$key]);
×
NEW
392
                if (!$removeAll) {
×
393
                    return;
×
394
                }
395
            }
396
        }
397
    }
×
398

399
    public function __toString(): string
×
400
    {
401
        return $this->render(new OutputFormat());
×
402
    }
403

404
    /**
405
     * @return string
406
     */
407
    protected function renderListContents(OutputFormat $oOutputFormat)
×
408
    {
NEW
409
        $result = '';
×
NEW
410
        $isFirst = true;
×
NEW
411
        $nextLevelFormat = $oOutputFormat;
×
412
        if (!$this->isRootList()) {
×
NEW
413
            $nextLevelFormat = $oOutputFormat->nextLevel();
×
414
        }
415
        foreach ($this->contents as $listItem) {
×
416
            $renderedCss = $oOutputFormat->safely(static function () use ($nextLevelFormat, $listItem): string {
NEW
417
                return $listItem->render($nextLevelFormat);
×
418
            });
×
NEW
419
            if ($renderedCss === null) {
×
420
                continue;
×
421
            }
NEW
422
            if ($isFirst) {
×
NEW
423
                $isFirst = false;
×
NEW
424
                $result .= $nextLevelFormat->spaceBeforeBlocks();
×
425
            } else {
NEW
426
                $result .= $nextLevelFormat->spaceBetweenBlocks();
×
427
            }
NEW
428
            $result .= $renderedCss;
×
429
        }
430

NEW
431
        if (!$isFirst) {
×
432
            // Had some output
NEW
433
            $result .= $oOutputFormat->spaceAfterBlocks();
×
434
        }
435

NEW
436
        return $result;
×
437
    }
438

439
    /**
440
     * Return true if the list can not be further outdented. Only important when rendering.
441
     *
442
     * @return bool
443
     */
444
    abstract public function isRootList();
445

446
    /**
447
     * Returns the stored items.
448
     *
449
     * @return array<int, RuleSet|Import|Charset|CSSList>
450
     */
451
    public function getContents()
×
452
    {
453
        return $this->contents;
×
454
    }
455

456
    /**
457
     * @param array<array-key, Comment> $comments
458
     */
459
    public function addComments(array $comments): void
×
460
    {
461
        $this->comments = \array_merge($this->comments, $comments);
×
462
    }
×
463

464
    /**
465
     * @return array<array-key, Comment>
466
     */
467
    public function getComments()
×
468
    {
469
        return $this->comments;
×
470
    }
471

472
    /**
473
     * @param array<array-key, Comment> $comments
474
     */
475
    public function setComments(array $comments): void
×
476
    {
477
        $this->comments = $comments;
×
478
    }
×
479
}
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