Passed
Pull Request — main (#961)
by Colin
04:38 queued 02:21
created

Cursor::advanceToNextNonSpaceOrTab()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 8
c 0
b 0
f 0
dl 0
loc 17
ccs 9
cts 9
cp 1
rs 10
cc 2
nc 2
nop 0
crap 2
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 2646
    public function __construct(string $line)
63
    {
64 2646
        if (! \mb_check_encoding($line, 'UTF-8')) {
65 2
            throw new UnexpectedEncodingException('Unexpected encoding - UTF-8 or ASCII was expected');
66
        }
67
68 2644
        $this->line            = $line;
69 2644
        $this->length          = \mb_strlen($line, 'UTF-8') ?: 0;
70 2644
        $this->isMultibyte     = $this->length !== \strlen($line);
71 2644
        $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 2326
    public function getNextNonSpacePosition(): int
78
    {
79 2326
        if ($this->nextNonSpaceCache !== null) {
80 2248
            return $this->nextNonSpaceCache;
81
        }
82
83 2326
        if ($this->currentPosition >= $this->length) {
84 690
            return $this->length;
85
        }
86
87 2310
        $cols = $this->column;
88
89 2310
        for ($i = $this->currentPosition; $i < $this->length; $i++) {
90
            // This if-else was copied out of getCharacter() for performance reasons
91 2310
            if ($this->isMultibyte) {
92 74
                $c = $this->charCache[$i] ??= \mb_substr($this->line, $i, 1, 'UTF-8');
93
            } else {
94 2244
                $c = $this->line[$i];
95
            }
96
97 2310
            if ($c === ' ') {
98 604
                $cols++;
99 2282
            } elseif ($c === "\t") {
100 30
                $cols += 4 - ($cols % 4);
101
            } else {
102 2282
                break;
103
            }
104
        }
105
106 2310
        $this->indent = $cols - $this->column;
107
108 2310
        return $this->nextNonSpaceCache = $i;
109
    }
110
111
    /**
112
     * Returns the next character which isn't a space (or tab)
113
     */
114 2170
    public function getNextNonSpaceCharacter(): ?string
115
    {
116 2170
        $index = $this->getNextNonSpacePosition();
117 2170
        if ($index >= $this->length) {
118 48
            return null;
119
        }
120
121 2164
        if ($this->isMultibyte) {
122 52
            return $this->charCache[$index] ??= \mb_substr($this->line, $index, 1, 'UTF-8');
123
        }
124
125 2118
        return $this->line[$index];
126
    }
127
128
    /**
129
     * Calculates the current indent (number of spaces after current position)
130
     */
131 1328
    public function getIndent(): int
132
    {
133 1328
        if ($this->nextNonSpaceCache === null) {
134 46
            $this->getNextNonSpacePosition();
135
        }
136
137 1328
        return $this->indent;
138
    }
139
140
    /**
141
     * Whether the cursor is indented to INDENT_LEVEL
142
     */
143 2206
    public function isIndented(): bool
144
    {
145 2206
        if ($this->nextNonSpaceCache === null) {
146 230
            $this->getNextNonSpacePosition();
147
        }
148
149 2206
        return $this->indent >= self::INDENT_LEVEL;
150
    }
151
152 1186
    public function getCharacter(?int $index = null): ?string
153
    {
154 1186
        if ($index === null) {
155 98
            $index = $this->currentPosition;
156
        }
157
158
        // Index out-of-bounds, or we're at the end
159 1186
        if ($index < 0 || $index >= $this->length) {
160 548
            return null;
161
        }
162
163 1126
        if ($this->isMultibyte) {
164 52
            return $this->charCache[$index] ??= \mb_substr($this->line, $index, 1, 'UTF-8');
165
        }
166
167 1074
        return $this->line[$index];
168
    }
169
170
    /**
171
     * Slightly-optimized version of getCurrent(null)
172
     */
173 1966
    public function getCurrentCharacter(): ?string
174
    {
175 1966
        if ($this->currentPosition >= $this->length) {
176 580
            return null;
177
        }
178
179 1956
        if ($this->isMultibyte) {
180 66
            return $this->charCache[$this->currentPosition] ??= \mb_substr($this->line, $this->currentPosition, 1, 'UTF-8');
181
        }
182
183 1894
        return $this->line[$this->currentPosition];
184
    }
185
186
    /**
187
     * Returns the next character (or null, if none) without advancing forwards
188
     */
189 1078
    public function peek(int $offset = 1): ?string
190
    {
191 1078
        return $this->getCharacter($this->currentPosition + $offset);
192
    }
193
194
    /**
195
     * Whether the remainder is blank
196
     */
197 2202
    public function isBlank(): bool
198
    {
199 2202
        return $this->nextNonSpaceCache === $this->length || $this->getNextNonSpacePosition() === $this->length;
200
    }
201
202
    /**
203
     * Move the cursor forwards
204
     */
205 404
    public function advance(): void
206
    {
207 404
        $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 2338
    public function advanceBy(int $characters, bool $advanceByColumns = false): void
217
    {
218 2338
        $this->previousPosition  = $this->currentPosition;
219 2338
        $this->nextNonSpaceCache = null;
220
221 2338
        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 2270
        if ($this->lastTabPosition === false || $this->currentPosition > $this->lastTabPosition) {
227 2250
            $length                     = \min($characters, $this->length - $this->currentPosition);
228 2250
            $this->partiallyConsumedTab = false;
229 2250
            $this->currentPosition     += $length;
230 2250
            $this->column              += $length;
231
232 2250
            return;
233
        }
234
235 40
        $nextFewChars = $this->isMultibyte ?
236 4
            \mb_substr($this->line, $this->currentPosition, $characters, 'UTF-8') :
237 39
            \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 36
                    $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 290
    public function advanceBySpaceOrTab(): bool
280
    {
281 290
        $character = $this->getCurrentCharacter();
282
283 290
        if ($character === ' ' || $character === "\t") {
284 282
            $this->advanceBy(1, true);
285
286 282
            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 2152
    public function advanceToNextNonSpaceOrTab(): int
298
    {
299 2152
        $newPosition = $this->nextNonSpaceCache ?? $this->getNextNonSpacePosition();
300 2152
        if ($newPosition === $this->currentPosition) {
301 2124
            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 326
    public function advanceToNextNonSpaceOrNewline(): int
324
    {
325 326
        $remainder = $this->getRemainder();
326
327
        // Optimization: Avoid the regex if we know there are no spaces or newlines
328 326
        if ($remainder === '' || ($remainder[0] !== ' ' && $remainder[0] !== "\n")) {
329 294
            $this->previousPosition = $this->currentPosition;
330
331 294
            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 2384
    public function getRemainder(): string
362
    {
363 2384
        if ($this->currentPosition >= $this->length) {
364 536
            return '';
365
        }
366
367 2368
        $prefix   = '';
368 2368
        $position = $this->currentPosition;
369 2368
        if ($this->partiallyConsumedTab) {
370 8
            $position++;
371 8
            $charsToTab = 4 - ($this->column % 4);
372 8
            $prefix     = \str_repeat(' ', $charsToTab);
373
        }
374
375 2368
        $subString = $this->isMultibyte ?
376 70
            \mb_substr($this->line, $position, null, 'UTF-8') :
377 2337
            \substr($this->line, $position);
378
379 2368
        return $prefix . $subString;
380
    }
381
382 1332
    public function getLine(): string
383
    {
384 1332
        return $this->line;
385
    }
386
387 2010
    public function isAtEnd(): bool
388
    {
389 2010
        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 812
    public function match(string $regex): ?string
398
    {
399 812
        $subject = $this->getRemainder();
400
401 812
        if (! \preg_match($regex, $subject, $matches, \PREG_OFFSET_CAPTURE)) {
402 580
            return null;
403
        }
404
405
        // $matches[0][0] contains the matched text
406
        // $matches[0][1] contains the index of that match
407
408 698
        if ($this->isMultibyte) {
409
            // PREG_OFFSET_CAPTURE always returns the byte offset, not the char offset, which is annoying
410 20
            $offset      = \mb_strlen(\substr($subject, 0, $matches[0][1]), 'UTF-8');
411 20
            $matchLength = \mb_strlen($matches[0][0], 'UTF-8');
412
        } else {
413 680
            $offset      = $matches[0][1];
414 680
            $matchLength = \strlen($matches[0][0]);
415
        }
416
417
        // [0][0] contains the matched text
418
        // [0][1] contains the index of that match
419 698
        $this->advanceBy($offset + $matchLength);
420
421 698
        return $matches[0][0];
422
    }
423
424
    /**
425
     * Encapsulates the current state of this cursor in case you need to rollback later.
426
     *
427
     * WARNING: Do not parse or use the return value for ANYTHING except for
428
     * passing it back into restoreState(), as the number of values and their
429
     * contents may change in any future release without warning.
430
     */
431 1512
    public function saveState(): CursorState
432
    {
433 1512
        return new CursorState([
434 1512
            $this->currentPosition,
435 1512
            $this->previousPosition,
436 1512
            $this->nextNonSpaceCache,
437 1512
            $this->indent,
438 1512
            $this->column,
439 1512
            $this->partiallyConsumedTab,
440 1512
        ]);
441
    }
442
443
    /**
444
     * Restore the cursor to a previous state.
445
     *
446
     * Pass in the value previously obtained by calling saveState().
447
     */
448 1376
    public function restoreState(CursorState $state): void
449
    {
450 1376
        [
451 1376
            $this->currentPosition,
452 1376
            $this->previousPosition,
453 1376
            $this->nextNonSpaceCache,
454 1376
            $this->indent,
455 1376
            $this->column,
456 1376
            $this->partiallyConsumedTab,
457 1376
        ] = $state->toArray();
458
    }
459
460 1700
    public function getPosition(): int
461
    {
462 1700
        return $this->currentPosition;
463
    }
464
465 1334
    public function getPreviousText(): string
466
    {
467 1334
        return \mb_substr($this->line, $this->previousPosition, $this->currentPosition - $this->previousPosition, 'UTF-8');
468
    }
469
470 318
    public function getSubstring(int $start, ?int $length = null): string
471
    {
472 318
        if ($this->isMultibyte) {
473 14
            return \mb_substr($this->line, $start, $length, 'UTF-8');
474
        }
475
476 304
        if ($length !== null) {
477 302
            return \substr($this->line, $start, $length);
478
        }
479
480 2
        return \substr($this->line, $start);
481
    }
482
483 214
    public function getColumn(): int
484
    {
485 214
        return $this->column;
486
    }
487
}
488