Tokens::isAllTokenKindsFound()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 9
rs 10
cc 3
nc 3
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of PHP CS Fixer.
7
 *
8
 * (c) Fabien Potencier <[email protected]>
9
 *     Dariusz Rumiński <[email protected]>
10
 *
11
 * This source file is subject to the MIT license that is bundled
12
 * with this source code in the file LICENSE.
13
 */
14
15
namespace PhpCsFixer\Tokenizer;
16
17
use PhpCsFixer\Preg;
18
19
/**
20
 * Collection of code tokens.
21
 *
22
 * Its role is to provide the ability to manage collection and navigate through it.
23
 *
24
 * As a token prototype you should understand a single element generated by token_get_all.
25
 *
26
 * @author Dariusz Rumiński <[email protected]>
27
 *
28
 * @extends \SplFixedArray<Token>
29
 *
30
 * @final
31
 */
32
class Tokens extends \SplFixedArray
33
{
34
    public const BLOCK_TYPE_PARENTHESIS_BRACE = 1;
35
    public const BLOCK_TYPE_CURLY_BRACE = 2;
36
    public const BLOCK_TYPE_INDEX_SQUARE_BRACE = 3;
37
    public const BLOCK_TYPE_ARRAY_SQUARE_BRACE = 4;
38
    public const BLOCK_TYPE_DYNAMIC_PROP_BRACE = 5;
39
    public const BLOCK_TYPE_DYNAMIC_VAR_BRACE = 6;
40
    public const BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE = 7;
41
    public const BLOCK_TYPE_GROUP_IMPORT_BRACE = 8;
42
    public const BLOCK_TYPE_DESTRUCTURING_SQUARE_BRACE = 9;
43
    public const BLOCK_TYPE_BRACE_CLASS_INSTANTIATION = 10;
44
    public const BLOCK_TYPE_ATTRIBUTE = 11;
45
46
    /**
47
     * Static class cache.
48
     *
49
     * @var array
50
     */
51
    private static $cache = [];
52
53
    /**
54
     * Cache of block starts. Any change in collection will invalidate it.
55
     *
56
     * @var array<int, int>
57
     */
58
    private $blockStartCache = [];
59
60
    /**
61
     * Cache of block ends. Any change in collection will invalidate it.
62
     *
63
     * @var array<int, int>
64
     */
65
    private $blockEndCache = [];
66
67
    /**
68
     * crc32 hash of code string.
69
     *
70
     * @var string
71
     */
72
    private $codeHash;
73
74
    /**
75
     * Flag is collection was changed.
76
     *
77
     * It doesn't know about change of collection's items. To check it run `isChanged` method.
78
     *
79
     * @var bool
80
     */
81
    private $changed = false;
82
83
    /**
84
     * Set of found token kinds.
85
     *
86
     * When the token kind is present in this set it means that given token kind
87
     * was ever seen inside the collection (but may not be part of it any longer).
88
     * The key is token kind and the value is always true.
89
     *
90
     * @var array<int|string, int>
91
     */
92
    private $foundTokenKinds = [];
93
94
    /**
95
     * Clone tokens collection.
96
     */
97
    public function __clone()
98
    {
99
        foreach ($this as $key => $val) {
100
            $this[$key] = clone $val;
101
        }
102
    }
103
104
    /**
105
     * Clear cache - one position or all of them.
106
     *
107
     * @param null|string $key position to clear, when null clear all
108
     */
109
    public static function clearCache(?string $key = null): void
110
    {
111
        if (null === $key) {
112
            self::$cache = [];
113
114
            return;
115
        }
116
117
        if (self::hasCache($key)) {
118
            unset(self::$cache[$key]);
119
        }
120
    }
121
122
    /**
123
     * Detect type of block.
124
     *
125
     * @param Token $token token
126
     *
127
     * @return null|array array with 'type' and 'isStart' keys or null if not found
128
     */
129
    public static function detectBlockType(Token $token): ?array
130
    {
131
        foreach (self::getBlockEdgeDefinitions() as $type => $definition) {
132
            if ($token->equals($definition['start'])) {
133
                return ['type' => $type, 'isStart' => true];
134
            }
135
136
            if ($token->equals($definition['end'])) {
137
                return ['type' => $type, 'isStart' => false];
138
            }
139
        }
140
141
        return null;
142
    }
143
144
    /**
145
     * Create token collection from array.
146
     *
147
     * @param Token[] $array       the array to import
148
     * @param ?bool   $saveIndexes save the numeric indexes used in the original array, default is yes
149
     */
150
    public static function fromArray($array, $saveIndexes = null): self
151
    {
152
        $tokens = new self(\count($array));
153
154
        if (null === $saveIndexes || $saveIndexes) {
155
            foreach ($array as $key => $val) {
156
                $tokens[$key] = $val;
157
            }
158
        } else {
159
            $index = 0;
160
161
            foreach ($array as $val) {
162
                $tokens[$index++] = $val;
163
            }
164
        }
165
166
        $tokens->generateCode(); // regenerate code to calculate code hash
167
        $tokens->clearChanged();
168
169
        return $tokens;
170
    }
171
172
    /**
173
     * Create token collection directly from code.
174
     *
175
     * @param string $code PHP code
176
     */
177
    public static function fromCode(string $code): self
178
    {
179
        $codeHash = self::calculateCodeHash($code);
180
181
        if (self::hasCache($codeHash)) {
182
            $tokens = self::getCache($codeHash);
183
184
            // generate the code to recalculate the hash
185
            $tokens->generateCode();
186
187
            if ($codeHash === $tokens->codeHash) {
188
                $tokens->clearEmptyTokens();
189
                $tokens->clearChanged();
190
191
                return $tokens;
192
            }
193
        }
194
195
        $tokens = new self();
196
        $tokens->setCode($code);
197
        $tokens->clearChanged();
198
199
        return $tokens;
200
    }
201
202
    public static function getBlockEdgeDefinitions(): array
203
    {
204
        $definitions = [
205
            self::BLOCK_TYPE_CURLY_BRACE => [
206
                'start' => '{',
207
                'end' => '}',
208
            ],
209
            self::BLOCK_TYPE_PARENTHESIS_BRACE => [
210
                'start' => '(',
211
                'end' => ')',
212
            ],
213
            self::BLOCK_TYPE_INDEX_SQUARE_BRACE => [
214
                'start' => '[',
215
                'end' => ']',
216
            ],
217
            self::BLOCK_TYPE_ARRAY_SQUARE_BRACE => [
218
                'start' => [CT::T_ARRAY_SQUARE_BRACE_OPEN, '['],
219
                'end' => [CT::T_ARRAY_SQUARE_BRACE_CLOSE, ']'],
220
            ],
221
            self::BLOCK_TYPE_DYNAMIC_PROP_BRACE => [
222
                'start' => [CT::T_DYNAMIC_PROP_BRACE_OPEN, '{'],
223
                'end' => [CT::T_DYNAMIC_PROP_BRACE_CLOSE, '}'],
224
            ],
225
            self::BLOCK_TYPE_DYNAMIC_VAR_BRACE => [
226
                'start' => [CT::T_DYNAMIC_VAR_BRACE_OPEN, '{'],
227
                'end' => [CT::T_DYNAMIC_VAR_BRACE_CLOSE, '}'],
228
            ],
229
            self::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE => [
230
                'start' => [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, '{'],
231
                'end' => [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE, '}'],
232
            ],
233
            self::BLOCK_TYPE_GROUP_IMPORT_BRACE => [
234
                'start' => [CT::T_GROUP_IMPORT_BRACE_OPEN, '{'],
235
                'end' => [CT::T_GROUP_IMPORT_BRACE_CLOSE, '}'],
236
            ],
237
            self::BLOCK_TYPE_DESTRUCTURING_SQUARE_BRACE => [
238
                'start' => [CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, '['],
239
                'end' => [CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, ']'],
240
            ],
241
            self::BLOCK_TYPE_BRACE_CLASS_INSTANTIATION => [
242
                'start' => [CT::T_BRACE_CLASS_INSTANTIATION_OPEN, '('],
243
                'end' => [CT::T_BRACE_CLASS_INSTANTIATION_CLOSE, ')'],
244
            ],
245
        ];
246
247
        // @TODO: drop condition when PHP 8.0+ is required
248
        if (\defined('T_ATTRIBUTE')) {
249
            $definitions[self::BLOCK_TYPE_ATTRIBUTE] = [
250
                'start' => [T_ATTRIBUTE, '#['],
251
                'end' => [CT::T_ATTRIBUTE_CLOSE, ']'],
252
            ];
253
        }
254
255
        return $definitions;
256
    }
257
258
    /**
259
     * Set new size of collection.
260
     *
261
     * @param int $size
262
     */
263
    public function setSize($size): bool
264
    {
265
        if ($this->getSize() !== $size) {
266
            $this->changed = true;
267
268
            return parent::setSize($size);
269
        }
270
271
        return true;
272
    }
273
274
    /**
275
     * Unset collection item.
276
     *
277
     * @param int $index
278
     */
279
    public function offsetUnset($index): void
280
    {
281
        $this->changed = true;
282
        $this->unregisterFoundToken($this[$index]);
283
        parent::offsetUnset($index);
284
    }
285
286
    /**
287
     * Set collection item.
288
     *
289
     * Warning! `$newval` must not be typehinted to be compatible with `ArrayAccess::offsetSet` method.
290
     *
291
     * @param int   $index
292
     * @param Token $newval
293
     */
294
    public function offsetSet($index, $newval): void
295
    {
296
        $this->blockStartCache = [];
297
        $this->blockEndCache = [];
298
299
        if (!isset($this[$index]) || !$this[$index]->equals($newval)) {
300
            $this->changed = true;
301
302
            if (isset($this[$index])) {
303
                $this->unregisterFoundToken($this[$index]);
304
            }
305
306
            $this->registerFoundToken($newval);
307
        }
308
309
        parent::offsetSet($index, $newval);
310
    }
311
312
    /**
313
     * Clear internal flag if collection was changed and flag for all collection's items.
314
     */
315
    public function clearChanged(): void
316
    {
317
        $this->changed = false;
318
    }
319
320
    /**
321
     * Clear empty tokens.
322
     *
323
     * Empty tokens can occur e.g. after calling clear on item of collection.
324
     */
325
    public function clearEmptyTokens(): void
326
    {
327
        $limit = $this->count();
328
        $index = 0;
329
330
        for (; $index < $limit; ++$index) {
331
            if ($this->isEmptyAt($index)) {
332
                break;
333
            }
334
        }
335
336
        // no empty token found, therefore there is no need to override collection
337
        if ($limit === $index) {
338
            return;
339
        }
340
341
        for ($count = $index; $index < $limit; ++$index) {
342
            if (!$this->isEmptyAt($index)) {
343
                $this[$count++] = $this[$index]; // @phpstan-ignore-line as we know that index exists
344
            }
345
        }
346
347
        $this->setSize($count);
348
    }
349
350
    /**
351
     * Ensure that on given index is a whitespace with given kind.
352
     *
353
     * If there is a whitespace then it's content will be modified.
354
     * If not - the new Token will be added.
355
     *
356
     * @param int    $index       index
357
     * @param int    $indexOffset index offset for Token insertion
358
     * @param string $whitespace  whitespace to set
359
     *
360
     * @return bool if new Token was added
361
     */
362
    public function ensureWhitespaceAtIndex(int $index, int $indexOffset, string $whitespace): bool
363
    {
364
        $removeLastCommentLine = static function (self $tokens, int $index, int $indexOffset, string $whitespace): string {
365
            $token = $tokens[$index];
366
367
            if (1 === $indexOffset && $token->isGivenKind(T_OPEN_TAG)) {
368
                if (0 === strpos($whitespace, "\r\n")) {
369
                    $tokens[$index] = new Token([T_OPEN_TAG, rtrim($token->getContent())."\r\n"]);
370
371
                    return \strlen($whitespace) > 2 // can be removed on PHP 7; https://php.net/manual/en/function.substr.php
372
                        ? substr($whitespace, 2)
373
                        : ''
374
                    ;
375
                }
376
377
                $tokens[$index] = new Token([T_OPEN_TAG, rtrim($token->getContent()).$whitespace[0]]);
378
379
                return \strlen($whitespace) > 1 // can be removed on PHP 7; https://php.net/manual/en/function.substr.php
380
                    ? substr($whitespace, 1)
381
                    : ''
382
                ;
383
            }
384
385
            return $whitespace;
386
        };
387
388
        if ($this[$index]->isWhitespace()) {
389
            $whitespace = $removeLastCommentLine($this, $index - 1, $indexOffset, $whitespace);
390
391
            if ('' === $whitespace) {
392
                $this->clearAt($index);
393
            } else {
394
                $this[$index] = new Token([T_WHITESPACE, $whitespace]);
395
            }
396
397
            return false;
398
        }
399
400
        $whitespace = $removeLastCommentLine($this, $index, $indexOffset, $whitespace);
401
402
        if ('' === $whitespace) {
403
            return false;
404
        }
405
406
        $this->insertAt(
407
            $index + $indexOffset,
408
            [new Token([T_WHITESPACE, $whitespace])]
409
        );
410
411
        return true;
412
    }
413
414
    /**
415
     * @param int $type        type of block, one of BLOCK_TYPE_*
416
     * @param int $searchIndex index of opening brace
417
     *
418
     * @return int index of closing brace
419
     */
420
    public function findBlockEnd(int $type, int $searchIndex): int
421
    {
422
        return $this->findOppositeBlockEdge($type, $searchIndex, true);
423
    }
424
425
    /**
426
     * @param int $type        type of block, one of BLOCK_TYPE_*
427
     * @param int $searchIndex index of closing brace
428
     *
429
     * @return int index of opening brace
430
     */
431
    public function findBlockStart(int $type, int $searchIndex): int
432
    {
433
        return $this->findOppositeBlockEdge($type, $searchIndex, false);
434
    }
435
436
    /**
437
     * @param array|int $possibleKind kind or array of kind
438
     * @param int       $start        optional offset
439
     * @param null|int  $end          optional limit
440
     *
441
     * @return array array of tokens of given kinds or assoc array of arrays
442
     */
443
    public function findGivenKind($possibleKind, int $start = 0, ?int $end = null): array
444
    {
445
        if (null === $end) {
446
            $end = $this->count();
447
        }
448
449
        $elements = [];
450
        $possibleKinds = (array) $possibleKind;
451
452
        foreach ($possibleKinds as $kind) {
453
            $elements[$kind] = [];
454
        }
455
456
        $possibleKinds = array_filter($possibleKinds, function ($kind) {
457
            return $this->isTokenKindFound($kind);
458
        });
459
460
        if (\count($possibleKinds)) {
461
            for ($i = $start; $i < $end; ++$i) {
462
                $token = $this[$i];
463
                if ($token->isGivenKind($possibleKinds)) {
464
                    $elements[$token->getId()][$i] = $token;
465
                }
466
            }
467
        }
468
469
        return \is_array($possibleKind) ? $elements : $elements[$possibleKind];
470
    }
471
472
    public function generateCode(): string
473
    {
474
        $code = $this->generatePartialCode(0, \count($this) - 1);
475
        $this->changeCodeHash(self::calculateCodeHash($code));
476
477
        return $code;
478
    }
479
480
    /**
481
     * Generate code from tokens between given indexes.
482
     *
483
     * @param int $start start index
484
     * @param int $end   end index
485
     */
486
    public function generatePartialCode(int $start, int $end): string
487
    {
488
        $code = '';
489
490
        for ($i = $start; $i <= $end; ++$i) {
491
            $code .= $this[$i]->getContent();
492
        }
493
494
        return $code;
495
    }
496
497
    /**
498
     * Get hash of code.
499
     */
500
    public function getCodeHash(): string
501
    {
502
        return $this->codeHash;
503
    }
504
505
    /**
506
     * Get index for closest next token which is non whitespace.
507
     *
508
     * This method is shorthand for getNonWhitespaceSibling method.
509
     *
510
     * @param int         $index       token index
511
     * @param null|string $whitespaces whitespaces characters for Token::isWhitespace
512
     */
513
    public function getNextNonWhitespace(int $index, ?string $whitespaces = null): ?int
514
    {
515
        return $this->getNonWhitespaceSibling($index, 1, $whitespaces);
516
    }
517
518
    /**
519
     * Get index for closest next token of given kind.
520
     *
521
     * This method is shorthand for getTokenOfKindSibling method.
522
     *
523
     * @param int   $index         token index
524
     * @param array $tokens        possible tokens
525
     * @param bool  $caseSensitive perform a case sensitive comparison
526
     */
527
    public function getNextTokenOfKind(int $index, array $tokens = [], bool $caseSensitive = true): ?int
528
    {
529
        return $this->getTokenOfKindSibling($index, 1, $tokens, $caseSensitive);
530
    }
531
532
    /**
533
     * Get index for closest sibling token which is non whitespace.
534
     *
535
     * @param int         $index       token index
536
     * @param int         $direction   direction for looking, +1 or -1
537
     * @param null|string $whitespaces whitespaces characters for Token::isWhitespace
538
     */
539
    public function getNonWhitespaceSibling(int $index, int $direction, ?string $whitespaces = null): ?int
540
    {
541
        while (true) {
542
            $index += $direction;
543
544
            if (!$this->offsetExists($index)) {
545
                return null;
546
            }
547
548
            if (!$this[$index]->isWhitespace($whitespaces)) {
549
                return $index;
550
            }
551
        }
552
    }
553
554
    /**
555
     * Get index for closest previous token which is non whitespace.
556
     *
557
     * This method is shorthand for getNonWhitespaceSibling method.
558
     *
559
     * @param int         $index       token index
560
     * @param null|string $whitespaces whitespaces characters for Token::isWhitespace
561
     */
562
    public function getPrevNonWhitespace(int $index, ?string $whitespaces = null): ?int
563
    {
564
        return $this->getNonWhitespaceSibling($index, -1, $whitespaces);
565
    }
566
567
    /**
568
     * Get index for closest previous token of given kind.
569
     * This method is shorthand for getTokenOfKindSibling method.
570
     *
571
     * @param int   $index         token index
572
     * @param array $tokens        possible tokens
573
     * @param bool  $caseSensitive perform a case sensitive comparison
574
     */
575
    public function getPrevTokenOfKind(int $index, array $tokens = [], bool $caseSensitive = true): ?int
576
    {
577
        return $this->getTokenOfKindSibling($index, -1, $tokens, $caseSensitive);
578
    }
579
580
    /**
581
     * Get index for closest sibling token of given kind.
582
     *
583
     * @param int   $index         token index
584
     * @param int   $direction     direction for looking, +1 or -1
585
     * @param array $tokens        possible tokens
586
     * @param bool  $caseSensitive perform a case sensitive comparison
587
     */
588
    public function getTokenOfKindSibling(int $index, int $direction, array $tokens = [], bool $caseSensitive = true): ?int
589
    {
590
        $tokens = array_filter($tokens, function ($token) {
591
            return $this->isTokenKindFound($this->extractTokenKind($token));
592
        });
593
594
        if (!\count($tokens)) {
595
            return null;
596
        }
597
598
        while (true) {
599
            $index += $direction;
600
601
            if (!$this->offsetExists($index)) {
602
                return null;
603
            }
604
605
            if ($this[$index]->equalsAny($tokens, $caseSensitive)) {
606
                return $index;
607
            }
608
        }
609
    }
610
611
    /**
612
     * Get index for closest sibling token not of given kind.
613
     *
614
     * @param int   $index     token index
615
     * @param int   $direction direction for looking, +1 or -1
616
     * @param array $tokens    possible tokens
617
     */
618
    public function getTokenNotOfKindSibling(int $index, int $direction, array $tokens = []): ?int
619
    {
620
        return $this->getTokenNotOfKind(
621
            $index,
622
            $direction,
623
            function (int $a) use ($tokens) {
624
                return $this[$a]->equalsAny($tokens);
625
            }
626
        );
627
    }
628
629
    /**
630
     * Get index for closest sibling token not of given kind.
631
     *
632
     * @param int   $index     token index
633
     * @param int   $direction direction for looking, +1 or -1
634
     * @param array $kinds     possible tokens kinds
635
     */
636
    public function getTokenNotOfKindsSibling(int $index, int $direction, array $kinds = []): ?int
637
    {
638
        return $this->getTokenNotOfKind(
639
            $index,
640
            $direction,
641
            function (int $index) use ($kinds) {
642
                return $this[$index]->isGivenKind($kinds);
643
            }
644
        );
645
    }
646
647
    /**
648
     * Get index for closest sibling token that is not a whitespace, comment or attribute.
649
     *
650
     * @param int $index     token index
651
     * @param int $direction direction for looking, +1 or -1
652
     */
653
    public function getMeaningfulTokenSibling(int $index, int $direction): ?int
654
    {
655
        return $this->getTokenNotOfKindsSibling(
656
            $index,
657
            $direction,
658
            [T_WHITESPACE, T_COMMENT, T_DOC_COMMENT]
659
        );
660
    }
661
662
    /**
663
     * Get index for closest sibling token which is not empty.
664
     *
665
     * @param int $index     token index
666
     * @param int $direction direction for looking, +1 or -1
667
     */
668
    public function getNonEmptySibling(int $index, int $direction): ?int
669
    {
670
        while (true) {
671
            $index += $direction;
672
673
            if (!$this->offsetExists($index)) {
674
                return null;
675
            }
676
677
            if (!$this->isEmptyAt($index)) {
678
                return $index;
679
            }
680
        }
681
    }
682
683
    /**
684
     * Get index for closest next token that is not a whitespace or comment.
685
     *
686
     * @param int $index token index
687
     */
688
    public function getNextMeaningfulToken(int $index): ?int
689
    {
690
        return $this->getMeaningfulTokenSibling($index, 1);
691
    }
692
693
    /**
694
     * Get index for closest previous token that is not a whitespace or comment.
695
     *
696
     * @param int $index token index
697
     */
698
    public function getPrevMeaningfulToken(int $index): ?int
699
    {
700
        return $this->getMeaningfulTokenSibling($index, -1);
701
    }
702
703
    /**
704
     * Find a sequence of meaningful tokens and returns the array of their locations.
705
     *
706
     * @param array                 $sequence      an array of tokens (kinds) (same format used by getNextTokenOfKind)
707
     * @param int                   $start         start index, defaulting to the start of the file
708
     * @param int                   $end           end index, defaulting to the end of the file
709
     * @param array<int, bool>|bool $caseSensitive global case sensitiveness or an array of booleans, whose keys should match
710
     *                                             the ones used in $others. If any is missing, the default case-sensitive
711
     *                                             comparison is used
712
     *
713
     * @return null|array<int, Token> an array containing the tokens matching the sequence elements, indexed by their position
714
     */
715
    public function findSequence(array $sequence, int $start = 0, ?int $end = null, $caseSensitive = true): ?array
716
    {
717
        $sequenceCount = \count($sequence);
718
        if (0 === $sequenceCount) {
719
            throw new \InvalidArgumentException('Invalid sequence.');
720
        }
721
722
        // $end defaults to the end of the collection
723
        $end = null === $end ? \count($this) - 1 : min($end, \count($this) - 1);
724
725
        if ($start + $sequenceCount - 1 > $end) {
726
            return null;
727
        }
728
729
        $nonMeaningFullKind = [T_COMMENT, T_DOC_COMMENT, T_WHITESPACE];
730
731
        // make sure the sequence content is "meaningful"
732
        foreach ($sequence as $key => $token) {
733
            // if not a Token instance already, we convert it to verify the meaningfulness
734
            if (!$token instanceof Token) {
735
                if (\is_array($token) && !isset($token[1])) {
736
                    // fake some content as it is required by the Token constructor,
737
                    // although optional for search purposes
738
                    $token[1] = 'DUMMY';
739
                }
740
741
                $token = new Token($token);
742
            }
743
744
            if ($token->isGivenKind($nonMeaningFullKind)) {
745
                throw new \InvalidArgumentException(sprintf('Non-meaningful token at position: "%s".', $key));
746
            }
747
748
            if ('' === $token->getContent()) {
749
                throw new \InvalidArgumentException(sprintf('Non-meaningful (empty) token at position: "%s".', $key));
750
            }
751
        }
752
753
        foreach ($sequence as $token) {
754
            if (!$this->isTokenKindFound($this->extractTokenKind($token))) {
755
                return null;
756
            }
757
        }
758
759
        // remove the first token from the sequence, so we can freely iterate through the sequence after a match to
760
        // the first one is found
761
        $key = key($sequence);
762
        $firstCs = Token::isKeyCaseSensitive($caseSensitive, $key);
763
        $firstToken = $sequence[$key];
764
        unset($sequence[$key]);
765
766
        // begin searching for the first token in the sequence (start included)
767
        $index = $start - 1;
768
        while (null !== $index && $index <= $end) {
769
            $index = $this->getNextTokenOfKind($index, [$firstToken], $firstCs);
770
771
            // ensure we found a match and didn't get past the end index
772
            if (null === $index || $index > $end) {
773
                return null;
774
            }
775
776
            // initialise the result array with the current index
777
            $result = [$index => $this[$index]];
778
779
            // advance cursor to the current position
780
            $currIdx = $index;
781
782
            // iterate through the remaining tokens in the sequence
783
            foreach ($sequence as $key => $token) {
784
                $currIdx = $this->getNextMeaningfulToken($currIdx);
785
786
                // ensure we didn't go too far
787
                if (null === $currIdx || $currIdx > $end) {
788
                    return null;
789
                }
790
791
                if (!$this[$currIdx]->equals($token, Token::isKeyCaseSensitive($caseSensitive, $key))) {
792
                    // not a match, restart the outer loop
793
                    continue 2;
794
                }
795
796
                // append index to the result array
797
                $result[$currIdx] = $this[$currIdx];
798
            }
799
800
            // do we have a complete match?
801
            // hint: $result is bigger than $sequence since the first token has been removed from the latter
802
            if (\count($sequence) < \count($result)) {
803
                return $result;
804
            }
805
        }
806
807
        return null;
808
    }
809
810
    /**
811
     * Insert instances of Token inside collection.
812
     *
813
     * @param int                       $index start inserting index
814
     * @param array<Token>|Token|Tokens $items instances of Token to insert
815
     */
816
    public function insertAt(int $index, $items): void
817
    {
818
        $items = \is_array($items) || $items instanceof self ? $items : [$items];
819
820
        $this->insertSlices([$index => $items]);
821
    }
822
823
    /**
824
     * Insert a slices or individual Tokens into multiple places in a single run.
825
     *
826
     * This approach is kind-of an experiment - it's proven to improve performance a lot for big files that needs plenty of new tickets to be inserted,
827
     * like edge case example of 3.7h vs 4s (https://github.com/FriendsOfPHP/PHP-CS-Fixer/issues/3996#issuecomment-455617637),
828
     * yet at same time changing a logic of fixers in not-always easy way.
829
     *
830
     * To be discuss:
831
     * - should we always aim to use this method?
832
     * - should we deprecate `insertAt` method ?
833
     *
834
     * The `$slices` parameter is an assoc array, in which:
835
     * - index: starting point for inserting of individual slice, with indexes being relatives to original array collection before any Token inserted
836
     * - value under index: a slice of Tokens to be inserted
837
     *
838
     * @internal
839
     *
840
     * @param array<int, array<Token>|Token|Tokens> $slices
841
     */
842
    public function insertSlices(array $slices): void
843
    {
844
        $itemsCount = 0;
845
        foreach ($slices as $slice) {
846
            $slice = \is_array($slice) || $slice instanceof self ? $slice : [$slice];
847
            $itemsCount += \count($slice);
848
        }
849
850
        if (0 === $itemsCount) {
0 ignored issues
show
introduced by
The condition 0 === $itemsCount is always true.
Loading history...
851
            return;
852
        }
853
854
        $oldSize = \count($this);
855
        $this->changed = true;
856
        $this->blockStartCache = [];
857
        $this->blockEndCache = [];
858
        $this->setSize($oldSize + $itemsCount);
859
860
        krsort($slices);
861
862
        $insertBound = $oldSize - 1;
863
864
        // since we only move already existing items around, we directly call into SplFixedArray::offset* methods.
865
        // that way we get around additional overhead this class adds with overridden offset* methods.
866
        foreach ($slices as $index => $slice) {
867
            $slice = \is_array($slice) || $slice instanceof self ? $slice : [$slice];
868
            $sliceCount = \count($slice);
869
870
            for ($i = $insertBound; $i >= $index; --$i) {
871
                $oldItem = parent::offsetExists($i) ? parent::offsetGet($i) : new Token('');
872
                parent::offsetSet($i + $itemsCount, $oldItem);
873
            }
874
875
            $insertBound = $index - $sliceCount;
876
            $itemsCount -= $sliceCount;
877
878
            foreach ($slice as $indexItem => $item) {
879
                if ('' === $item->getContent()) {
880
                    throw new \InvalidArgumentException('Must not add empty token to collection.');
881
                }
882
883
                $this->registerFoundToken($item);
884
                $newOffset = $index + $itemsCount + $indexItem;
885
                parent::offsetSet($newOffset, $item);
886
            }
887
        }
888
    }
889
890
    /**
891
     * Check if collection was change: collection itself (like insert new tokens) or any of collection's elements.
892
     */
893
    public function isChanged(): bool
894
    {
895
        if ($this->changed) {
896
            return true;
897
        }
898
899
        return false;
900
    }
901
902
    public function isEmptyAt(int $index): bool
903
    {
904
        $token = $this[$index];
905
906
        return null === $token->getId() && '' === $token->getContent();
907
    }
908
909
    public function clearAt(int $index): void
910
    {
911
        $this[$index] = new Token('');
912
    }
913
914
    /**
915
     * Override tokens at given range.
916
     *
917
     * @param int                 $indexStart start overriding index
918
     * @param int                 $indexEnd   end overriding index
919
     * @param array<Token>|Tokens $items      tokens to insert
920
     */
921
    public function overrideRange(int $indexStart, int $indexEnd, iterable $items): void
922
    {
923
        $indexToChange = $indexEnd - $indexStart + 1;
924
        $itemsCount = \count($items);
925
926
        // If we want to add more items than passed range contains we need to
927
        // add placeholders for overhead items.
928
        if ($itemsCount > $indexToChange) {
929
            $placeholders = [];
930
931
            while ($itemsCount > $indexToChange) {
932
                $placeholders[] = new Token('__PLACEHOLDER__');
933
                ++$indexToChange;
934
            }
935
936
            $this->insertAt($indexEnd + 1, $placeholders);
937
        }
938
939
        // Override each items.
940
        foreach ($items as $itemIndex => $item) {
941
            $this[$indexStart + $itemIndex] = $item;
942
        }
943
944
        // If we want to add less tokens than passed range contains then clear
945
        // not needed tokens.
946
        if ($itemsCount < $indexToChange) {
947
            $this->clearRange($indexStart + $itemsCount, $indexEnd);
948
        }
949
    }
950
951
    /**
952
     * @param null|string $whitespaces optional whitespaces characters for Token::isWhitespace
953
     */
954
    public function removeLeadingWhitespace(int $index, ?string $whitespaces = null): void
955
    {
956
        $this->removeWhitespaceSafely($index, -1, $whitespaces);
957
    }
958
959
    /**
960
     * @param null|string $whitespaces optional whitespaces characters for Token::isWhitespace
961
     */
962
    public function removeTrailingWhitespace(int $index, ?string $whitespaces = null): void
963
    {
964
        $this->removeWhitespaceSafely($index, 1, $whitespaces);
965
    }
966
967
    /**
968
     * Set code. Clear all current content and replace it by new Token items generated from code directly.
969
     *
970
     * @param string $code PHP code
971
     */
972
    public function setCode(string $code): void
973
    {
974
        // No need to work when the code is the same.
975
        // That is how we avoid a lot of work and setting changed flag.
976
        if ($code === $this->generateCode()) {
977
            return;
978
        }
979
980
        // clear memory
981
        $this->setSize(0);
982
983
        $tokens = token_get_all($code, TOKEN_PARSE);
984
985
        $this->setSize(\count($tokens));
986
987
        foreach ($tokens as $index => $token) {
988
            $this[$index] = new Token($token);
989
        }
990
991
        $this->applyTransformers();
992
993
        $this->foundTokenKinds = [];
994
995
        foreach ($this as $token) {
996
            $this->registerFoundToken($token);
997
        }
998
999
        if (\PHP_VERSION_ID < 80000) {
1000
            $this->rewind();
1001
        }
1002
1003
        $this->changeCodeHash(self::calculateCodeHash($code));
1004
        $this->changed = true;
1005
    }
1006
1007
    public function toJson(): string
1008
    {
1009
        $output = new \SplFixedArray(\count($this));
1010
1011
        foreach ($this as $index => $token) {
1012
            $output[$index] = $token->toArray();
1013
        }
1014
1015
        if (\PHP_VERSION_ID < 80000) {
1016
            $this->rewind();
1017
        }
1018
1019
        return json_encode($output, JSON_PRETTY_PRINT | JSON_NUMERIC_CHECK);
1020
    }
1021
1022
    /**
1023
     * Check if all token kinds given as argument are found.
1024
     */
1025
    public function isAllTokenKindsFound(array $tokenKinds): bool
1026
    {
1027
        foreach ($tokenKinds as $tokenKind) {
1028
            if (empty($this->foundTokenKinds[$tokenKind])) {
1029
                return false;
1030
            }
1031
        }
1032
1033
        return true;
1034
    }
1035
1036
    /**
1037
     * Check if any token kind given as argument is found.
1038
     */
1039
    public function isAnyTokenKindsFound(array $tokenKinds): bool
1040
    {
1041
        foreach ($tokenKinds as $tokenKind) {
1042
            if (!empty($this->foundTokenKinds[$tokenKind])) {
1043
                return true;
1044
            }
1045
        }
1046
1047
        return false;
1048
    }
1049
1050
    /**
1051
     * Check if token kind given as argument is found.
1052
     *
1053
     * @param int|string $tokenKind
1054
     */
1055
    public function isTokenKindFound($tokenKind): bool
1056
    {
1057
        return !empty($this->foundTokenKinds[$tokenKind]);
1058
    }
1059
1060
    /**
1061
     * @param int|string $tokenKind
1062
     */
1063
    public function countTokenKind($tokenKind): int
1064
    {
1065
        return $this->foundTokenKinds[$tokenKind] ?? 0;
1066
    }
1067
1068
    /**
1069
     * Clear tokens in the given range.
1070
     */
1071
    public function clearRange(int $indexStart, int $indexEnd): void
1072
    {
1073
        for ($i = $indexStart; $i <= $indexEnd; ++$i) {
1074
            $this->clearAt($i);
1075
        }
1076
    }
1077
1078
    /**
1079
     * Checks for monolithic PHP code.
1080
     *
1081
     * Checks that the code is pure PHP code, in a single code block, starting
1082
     * with an open tag.
1083
     */
1084
    public function isMonolithicPhp(): bool
1085
    {
1086
        $size = $this->count();
1087
1088
        if (0 === $size) {
1089
            return false;
1090
        }
1091
1092
        if ($this->isTokenKindFound(T_INLINE_HTML)) {
1093
            return false;
1094
        }
1095
1096
        return 1 >= ($this->countTokenKind(T_OPEN_TAG) + $this->countTokenKind(T_OPEN_TAG_WITH_ECHO));
1097
    }
1098
1099
    /**
1100
     * @param int $start start index
1101
     * @param int $end   end index
1102
     */
1103
    public function isPartialCodeMultiline(int $start, int $end): bool
1104
    {
1105
        for ($i = $start; $i <= $end; ++$i) {
1106
            if (false !== strpos($this[$i]->getContent(), "\n")) {
1107
                return true;
1108
            }
1109
        }
1110
1111
        return false;
1112
    }
1113
1114
    public function hasAlternativeSyntax(): bool
1115
    {
1116
        return $this->isAnyTokenKindsFound([
1117
            T_ENDDECLARE,
1118
            T_ENDFOR,
1119
            T_ENDFOREACH,
1120
            T_ENDIF,
1121
            T_ENDSWITCH,
1122
            T_ENDWHILE,
1123
        ]);
1124
    }
1125
1126
    public function clearTokenAndMergeSurroundingWhitespace(int $index): void
1127
    {
1128
        $count = \count($this);
1129
        $this->clearAt($index);
1130
1131
        if ($index === $count - 1) {
1132
            return;
1133
        }
1134
1135
        $nextIndex = $this->getNonEmptySibling($index, 1);
1136
1137
        if (null === $nextIndex || !$this[$nextIndex]->isWhitespace()) {
1138
            return;
1139
        }
1140
1141
        $prevIndex = $this->getNonEmptySibling($index, -1);
1142
1143
        if ($this[$prevIndex]->isWhitespace()) {
1144
            $this[$prevIndex] = new Token([T_WHITESPACE, $this[$prevIndex]->getContent().$this[$nextIndex]->getContent()]);
1145
        } elseif ($this->isEmptyAt($prevIndex + 1)) {
1146
            $this[$prevIndex + 1] = new Token([T_WHITESPACE, $this[$nextIndex]->getContent()]);
1147
        }
1148
1149
        $this->clearAt($nextIndex);
1150
    }
1151
1152
    /**
1153
     * @internal
1154
     */
1155
    protected function applyTransformers(): void
1156
    {
1157
        $transformers = Transformers::createSingleton();
1158
        $transformers->transform($this);
1159
    }
1160
1161
    private function removeWhitespaceSafely(int $index, int $direction, ?string $whitespaces = null): void
1162
    {
1163
        $whitespaceIndex = $this->getNonEmptySibling($index, $direction);
1164
        if (isset($this[$whitespaceIndex]) && $this[$whitespaceIndex]->isWhitespace()) {
1165
            $newContent = '';
1166
            $tokenToCheck = $this[$whitespaceIndex];
1167
1168
            // if the token candidate to remove is preceded by single line comment we do not consider the new line after this comment as part of T_WHITESPACE
1169
            if (isset($this[$whitespaceIndex - 1]) && $this[$whitespaceIndex - 1]->isComment() && '/*' !== substr($this[$whitespaceIndex - 1]->getContent(), 0, 2)) {
1170
                [$emptyString, $newContent, $whitespacesToCheck] = Preg::split('/^(\R)/', $this[$whitespaceIndex]->getContent(), -1, PREG_SPLIT_DELIM_CAPTURE);
1171
1172
                if ('' === $whitespacesToCheck) {
1173
                    return;
1174
                }
1175
1176
                $tokenToCheck = new Token([T_WHITESPACE, $whitespacesToCheck]);
1177
            }
1178
1179
            if (!$tokenToCheck->isWhitespace($whitespaces)) {
1180
                return;
1181
            }
1182
1183
            if ('' === $newContent) {
1184
                $this->clearAt($whitespaceIndex);
1185
            } else {
1186
                $this[$whitespaceIndex] = new Token([T_WHITESPACE, $newContent]);
1187
            }
1188
        }
1189
    }
1190
1191
    /**
1192
     * @param int  $type        type of block, one of BLOCK_TYPE_*
1193
     * @param int  $searchIndex index of starting brace
1194
     * @param bool $findEnd     if method should find block's end or start
1195
     *
1196
     * @return int index of opposite brace
1197
     */
1198
    private function findOppositeBlockEdge(int $type, int $searchIndex, bool $findEnd): int
1199
    {
1200
        $blockEdgeDefinitions = self::getBlockEdgeDefinitions();
1201
1202
        if (!isset($blockEdgeDefinitions[$type])) {
1203
            throw new \InvalidArgumentException(sprintf('Invalid param type: "%s".', $type));
1204
        }
1205
1206
        if ($findEnd && isset($this->blockStartCache[$searchIndex])) {
1207
            return $this->blockStartCache[$searchIndex];
1208
        }
1209
        if (!$findEnd && isset($this->blockEndCache[$searchIndex])) {
1210
            return $this->blockEndCache[$searchIndex];
1211
        }
1212
1213
        $startEdge = $blockEdgeDefinitions[$type]['start'];
1214
        $endEdge = $blockEdgeDefinitions[$type]['end'];
1215
        $startIndex = $searchIndex;
1216
        $endIndex = $this->count() - 1;
1217
        $indexOffset = 1;
1218
1219
        if (!$findEnd) {
1220
            [$startEdge, $endEdge] = [$endEdge, $startEdge];
1221
            $indexOffset = -1;
1222
            $endIndex = 0;
1223
        }
1224
1225
        if (!$this[$startIndex]->equals($startEdge)) {
1226
            throw new \InvalidArgumentException(sprintf('Invalid param $startIndex - not a proper block "%s".', $findEnd ? 'start' : 'end'));
1227
        }
1228
1229
        $blockLevel = 0;
1230
1231
        for ($index = $startIndex; $index !== $endIndex; $index += $indexOffset) {
1232
            $token = $this[$index];
1233
1234
            if ($token->equals($startEdge)) {
1235
                ++$blockLevel;
1236
1237
                continue;
1238
            }
1239
1240
            if ($token->equals($endEdge)) {
1241
                --$blockLevel;
1242
1243
                if (0 === $blockLevel) {
1244
                    break;
1245
                }
1246
            }
1247
        }
1248
1249
        if (!$this[$index]->equals($endEdge)) {
1250
            throw new \UnexpectedValueException(sprintf('Missing block "%s".', $findEnd ? 'end' : 'start'));
1251
        }
1252
1253
        if ($startIndex < $index) {
1254
            $this->blockStartCache[$startIndex] = $index;
1255
            $this->blockEndCache[$index] = $startIndex;
1256
        } else {
1257
            $this->blockStartCache[$index] = $startIndex;
1258
            $this->blockEndCache[$startIndex] = $index;
1259
        }
1260
1261
        return $index;
1262
    }
1263
1264
    /**
1265
     * Calculate hash for code.
1266
     */
1267
    private static function calculateCodeHash(string $code): string
1268
    {
1269
        return CodeHasher::calculateCodeHash($code);
1270
    }
1271
1272
    /**
1273
     * Get cache value for given key.
1274
     *
1275
     * @param string $key item key
1276
     */
1277
    private static function getCache(string $key): self
1278
    {
1279
        if (!self::hasCache($key)) {
1280
            throw new \OutOfBoundsException(sprintf('Unknown cache key: "%s".', $key));
1281
        }
1282
1283
        return self::$cache[$key];
1284
    }
1285
1286
    /**
1287
     * Check if given key exists in cache.
1288
     *
1289
     * @param string $key item key
1290
     */
1291
    private static function hasCache(string $key): bool
1292
    {
1293
        return isset(self::$cache[$key]);
1294
    }
1295
1296
    /**
1297
     * @param string $key   item key
1298
     * @param Tokens $value item value
1299
     */
1300
    private static function setCache(string $key, self $value): void
1301
    {
1302
        self::$cache[$key] = $value;
1303
    }
1304
1305
    /**
1306
     * Change code hash.
1307
     *
1308
     * Remove old cache and set new one.
1309
     *
1310
     * @param string $codeHash new code hash
1311
     */
1312
    private function changeCodeHash(string $codeHash): void
1313
    {
1314
        if (null !== $this->codeHash) {
1315
            self::clearCache($this->codeHash);
1316
        }
1317
1318
        $this->codeHash = $codeHash;
1319
        self::setCache($this->codeHash, $this);
1320
    }
1321
1322
    /**
1323
     * Register token as found.
1324
     *
1325
     * @param array|string|Token $token token prototype
1326
     */
1327
    private function registerFoundToken($token): void
1328
    {
1329
        // inlined extractTokenKind() call on the hot path
1330
        $tokenKind = $token instanceof Token
1331
            ? ($token->isArray() ? $token->getId() : $token->getContent())
1332
            : (\is_array($token) ? $token[0] : $token)
1333
        ;
1334
1335
        if (!isset($this->foundTokenKinds[$tokenKind])) {
1336
            $this->foundTokenKinds[$tokenKind] = 0;
1337
        }
1338
1339
        ++$this->foundTokenKinds[$tokenKind];
1340
    }
1341
1342
    /**
1343
     * Register token as found.
1344
     *
1345
     * @param array|string|Token $token token prototype
1346
     */
1347
    private function unregisterFoundToken($token): void
1348
    {
1349
        // inlined extractTokenKind() call on the hot path
1350
        $tokenKind = $token instanceof Token
1351
            ? ($token->isArray() ? $token->getId() : $token->getContent())
1352
            : (\is_array($token) ? $token[0] : $token)
1353
        ;
1354
1355
        if (!isset($this->foundTokenKinds[$tokenKind])) {
1356
            return;
1357
        }
1358
1359
        --$this->foundTokenKinds[$tokenKind];
1360
    }
1361
1362
    /**
1363
     * @param array|string|Token $token token prototype
1364
     *
1365
     * @return int|string
1366
     */
1367
    private function extractTokenKind($token)
1368
    {
1369
        return $token instanceof Token
1370
            ? ($token->isArray() ? $token->getId() : $token->getContent())
1371
            : (\is_array($token) ? $token[0] : $token)
1372
        ;
1373
    }
1374
1375
    /**
1376
     * @param int $index     token index
1377
     * @param int $direction direction for looking, +1 or -1
1378
     */
1379
    private function getTokenNotOfKind(int $index, int $direction, callable $filter): ?int
1380
    {
1381
        while (true) {
1382
            $index += $direction;
1383
1384
            if (!$this->offsetExists($index)) {
1385
                return null;
1386
            }
1387
1388
            if ($this->isEmptyAt($index) || $filter($index)) {
1389
                continue;
1390
            }
1391
1392
            return $index;
1393
        }
1394
    }
1395
}
1396