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

MyIntervals / PHP-CSS-Parser / 20130871357

11 Dec 2025 11:01AM UTC coverage: 62.729% (-0.3%) from 63.014%
20130871357

Pull #1420

github

web-flow
Merge 26ac2f244 into 8d123a220
Pull Request #1420: [CLEANUP] Extract method `DeclarationBlock::parseSelector`

15 of 26 new or added lines in 2 files covered. (57.69%)

51 existing lines in 1 file now uncovered.

1200 of 1913 relevant lines covered (62.73%)

30.86 hits per line

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

0.0
/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)
×
58
    {
59
        $this->parserSettings = $parserSettings;
×
60
        $this->text = $text;
×
61
        $this->lineNumber = $lineNumber;
×
62
        $this->setCharset($this->parserSettings->getDefaultCharset());
×
63
    }
×
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
×
69
    {
70
        $this->charset = $charset;
×
71
        $this->characters = $this->strsplit($this->text);
×
72
    }
×
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
×
225
    {
226
        $peek = $this->peek(\strlen($string));
×
227

228
        return ($peek !== '') && $this->streql($peek, $string, $caseInsensitive);
×
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
×
236
    {
237
        $offset += $this->currentPosition;
×
238
        if ($offset >= \count($this->characters)) {
×
239
            return '';
×
240
        }
241

242
        return $this->substr($offset, $length);
×
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
×
252
    {
253
        if (\is_string($value)) {
×
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)) {
×
270
                throw new UnexpectedEOFException((string) $value, $this->peek(5), 'count', $this->lineNumber);
×
271
            }
272

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

279
        return $result;
×
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
     */
310
    public function consumeExpression(string $expression, ?int $maximumLength = null): string
×
311
    {
312
        $matches = null;
×
313
        $input = ($maximumLength !== null) ? $this->peek($maximumLength) : $this->inputLeft();
×
314
        if (preg_match($expression, $input, $matches, PREG_OFFSET_CAPTURE) !== 1) {
×
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()
×
325
    {
326
        $lineNumber = $this->lineNumber;
×
UNCOV
327
        $comment = null;
×
328

UNCOV
329
        if ($this->comes('/*')) {
×
UNCOV
330
            $this->consume(1);
×
UNCOV
331
            $comment = '';
×
UNCOV
332
            while (($char = $this->consume(1)) !== '') {
×
UNCOV
333
                $comment .= $char;
×
UNCOV
334
                if ($this->comes('*/')) {
×
UNCOV
335
                    $this->consume(2);
×
336
                    break;
×
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;
×
343
    }
344

UNCOV
345
    public function isEnd(): bool
×
346
    {
347
        return $this->currentPosition >= \count($this->characters);
×
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(
×
358
        $stopCharacters,
359
        bool $includeEnd = false,
360
        bool $consumeEnd = false,
361
        array &$comments = []
362
    ): string {
363
        $stopCharacters = \is_array($stopCharacters) ? $stopCharacters : [$stopCharacters];
×
364
        $consumedCharacters = '';
×
UNCOV
365
        $start = $this->currentPosition;
×
366

NEW
367
        $comment = $this->consumeComment();
×
NEW
368
        if ($comment instanceof Comment) {
×
NEW
369
            $comments[] = $comment;
×
370
        }
371
        while (!$this->isEnd()) {
×
372
            $character = $this->consume(1);
×
UNCOV
373
            if (\in_array($character, $stopCharacters, true)) {
×
UNCOV
374
                if ($includeEnd) {
×
UNCOV
375
                    $consumedCharacters .= $character;
×
376
                } elseif (!$consumeEnd) {
×
UNCOV
377
                    $this->currentPosition -= $this->strlen($character);
×
378
                }
UNCOV
379
                return $consumedCharacters;
×
380
            }
381
            $consumedCharacters .= $character;
×
UNCOV
382
            $comment = $this->consumeComment();
×
383
            if ($comment instanceof Comment) {
×
384
                $comments[] = $comment;
×
385
            }
386
        }
387

UNCOV
388
        if (\in_array(self::EOF, $stopCharacters, true)) {
×
UNCOV
389
            return $consumedCharacters;
×
390
        }
391

UNCOV
392
        $this->currentPosition = $start;
×
393
        throw new UnexpectedEOFException(
×
394
            'One of ("' . \implode('","', $stopCharacters) . '")',
×
UNCOV
395
            $this->peek(5),
×
UNCOV
396
            'search',
×
UNCOV
397
            $this->lineNumber
×
398
        );
399
    }
400

401
    private function inputLeft(): string
×
402
    {
403
        return $this->substr($this->currentPosition, -1);
×
404
    }
405

UNCOV
406
    public function streql(string $string1, string $string2, bool $caseInsensitive = true): bool
×
407
    {
UNCOV
408
        return $caseInsensitive
×
409
            ? ($this->strtolower($string1) === $this->strtolower($string2))
×
UNCOV
410
            : ($string1 === $string2);
×
411
    }
412

413
    /**
414
     * @param int<1, max> $numberOfCharacters
415
     */
UNCOV
416
    public function backtrack(int $numberOfCharacters): void
×
417
    {
418
        $this->currentPosition -= $numberOfCharacters;
×
419
    }
×
420

421
    /**
422
     * @return int<0, max>
423
     */
424
    public function strlen(string $string): int
×
425
    {
UNCOV
426
        return $this->parserSettings->hasMultibyteSupport()
×
UNCOV
427
            ? \mb_strlen($string, $this->charset)
×
UNCOV
428
            : \strlen($string);
×
429
    }
430

431
    /**
432
     * @param int<0, max> $offset
433
     */
434
    private function substr(int $offset, int $length): string
×
435
    {
UNCOV
436
        if ($length < 0) {
×
UNCOV
437
            $length = \count($this->characters) - $offset + $length;
×
438
        }
UNCOV
439
        if ($offset + $length > \count($this->characters)) {
×
440
            $length = \count($this->characters) - $offset;
×
441
        }
442
        $result = '';
×
443
        while ($length > 0) {
×
444
            $result .= $this->characters[$offset];
×
UNCOV
445
            $offset++;
×
446
            $length--;
×
447
        }
448

449
        return $result;
×
450
    }
451

452
    /**
453
     * @return ($string is non-empty-string ? non-empty-string : string)
454
     */
UNCOV
455
    private function strtolower(string $string): string
×
456
    {
UNCOV
457
        return $this->parserSettings->hasMultibyteSupport()
×
UNCOV
458
            ? \mb_strtolower($string, $this->charset)
×
UNCOV
459
            : \strtolower($string);
×
460
    }
461

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

UNCOV
481
        return $result;
×
482
    }
483
}
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