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

MyIntervals / PHP-CSS-Parser / 11767738200

10 Nov 2024 07:04PM UTC coverage: 38.583% (-0.04%) from 38.622%
11767738200

Pull #772

github

web-flow
Merge 43e100d73 into b56f7c697
Pull Request #772: [TASK] Clean up the code with Rector

9 of 18 new or added lines in 9 files covered. (50.0%)

1 existing line in 1 file now uncovered.

779 of 2019 relevant lines covered (38.58%)

5.33 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 $aComments;
40

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

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

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

61
    /**
62
     * @throws UnexpectedTokenException
63
     * @throws SourceException
64
     */
65
    public static function parseList(ParserState $oParserState, CSSList $oList): void
×
66
    {
67
        $bIsRoot = $oList instanceof Document;
×
68
        if (\is_string($oParserState)) {
×
69
            $oParserState = new ParserState($oParserState, Settings::create());
×
70
        }
71
        $bLenientParsing = $oParserState->getSettings()->bLenientParsing;
×
72
        $aComments = [];
×
73
        while (!$oParserState->isEnd()) {
×
74
            $aComments = \array_merge($aComments, $oParserState->consumeWhiteSpace());
×
75
            $oListItem = null;
×
76
            if ($bLenientParsing) {
×
77
                try {
78
                    $oListItem = self::parseListItem($oParserState, $oList);
×
79
                } catch (UnexpectedTokenException $e) {
×
80
                    $oListItem = false;
×
81
                }
82
            } else {
83
                $oListItem = self::parseListItem($oParserState, $oList);
×
84
            }
85
            if ($oListItem === null) {
×
86
                // List parsing finished
87
                return;
×
88
            }
89
            if ($oListItem) {
×
90
                $oListItem->addComments($aComments);
×
91
                $oList->append($oListItem);
×
92
            }
93
            $aComments = $oParserState->consumeWhiteSpace();
×
94
        }
95
        $oList->addComments($aComments);
×
96
        if (!$bIsRoot && !$bLenientParsing) {
×
97
            throw new SourceException('Unexpected end of document', $oParserState->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 $oParserState, CSSList $oList)
×
109
    {
110
        $bIsRoot = $oList instanceof Document;
×
111
        if ($oParserState->comes('@')) {
×
112
            $oAtRule = self::parseAtRule($oParserState);
×
113
            if ($oAtRule instanceof Charset) {
×
114
                if (!$bIsRoot) {
×
115
                    throw new UnexpectedTokenException(
×
116
                        '@charset may only occur in root document',
×
117
                        '',
×
118
                        'custom',
×
119
                        $oParserState->currentLine()
×
120
                    );
121
                }
122
                if (\count($oList->getContents()) > 0) {
×
123
                    throw new UnexpectedTokenException(
×
124
                        '@charset must be the first parseable token in a document',
×
125
                        '',
×
126
                        'custom',
×
127
                        $oParserState->currentLine()
×
128
                    );
129
                }
130
                $oParserState->setCharset($oAtRule->getCharset());
×
131
            }
132
            return $oAtRule;
×
133
        } elseif ($oParserState->comes('}')) {
×
134
            if ($bIsRoot) {
×
135
                if ($oParserState->getSettings()->bLenientParsing) {
×
136
                    return DeclarationBlock::parse($oParserState);
×
137
                } else {
138
                    throw new SourceException('Unopened {', $oParserState->currentLine());
×
139
                }
140
            } else {
141
                // End of list
142
                return null;
×
143
            }
144
        } else {
145
            return DeclarationBlock::parse($oParserState, $oList);
×
146
        }
147
    }
148

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

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

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

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

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

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

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

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

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

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

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

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

405
    /**
406
     * @return string
407
     */
408
    protected function renderListContents(OutputFormat $oOutputFormat)
×
409
    {
410
        $sResult = '';
×
411
        $bIsFirst = true;
×
412
        $oNextLevel = $oOutputFormat;
×
413
        if (!$this->isRootList()) {
×
414
            $oNextLevel = $oOutputFormat->nextLevel();
×
415
        }
416
        foreach ($this->aContents as $oContent) {
×
417
            $sRendered = $oOutputFormat->safely(function () use ($oNextLevel, $oContent) {
418
                return $oContent->render($oNextLevel);
×
419
            });
×
420
            if ($sRendered === null) {
×
421
                continue;
×
422
            }
423
            if ($bIsFirst) {
×
424
                $bIsFirst = false;
×
425
                $sResult .= $oNextLevel->spaceBeforeBlocks();
×
426
            } else {
427
                $sResult .= $oNextLevel->spaceBetweenBlocks();
×
428
            }
429
            $sResult .= $sRendered;
×
430
        }
431

432
        if (!$bIsFirst) {
×
433
            // Had some output
434
            $sResult .= $oOutputFormat->spaceAfterBlocks();
×
435
        }
436

437
        return $sResult;
×
438
    }
439

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

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

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

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

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