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

MyIntervals / PHP-CSS-Parser / 20148167174

11 Dec 2025 09:35PM UTC coverage: 67.188% (-0.2%) from 67.402%
20148167174

Pull #1420

github

web-flow
Merge f87f9e2da into 42502fd99
Pull Request #1420: [CLEANUP] Extract method `DeclarationBlock::parseSelector`

15 of 23 new or added lines in 2 files covered. (65.22%)

25 existing lines in 1 file now uncovered.

1288 of 1917 relevant lines covered (67.19%)

31.07 hits per line

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

43.14
/src/Parsing/ParserState.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Sabberworm\CSS\Parsing;
6

7
use Sabberworm\CSS\Comment\Comment;
8
use Sabberworm\CSS\Settings;
9

10
use function Safe\iconv;
11
use function Safe\preg_match;
12
use function Safe\preg_split;
13

14
/**
15
 * @internal since 8.7.0
16
 */
17
class ParserState
18
{
19
    public const EOF = null;
20

21
    /**
22
     * @var Settings
23
     */
24
    private $parserSettings;
25

26
    /**
27
     * @var string
28
     */
29
    private $text;
30

31
    /**
32
     * @var array<int, string>
33
     */
34
    private $characters;
35

36
    /**
37
     * @var int<0, max>
38
     */
39
    private $currentPosition = 0;
40

41
    /**
42
     * will only be used if the CSS does not contain an `@charset` declaration
43
     *
44
     * @var string
45
     */
46
    private $charset;
47

48
    /**
49
     * @var int<1, max> $lineNumber
50
     */
51
    private $lineNumber;
52

53
    /**
54
     * @param string $text the complete CSS as text (i.e., usually the contents of a CSS file)
55
     * @param int<1, max> $lineNumber
56
     */
57
    public function __construct(string $text, Settings $parserSettings, int $lineNumber = 1)
6✔
58
    {
59
        $this->parserSettings = $parserSettings;
6✔
60
        $this->text = $text;
6✔
61
        $this->lineNumber = $lineNumber;
6✔
62
        $this->setCharset($this->parserSettings->getDefaultCharset());
6✔
63
    }
6✔
64

65
    /**
66
     * Sets the charset to be used if the CSS does not contain an `@charset` declaration.
67
     */
68
    public function setCharset(string $charset): void
6✔
69
    {
70
        $this->charset = $charset;
6✔
71
        $this->characters = $this->strsplit($this->text);
6✔
72
    }
6✔
73

74
    /**
75
     * @return int<1, max>
76
     */
77
    public function currentLine(): int
×
78
    {
79
        return $this->lineNumber;
×
80
    }
81

82
    /**
83
     * @return int<0, max>
84
     */
85
    public function currentColumn(): int
×
86
    {
87
        return $this->currentPosition;
×
88
    }
89

90
    public function getSettings(): Settings
×
91
    {
92
        return $this->parserSettings;
×
93
    }
94

95
    public function anchor(): Anchor
×
96
    {
97
        return new Anchor($this->currentPosition, $this);
×
98
    }
99

100
    /**
101
     * @param int<0, max> $position
102
     */
103
    public function setPosition(int $position): void
×
104
    {
105
        $this->currentPosition = $position;
×
106
    }
×
107

108
    /**
109
     * @return non-empty-string
110
     *
111
     * @throws UnexpectedTokenException
112
     */
113
    public function parseIdentifier(bool $ignoreCase = true): string
×
114
    {
115
        if ($this->isEnd()) {
×
116
            throw new UnexpectedEOFException('', '', 'identifier', $this->lineNumber);
×
117
        }
118
        $result = $this->parseCharacter(true);
×
119
        if ($result === null) {
×
120
            throw new UnexpectedTokenException('', $this->peek(5), 'identifier', $this->lineNumber);
×
121
        }
122
        $character = null;
×
123
        while (!$this->isEnd() && ($character = $this->parseCharacter(true)) !== null) {
×
124
            if (preg_match('/[a-zA-Z0-9\\x{00A0}-\\x{FFFF}_-]/Sux', $character) !== 0) {
×
125
                $result .= $character;
×
126
            } else {
127
                $result .= '\\' . $character;
×
128
            }
129
        }
130
        if ($ignoreCase) {
×
131
            $result = $this->strtolower($result);
×
132
        }
133

134
        return $result;
×
135
    }
136

137
    /**
138
     * @throws UnexpectedEOFException
139
     * @throws UnexpectedTokenException
140
     */
141
    public function parseCharacter(bool $isForIdentifier): ?string
×
142
    {
143
        if ($this->peek() === '\\') {
×
144
            $this->consume('\\');
×
145
            if ($this->comes('\\n') || $this->comes('\\r')) {
×
146
                return '';
×
147
            }
148
            if (preg_match('/[0-9a-fA-F]/Su', $this->peek()) === 0) {
×
149
                return $this->consume(1);
×
150
            }
151
            $hexCodePoint = $this->consumeExpression('/^[0-9a-fA-F]{1,6}/u', 6);
×
152
            if ($this->strlen($hexCodePoint) < 6) {
×
153
                // Consume whitespace after incomplete unicode escape
154
                if (preg_match('/\\s/isSu', $this->peek()) !== 0) {
×
155
                    if ($this->comes('\\r\\n')) {
×
156
                        $this->consume(2);
×
157
                    } else {
158
                        $this->consume(1);
×
159
                    }
160
                }
161
            }
162
            $codePoint = \intval($hexCodePoint, 16);
×
163
            $utf32EncodedCharacter = '';
×
164
            for ($i = 0; $i < 4; ++$i) {
×
165
                $utf32EncodedCharacter .= \chr($codePoint & 0xff);
×
166
                $codePoint = $codePoint >> 8;
×
167
            }
168
            return iconv('utf-32le', $this->charset, $utf32EncodedCharacter);
×
169
        }
170
        if ($isForIdentifier) {
×
171
            $peek = \ord($this->peek());
×
172
            // Ranges: a-z A-Z 0-9 - _
173
            if (
174
                ($peek >= 97 && $peek <= 122)
×
175
                || ($peek >= 65 && $peek <= 90)
×
176
                || ($peek >= 48 && $peek <= 57)
×
177
                || ($peek === 45)
×
178
                || ($peek === 95)
×
179
                || ($peek > 0xa1)
×
180
            ) {
181
                return $this->consume(1);
×
182
            }
183
        } else {
184
            return $this->consume(1);
×
185
        }
186

187
        return null;
×
188
    }
189

190
    /**
191
     * @return list<Comment>
192
     *
193
     * @throws UnexpectedEOFException
194
     * @throws UnexpectedTokenException
195
     */
196
    public function consumeWhiteSpace(): array
×
197
    {
198
        $comments = [];
×
199
        do {
200
            while (preg_match('/\\s/isSu', $this->peek()) === 1) {
×
201
                $this->consume(1);
×
202
            }
203
            if ($this->parserSettings->usesLenientParsing()) {
×
204
                try {
205
                    $comment = $this->consumeComment();
×
206
                } catch (UnexpectedEOFException $e) {
×
207
                    $this->currentPosition = \count($this->characters);
×
208
                    break;
×
209
                }
210
            } else {
211
                $comment = $this->consumeComment();
×
212
            }
213
            if ($comment instanceof Comment) {
×
214
                $comments[] = $comment;
×
215
            }
216
        } while ($comment instanceof Comment);
×
217

218
        return $comments;
×
219
    }
220

221
    /**
222
     * @param non-empty-string $string
223
     */
224
    public function comes(string $string, bool $caseInsensitive = false): bool
6✔
225
    {
226
        $peek = $this->peek(\strlen($string));
6✔
227

228
        return ($peek !== '') && $this->streql($peek, $string, $caseInsensitive);
6✔
229
    }
230

231
    /**
232
     * @param int<1, max> $length
233
     * @param int<0, max> $offset
234
     */
235
    public function peek(int $length = 1, int $offset = 0): string
6✔
236
    {
237
        $offset += $this->currentPosition;
6✔
238
        if ($offset >= \count($this->characters)) {
6✔
239
            return '';
×
240
        }
241

242
        return $this->substr($offset, $length);
6✔
243
    }
244

245
    /**
246
     * @param string|int<1, max> $value
247
     *
248
     * @throws UnexpectedEOFException
249
     * @throws UnexpectedTokenException
250
     */
251
    public function consume($value = 1): string
6✔
252
    {
253
        if (\is_string($value)) {
6✔
254
            $numberOfLines = \substr_count($value, "\n");
×
255
            $length = $this->strlen($value);
×
256
            if (!$this->streql($this->substr($this->currentPosition, $length), $value)) {
×
257
                throw new UnexpectedTokenException(
×
258
                    $value,
×
259
                    $this->peek(\max($length, 5)),
×
260
                    'literal',
×
261
                    $this->lineNumber
×
262
                );
263
            }
264

265
            $this->lineNumber += $numberOfLines;
×
266
            $this->currentPosition += $this->strlen($value);
×
267
            $result = $value;
×
268
        } else {
269
            if ($this->currentPosition + $value > \count($this->characters)) {
6✔
270
                throw new UnexpectedEOFException((string) $value, $this->peek(5), 'count', $this->lineNumber);
×
271
            }
272

273
            $result = $this->substr($this->currentPosition, $value);
6✔
274
            $numberOfLines = \substr_count($result, "\n");
6✔
275
            $this->lineNumber += $numberOfLines;
6✔
276
            $this->currentPosition += $value;
6✔
277
        }
278

279
        return $result;
6✔
280
    }
281

282
    /**
283
     * If the possibly-expected next content is next, consume it.
284
     *
285
     * @param non-empty-string $nextContent
286
     *
287
     * @return bool whether the possibly-expected content was found and consumed
288
     */
NEW
289
    public function consumeIfComes(string $nextContent): bool
×
290
    {
NEW
291
        $length = $this->strlen($nextContent);
×
NEW
292
        if (!$this->streql($this->substr($this->currentPosition, $length), $nextContent)) {
×
NEW
293
            return false;
×
294
        }
295

NEW
UNCOV
296
        $numberOfLines = \substr_count($nextContent, "\n");
×
NEW
297
        $this->lineNumber += $numberOfLines;
×
NEW
UNCOV
298
        $this->currentPosition += $this->strlen($nextContent);
×
299

NEW
UNCOV
300
        return true;
×
301
    }
302

303
    /**
304
     * @param string $expression
305
     * @param int<1, max>|null $maximumLength
306
     *
307
     * @throws UnexpectedEOFException
308
     * @throws UnexpectedTokenException
309
     */
UNCOV
310
    public function consumeExpression(string $expression, ?int $maximumLength = null): string
×
311
    {
UNCOV
312
        $matches = null;
×
UNCOV
313
        $input = ($maximumLength !== null) ? $this->peek($maximumLength) : $this->inputLeft();
×
UNCOV
314
        if (preg_match($expression, $input, $matches, PREG_OFFSET_CAPTURE) !== 1) {
×
UNCOV
315
            throw new UnexpectedTokenException($expression, $this->peek(5), 'expression', $this->lineNumber);
×
316
        }
317

UNCOV
318
        return $this->consume($matches[0][0]);
×
319
    }
320

321
    /**
322
     * @return Comment|false
323
     */
324
    public function consumeComment()
6✔
325
    {
326
        $lineNumber = $this->lineNumber;
6✔
327
        $comment = null;
6✔
328

329
        if ($this->comes('/*')) {
6✔
330
            $this->consume(1);
6✔
331
            $comment = '';
6✔
332
            while (($char = $this->consume(1)) !== '') {
6✔
333
                $comment .= $char;
6✔
334
                if ($this->comes('*/')) {
6✔
335
                    $this->consume(2);
6✔
336
                    break;
6✔
337
                }
338
            }
339
        }
340

341
        // We skip the * which was included in the comment.
342
        return \is_string($comment) ? new Comment(\substr($comment, 1), $lineNumber) : false;
6✔
343
    }
344

345
    public function isEnd(): bool
6✔
346
    {
347
        return $this->currentPosition >= \count($this->characters);
6✔
348
    }
349

350
    /**
351
     * @param list<string|self::EOF>|string|self::EOF $stopCharacters
352
     * @param list<Comment> $comments
353
     *
354
     * @throws UnexpectedEOFException
355
     * @throws UnexpectedTokenException
356
     */
357
    public function consumeUntil(
6✔
358
        $stopCharacters,
359
        bool $includeEnd = false,
360
        bool $consumeEnd = false,
361
        array &$comments = []
362
    ): string {
363
        $stopCharacters = \is_array($stopCharacters) ? $stopCharacters : [$stopCharacters];
6✔
364
        $consumedCharacters = '';
6✔
365
        $start = $this->currentPosition;
6✔
366

367
        $comments = \array_merge($comments, $this->consumeComments());
6✔
368
        while (!$this->isEnd()) {
6✔
369
            $character = $this->consume(1);
6✔
370
            if (\in_array($character, $stopCharacters, true)) {
6✔
371
                if ($includeEnd) {
6✔
UNCOV
372
                    $consumedCharacters .= $character;
×
373
                } elseif (!$consumeEnd) {
6✔
374
                    $this->currentPosition -= $this->strlen($character);
6✔
375
                }
376
                return $consumedCharacters;
6✔
377
            }
378
            $consumedCharacters .= $character;
6✔
379
            $comments = \array_merge($comments, $this->consumeComments());
6✔
380
        }
381

UNCOV
382
        if (\in_array(self::EOF, $stopCharacters, true)) {
×
UNCOV
383
            return $consumedCharacters;
×
384
        }
385

UNCOV
386
        $this->currentPosition = $start;
×
UNCOV
387
        throw new UnexpectedEOFException(
×
UNCOV
388
            'One of ("' . \implode('","', $stopCharacters) . '")',
×
389
            $this->peek(5),
×
UNCOV
390
            'search',
×
391
            $this->lineNumber
×
392
        );
393
    }
394

UNCOV
395
    private function inputLeft(): string
×
396
    {
UNCOV
397
        return $this->substr($this->currentPosition, -1);
×
398
    }
399

400
    public function streql(string $string1, string $string2, bool $caseInsensitive = true): bool
6✔
401
    {
402
        return $caseInsensitive
6✔
403
            ? ($this->strtolower($string1) === $this->strtolower($string2))
6✔
404
            : ($string1 === $string2);
6✔
405
    }
406

407
    /**
408
     * @param int<1, max> $numberOfCharacters
409
     */
410
    public function backtrack(int $numberOfCharacters): void
×
411
    {
UNCOV
412
        $this->currentPosition -= $numberOfCharacters;
×
UNCOV
413
    }
×
414

415
    /**
416
     * @return int<0, max>
417
     */
418
    public function strlen(string $string): int
6✔
419
    {
420
        return $this->parserSettings->hasMultibyteSupport()
6✔
421
            ? \mb_strlen($string, $this->charset)
6✔
422
            : \strlen($string);
6✔
423
    }
424

425
    /**
426
     * @param int<0, max> $offset
427
     */
428
    private function substr(int $offset, int $length): string
6✔
429
    {
430
        if ($length < 0) {
6✔
UNCOV
431
            $length = \count($this->characters) - $offset + $length;
×
432
        }
433
        if ($offset + $length > \count($this->characters)) {
6✔
434
            $length = \count($this->characters) - $offset;
6✔
435
        }
436
        $result = '';
6✔
437
        while ($length > 0) {
6✔
438
            $result .= $this->characters[$offset];
6✔
439
            $offset++;
6✔
440
            $length--;
6✔
441
        }
442

443
        return $result;
6✔
444
    }
445

446
    /**
447
     * @return ($string is non-empty-string ? non-empty-string : string)
448
     */
449
    private function strtolower(string $string): string
6✔
450
    {
451
        return $this->parserSettings->hasMultibyteSupport()
6✔
452
            ? \mb_strtolower($string, $this->charset)
6✔
453
            : \strtolower($string);
6✔
454
    }
455

456
    /**
457
     * @return list<string>
458
     */
459
    private function strsplit(string $string): array
6✔
460
    {
461
        if ($this->parserSettings->hasMultibyteSupport()) {
6✔
462
            if ($this->streql($this->charset, 'utf-8')) {
6✔
463
                $result = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);
6✔
464
            } else {
UNCOV
465
                $length = \mb_strlen($string, $this->charset);
×
UNCOV
466
                $result = [];
×
467
                for ($i = 0; $i < $length; ++$i) {
6✔
UNCOV
468
                    $result[] = \mb_substr($string, $i, 1, $this->charset);
×
469
                }
470
            }
471
        } else {
472
            $result = ($string !== '') ? \str_split($string) : [];
×
473
        }
474

475
        return $result;
6✔
476
    }
477

478
    /**
479
     * @return list<Comment>
480
     */
481
    private function consumeComments(): array
6✔
482
    {
483
        $comments = [];
6✔
484

485
        while (true) {
6✔
486
            $comment = $this->consumeComment();
6✔
487
            if ($comment instanceof Comment) {
6✔
488
                $comments[] = $comment;
6✔
489
            } else {
490
                return $comments;
6✔
491
            }
492
        }
UNCOV
493
    }
×
494
}
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