Passed
Push — phpunit-10 ( 647fc3...2c9a19 )
by Colin
11:16
created

Cursor::advanceWithoutTabCharacters()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the league/commonmark package.
7
 *
8
 * (c) Colin O'Dell <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace League\CommonMark\Parser;
15
16
use League\CommonMark\Exception\UnexpectedEncodingException;
17
18
class Cursor
19
{
20
    public const INDENT_LEVEL = 4;
21
22
    /** @psalm-readonly */
23
    private string $line;
24
25
    /** @psalm-readonly */
26
    private int $length;
27
28
    /**
29
     * @var int
30
     *
31
     * It's possible for this to be 1 char past the end, meaning we've parsed all chars and have
32
     * reached the end.  In this state, any character-returning method MUST return null.
33
     */
34
    private int $currentPosition = 0;
35
36
    private int $column = 0;
37
38
    private int $indent = 0;
39
40
    private int $previousPosition = 0;
41
42
    private ?int $nextNonSpaceCache = null;
43
44
    private bool $partiallyConsumedTab = false;
45
46
    /**
47
     * @var int|false
48
     *
49
     * @psalm-readonly
50
     */
51
    private $lastTabPosition;
52
53
    /** @psalm-readonly */
54
    private bool $isMultibyte;
55
56
    /** @var array<int, string> */
57
    private array $charCache = [];
58
59
    /**
60
     * @param string $line The line being parsed (ASCII or UTF-8)
61
     */
62 2678
    public function __construct(string $line)
63
    {
64 2678
        if (! \mb_check_encoding($line, 'UTF-8')) {
65 2
            throw new UnexpectedEncodingException('Unexpected encoding - UTF-8 or ASCII was expected');
66
        }
67
68 2676
        $this->line            = $line;
69 2676
        $this->length          = \mb_strlen($line, 'UTF-8') ?: 0;
70 2676
        $this->isMultibyte     = $this->length !== \strlen($line);
71 2676
        $this->lastTabPosition = $this->isMultibyte ? \mb_strrpos($line, "\t", 0, 'UTF-8') : \strrpos($line, "\t");
72
    }
73
74
    /**
75
     * Returns the position of the next character which is not a space (or tab)
76
     */
77 2358
    public function getNextNonSpacePosition(): int
78
    {
79 2358
        if ($this->nextNonSpaceCache !== null) {
80 2280
            return $this->nextNonSpaceCache;
81
        }
82
83 2358
        if ($this->currentPosition >= $this->length) {
84 690
            return $this->length;
85
        }
86
87 2342
        $cols = $this->column;
88
89 2342
        for ($i = $this->currentPosition; $i < $this->length; $i++) {
90
            // This if-else was copied out of getCharacter() for performance reasons
91 2342
            if ($this->isMultibyte) {
92 74
                $c = $this->charCache[$i] ??= \mb_substr($this->line, $i, 1, 'UTF-8');
93
            } else {
94 2276
                $c = $this->line[$i];
95
            }
96
97 2342
            if ($c === ' ') {
98 604
                $cols++;
99 2314
            } elseif ($c === "\t") {
100 30
                $cols += 4 - ($cols % 4);
101
            } else {
102 2314
                break;
103
            }
104
        }
105
106 2342
        $this->indent = $cols - $this->column;
107
108 2342
        return $this->nextNonSpaceCache = $i;
109
    }
110
111
    /**
112
     * Returns the next character which isn't a space (or tab)
113
     */
114 2202
    public function getNextNonSpaceCharacter(): ?string
115
    {
116 2202
        $index = $this->getNextNonSpacePosition();
117 2202
        if ($index >= $this->length) {
118 48
            return null;
119
        }
120
121 2196
        if ($this->isMultibyte) {
122 52
            return $this->charCache[$index] ??= \mb_substr($this->line, $index, 1, 'UTF-8');
123
        }
124
125 2150
        return $this->line[$index];
126
    }
127
128
    /**
129
     * Calculates the current indent (number of spaces after current position)
130
     */
131 1348
    public function getIndent(): int
132
    {
133 1348
        if ($this->nextNonSpaceCache === null) {
134 46
            $this->getNextNonSpacePosition();
135
        }
136
137 1348
        return $this->indent;
138
    }
139
140
    /**
141
     * Whether the cursor is indented to INDENT_LEVEL
142
     */
143 2238
    public function isIndented(): bool
144
    {
145 2238
        if ($this->nextNonSpaceCache === null) {
146 230
            $this->getNextNonSpacePosition();
147
        }
148
149 2238
        return $this->indent >= self::INDENT_LEVEL;
150
    }
151
152 1214
    public function getCharacter(?int $index = null): ?string
153
    {
154 1214
        if ($index === null) {
155 98
            $index = $this->currentPosition;
156
        }
157
158
        // Index out-of-bounds, or we're at the end
159 1214
        if ($index < 0 || $index >= $this->length) {
160 574
            return null;
161
        }
162
163 1154
        if ($this->isMultibyte) {
164 52
            return $this->charCache[$index] ??= \mb_substr($this->line, $index, 1, 'UTF-8');
165
        }
166
167 1102
        return $this->line[$index];
168
    }
169
170
    /**
171
     * Slightly-optimized version of getCurrent(null)
172
     */
173 1996
    public function getCurrentCharacter(): ?string
174
    {
175 1996
        if ($this->currentPosition >= $this->length) {
176 600
            return null;
177
        }
178
179 1986
        if ($this->isMultibyte) {
180 66
            return $this->charCache[$this->currentPosition] ??= \mb_substr($this->line, $this->currentPosition, 1, 'UTF-8');
181
        }
182
183 1924
        return $this->line[$this->currentPosition];
184
    }
185
186
    /**
187
     * Returns the next character (or null, if none) without advancing forwards
188
     */
189 1106
    public function peek(int $offset = 1): ?string
190
    {
191 1106
        return $this->getCharacter($this->currentPosition + $offset);
192
    }
193
194
    /**
195
     * Whether the remainder is blank
196
     */
197 2234
    public function isBlank(): bool
198
    {
199 2234
        return $this->nextNonSpaceCache === $this->length || $this->getNextNonSpacePosition() === $this->length;
200
    }
201
202
    /**
203
     * Move the cursor forwards
204
     */
205 400
    public function advance(): void
206
    {
207 400
        $this->advanceBy(1);
208
    }
209
210
    /**
211
     * Move the cursor forwards
212
     *
213
     * @param int  $characters       Number of characters to advance by
214
     * @param bool $advanceByColumns Whether to advance by columns instead of spaces
215
     */
216 2368
    public function advanceBy(int $characters, bool $advanceByColumns = false): void
217
    {
218 2368
        $this->previousPosition  = $this->currentPosition;
219 2368
        $this->nextNonSpaceCache = null;
220
221 2368
        if ($this->currentPosition >= $this->length || $characters === 0) {
222 138
            return;
223
        }
224
225
        // Optimization to avoid tab handling logic if we have no tabs
226 2300
        if ($this->lastTabPosition === false || $this->currentPosition > $this->lastTabPosition) {
227 2280
            $length                     = \min($characters, $this->length - $this->currentPosition);
228 2280
            $this->partiallyConsumedTab = false;
229 2280
            $this->currentPosition     += $length;
230 2280
            $this->column              += $length;
231
232 2280
            return;
233
        }
234
235 40
        $nextFewChars = $this->isMultibyte ?
236 4
            \mb_substr($this->line, $this->currentPosition, $characters, 'UTF-8') :
237 38
            \substr($this->line, $this->currentPosition, $characters);
238
239 40
        if ($characters === 1) {
240 14
            $asArray = [$nextFewChars];
241 34
        } elseif ($this->isMultibyte) {
242
            /** @var string[] $asArray */
243 2
            $asArray = \mb_str_split($nextFewChars, 1, 'UTF-8');
244
        } else {
245 34
            $asArray = \str_split($nextFewChars);
246
        }
247
248 40
        foreach ($asArray as $c) {
249 40
            if ($c === "\t") {
250 36
                $charsToTab = 4 - ($this->column % 4);
251 36
                if ($advanceByColumns) {
252 26
                    $this->partiallyConsumedTab = $charsToTab > $characters;
253 26
                    $charsToAdvance             = $charsToTab > $characters ? $characters : $charsToTab;
254 26
                    $this->column              += $charsToAdvance;
255 26
                    $this->currentPosition     += $this->partiallyConsumedTab ? 0 : 1;
256 26
                    $characters                -= $charsToAdvance;
257
                } else {
258 14
                    $this->partiallyConsumedTab = false;
259 14
                    $this->column              += $charsToTab;
260 14
                    $this->currentPosition++;
261 25
                    $characters--;
262
                }
263
            } else {
264 22
                $this->partiallyConsumedTab = false;
265 22
                $this->currentPosition++;
266 22
                $this->column++;
267 22
                $characters--;
268
            }
269
270 40
            if ($characters <= 0) {
271 40
                break;
272
            }
273
        }
274
    }
275
276
    /**
277
     * Advances the cursor by a single space or tab, if present
278
     */
279 292
    public function advanceBySpaceOrTab(): bool
280
    {
281 292
        $character = $this->getCurrentCharacter();
282
283 292
        if ($character === ' ' || $character === "\t") {
284 284
            $this->advanceBy(1, true);
285
286 284
            return true;
287
        }
288
289 224
        return false;
290
    }
291
292
    /**
293
     * Parse zero or more space/tab characters
294
     *
295
     * @return int Number of positions moved
296
     */
297 2184
    public function advanceToNextNonSpaceOrTab(): int
298
    {
299 2184
        $newPosition = $this->nextNonSpaceCache ?? $this->getNextNonSpacePosition();
300 2184
        if ($newPosition === $this->currentPosition) {
301 2156
            return 0;
302
        }
303
304 378
        $this->advanceBy($newPosition - $this->currentPosition);
305 378
        $this->partiallyConsumedTab = false;
306
307
        // We've just advanced to where that non-space is,
308
        // so any subsequent calls to find the next one will
309
        // always return the current position.
310 378
        $this->nextNonSpaceCache = $this->currentPosition;
311 378
        $this->indent            = 0;
312
313 378
        return $this->currentPosition - $this->previousPosition;
314
    }
315
316
    /**
317
     * Parse zero or more space characters, including at most one newline.
318
     *
319
     * Tab characters are not parsed with this function.
320
     *
321
     * @return int Number of positions moved
322
     */
323 330
    public function advanceToNextNonSpaceOrNewline(): int
324
    {
325 330
        $remainder = $this->getRemainder();
326
327
        // Optimization: Avoid the regex if we know there are no spaces or newlines
328 330
        if ($remainder === '' || ($remainder[0] !== ' ' && $remainder[0] !== "\n")) {
329 298
            $this->previousPosition = $this->currentPosition;
330
331 298
            return 0;
332
        }
333
334 82
        $matches = [];
335 82
        \preg_match('/^ *(?:\n *)?/', $remainder, $matches, \PREG_OFFSET_CAPTURE);
336
337
        // [0][0] contains the matched text
338
        // [0][1] contains the index of that match
339 82
        $increment = $matches[0][1] + \strlen($matches[0][0]);
340
341 82
        $this->advanceBy($increment);
342
343 82
        return $this->currentPosition - $this->previousPosition;
344
    }
345
346
    /**
347
     * Move the position to the very end of the line
348
     *
349
     * @return int The number of characters moved
350
     */
351 748
    public function advanceToEnd(): int
352
    {
353 748
        $this->previousPosition  = $this->currentPosition;
354 748
        $this->nextNonSpaceCache = null;
355
356 748
        $this->currentPosition = $this->length;
357
358 748
        return $this->currentPosition - $this->previousPosition;
359
    }
360
361 2416
    public function getRemainder(): string
362
    {
363 2416
        if ($this->currentPosition >= $this->length) {
364 536
            return '';
365
        }
366
367 2400
        $prefix   = '';
368 2400
        $position = $this->currentPosition;
369 2400
        if ($this->partiallyConsumedTab) {
370 8
            $position++;
371 8
            $charsToTab = 4 - ($this->column % 4);
372 8
            $prefix     = \str_repeat(' ', $charsToTab);
373
        }
374
375 2400
        $subString = $this->isMultibyte ?
376 70
            \mb_substr($this->line, $position, null, 'UTF-8') :
377 2338
            \substr($this->line, $position);
378
379 2400
        return $prefix . $subString;
380
    }
381
382 1352
    public function getLine(): string
383
    {
384 1352
        return $this->line;
385
    }
386
387 2040
    public function isAtEnd(): bool
388
    {
389 2040
        return $this->currentPosition >= $this->length;
390
    }
391
392
    /**
393
     * Try to match a regular expression
394
     *
395
     * Returns the matching text and advances to the end of that match
396
     *
397
     * @psalm-param non-empty-string $regex
398
     */
399 834
    public function match(string $regex): ?string
400
    {
401 834
        $subject = $this->getRemainder();
402
403 834
        if (! \preg_match($regex, $subject, $matches, \PREG_OFFSET_CAPTURE)) {
404 602
            return null;
405
        }
406
407
        // $matches[0][0] contains the matched text
408
        // $matches[0][1] contains the index of that match
409
410 698
        if ($this->isMultibyte) {
411
            // PREG_OFFSET_CAPTURE always returns the byte offset, not the char offset, which is annoying
412 20
            $offset      = \mb_strlen(\substr($subject, 0, $matches[0][1]), 'UTF-8');
413 20
            $matchLength = \mb_strlen($matches[0][0], 'UTF-8');
414
        } else {
415 680
            $offset      = $matches[0][1];
416 680
            $matchLength = \strlen($matches[0][0]);
417
        }
418
419
        // [0][0] contains the matched text
420
        // [0][1] contains the index of that match
421 698
        $this->advanceBy($offset + $matchLength);
422
423 698
        return $matches[0][0];
424
    }
425
426
    /**
427
     * Encapsulates the current state of this cursor in case you need to rollback later.
428
     *
429
     * WARNING: Do not parse or use the return value for ANYTHING except for
430
     * passing it back into restoreState(), as the number of values and their
431
     * contents may change in any future release without warning.
432
     */
433 1520
    public function saveState(): CursorState
434
    {
435 1520
        return new CursorState([
436 1520
            $this->currentPosition,
437 1520
            $this->previousPosition,
438 1520
            $this->nextNonSpaceCache,
439 1520
            $this->indent,
440 1520
            $this->column,
441 1520
            $this->partiallyConsumedTab,
442 1520
        ]);
443
    }
444
445
    /**
446
     * Restore the cursor to a previous state.
447
     *
448
     * Pass in the value previously obtained by calling saveState().
449
     */
450 1384
    public function restoreState(CursorState $state): void
451
    {
452 1384
        [
453 1384
            $this->currentPosition,
454 1384
            $this->previousPosition,
455 1384
            $this->nextNonSpaceCache,
456 1384
            $this->indent,
457 1384
            $this->column,
458 1384
            $this->partiallyConsumedTab,
459 1384
        ] = $state->toArray();
460
    }
461
462 1730
    public function getPosition(): int
463
    {
464 1730
        return $this->currentPosition;
465
    }
466
467 1362
    public function getPreviousText(): string
468
    {
469 1362
        if ($this->isMultibyte) {
470 42
            return \mb_substr($this->line, $this->previousPosition, $this->currentPosition - $this->previousPosition, 'UTF-8');
471
        }
472
473 1322
        return \substr($this->line, $this->previousPosition, $this->currentPosition - $this->previousPosition);
474
    }
475
476 318
    public function getSubstring(int $start, ?int $length = null): string
477
    {
478 318
        if ($this->isMultibyte) {
479 14
            return \mb_substr($this->line, $start, $length, 'UTF-8');
480
        }
481
482 304
        if ($length !== null) {
483 302
            return \substr($this->line, $start, $length);
484
        }
485
486 2
        return \substr($this->line, $start);
487
    }
488
489 214
    public function getColumn(): int
490
    {
491 214
        return $this->column;
492
    }
493
}
494