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

keradus / PHP-CS-Fixer / 17377459942

01 Sep 2025 12:19PM UTC coverage: 94.684% (-0.009%) from 94.693%
17377459942

push

github

web-flow
chore: `Tokens::offsetSet` - explicit validation of input (#9004)

1 of 5 new or added lines in 1 file covered. (20.0%)

306 existing lines in 60 files now uncovered.

28390 of 29984 relevant lines covered (94.68%)

45.5 hits per line

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

99.26
/src/Fixer/Import/FullyQualifiedStrictTypesFixer.php
1
<?php
2

3
declare(strict_types=1);
4

5
/*
6
 * This file is part of PHP CS Fixer.
7
 *
8
 * (c) Fabien Potencier <fabien@symfony.com>
9
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
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\Fixer\Import;
16

17
use PhpCsFixer\AbstractFixer;
18
use PhpCsFixer\DocBlock\TypeExpression;
19
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
20
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
21
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
22
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
23
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
24
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
25
use PhpCsFixer\FixerDefinition\CodeSample;
26
use PhpCsFixer\FixerDefinition\FixerDefinition;
27
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
28
use PhpCsFixer\Preg;
29
use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis;
30
use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer;
31
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
32
use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer;
33
use PhpCsFixer\Tokenizer\CT;
34
use PhpCsFixer\Tokenizer\FCT;
35
use PhpCsFixer\Tokenizer\Processor\ImportProcessor;
36
use PhpCsFixer\Tokenizer\Token;
37
use PhpCsFixer\Tokenizer\Tokens;
38

39
/**
40
 * @phpstan-type _AutogeneratedInputConfiguration array{
41
 *  import_symbols?: bool,
42
 *  leading_backslash_in_global_namespace?: bool,
43
 *  phpdoc_tags?: list<string>,
44
 * }
45
 * @phpstan-type _AutogeneratedComputedConfiguration array{
46
 *  import_symbols: bool,
47
 *  leading_backslash_in_global_namespace: bool,
48
 *  phpdoc_tags: list<string>,
49
 * }
50
 * @phpstan-type _Uses array{
51
 *   constant?: array<class-string, string>,
52
 *   class?: array<class-string, string>,
53
 *   function?: array<class-string, string>
54
 * }
55
 *
56
 * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
57
 *
58
 * @author VeeWee <toonverwerft@gmail.com>
59
 * @author Tomas Jadrny <developer@tomasjadrny.cz>
60
 * @author Greg Korba <greg@codito.dev>
61
 * @author SpacePossum <possumfromspace@gmail.com>
62
 * @author Michael Vorisek <https://github.com/mvorisek>
63
 *
64
 * @phpstan-import-type _ImportType from \PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis
65
 *
66
 * @no-named-arguments Parameter names are not covered by the backward compatibility promise.
67
 */
68
final class FullyQualifiedStrictTypesFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
69
{
70
    /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
71
    use ConfigurableFixerTrait;
72

73
    private const REGEX_CLASS = '(?:\\\?+'.TypeExpression::REGEX_IDENTIFIER
74
        .'(\\\\'.TypeExpression::REGEX_IDENTIFIER.')*+)';
75
    private const CLASSY_KINDS = [\T_CLASS, \T_INTERFACE, \T_TRAIT, FCT::T_ENUM];
76

77
    /**
78
     * @var null|array{
79
     *     constant?: list<class-string>,
80
     *     class?: list<class-string>,
81
     *     function?: list<class-string>
82
     * }
83
     */
84
    private ?array $discoveredSymbols;
85

86
    /**
87
     * @var array{
88
     *     constant?: array<string, class-string>,
89
     *     class?: array<string, class-string>,
90
     *     function?: array<string, class-string>
91
     * }
92
     */
93
    private array $symbolsForImport = [];
94

95
    /**
96
     * @var array<int<0, max>, array<string, true>>
97
     */
98
    private array $reservedIdentifiersByLevel;
99

100
    /**
101
     * @var array{
102
     *     constant?: array<string, string>,
103
     *     class?: array<string, string>,
104
     *     function?: array<string, string>
105
     * }
106
     */
107
    private array $cacheUsesLast = [];
108

109
    /**
110
     * @var array{
111
     *     constant?: array<string, class-string>,
112
     *     class?: array<string, class-string>,
113
     *     function?: array<string, class-string>
114
     * }
115
     */
116
    private array $cacheUseNameByShortNameLower;
117

118
    /** @var _Uses */
119
    private array $cacheUseShortNameByNameLower;
120

121
    public function getDefinition(): FixerDefinitionInterface
122
    {
123
        return new FixerDefinition(
3✔
124
            'Removes the leading part of fully qualified symbol references if a given symbol is imported or belongs to the current namespace.',
3✔
125
            [
3✔
126
                new CodeSample(
3✔
127
                    <<<'PHP'
3✔
128
                        <?php
129

130
                        use Foo\Bar;
131
                        use Foo\Bar\Baz;
132
                        use Foo\OtherClass;
133
                        use Foo\SomeContract;
134
                        use Foo\SomeException;
135

136
                        /**
137
                         * @see \Foo\Bar\Baz
138
                         */
139
                        class SomeClass extends \Foo\OtherClass implements \Foo\SomeContract
140
                        {
141
                            /**
142
                             * @var \Foo\Bar\Baz
143
                             */
144
                            public $baz;
145

146
                            /**
147
                             * @param \Foo\Bar\Baz $baz
148
                             */
149
                            public function __construct($baz) {
150
                                $this->baz = $baz;
151
                            }
152

153
                            /**
154
                             * @return \Foo\Bar\Baz
155
                             */
156
                            public function getBaz() {
157
                                return $this->baz;
158
                            }
159

160
                            public function doX(\Foo\Bar $foo, \Exception $e): \Foo\Bar\Baz
161
                            {
162
                                try {}
163
                                catch (\Foo\SomeException $e) {}
164
                            }
165
                        }
166

167
                        PHP
3✔
168
                ),
3✔
169
                new CodeSample(
3✔
170
                    <<<'PHP'
3✔
171
                        <?php
172

173
                        class SomeClass
174
                        {
175
                            public function doY(Foo\NotImported $u, \Foo\NotImported $v)
176
                            {
177
                            }
178
                        }
179

180
                        PHP,
3✔
181
                    ['leading_backslash_in_global_namespace' => true]
3✔
182
                ),
3✔
183
                new CodeSample(
3✔
184
                    <<<'PHP'
3✔
185
                        <?php
186
                        namespace {
187
                            use Foo\A;
188
                            try {
189
                                foo();
190
                            } catch (\Exception|\Foo\A $e) {
191
                            }
192
                        }
193
                        namespace Foo\Bar {
194
                            class SomeClass implements \Foo\Bar\Baz
195
                            {
196
                            }
197
                        }
198

199
                        PHP,
3✔
200
                    ['leading_backslash_in_global_namespace' => true]
3✔
201
                ),
3✔
202
                new CodeSample(
3✔
203
                    <<<'PHP'
3✔
204
                        <?php
205

206
                        namespace Foo\Test;
207

208
                        class Foo extends \Other\BaseClass implements \Other\Interface1, \Other\Interface2
209
                        {
210
                            /** @var \Other\PropertyPhpDoc */
211
                            private $array;
212
                            public function __construct(\Other\FunctionArgument $arg) {}
213
                            public function foo(): \Other\FunctionReturnType
214
                            {
215
                                try {
216
                                    \Other\StaticFunctionCall::bar();
217
                                } catch (\Other\CaughtThrowable $e) {}
218
                            }
219
                        }
220

221
                        PHP,
3✔
222
                    ['import_symbols' => true]
3✔
223
                ),
3✔
224
            ]
3✔
225
        );
3✔
226
    }
227

228
    /**
229
     * {@inheritdoc}
230
     *
231
     * Must run before NoSuperfluousPhpdocTagsFixer, OrderedAttributesFixer, OrderedImportsFixer, OrderedInterfacesFixer, StatementIndentationFixer.
232
     * Must run after ClassKeywordFixer, PhpUnitAttributesFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer.
233
     */
234
    public function getPriority(): int
235
    {
236
        return 7;
1✔
237
    }
238

239
    public function isCandidate(Tokens $tokens): bool
240
    {
241
        return $tokens->isAnyTokenKindsFound([
149✔
242
            CT::T_USE_TRAIT,
149✔
243
            FCT::T_ATTRIBUTE,
149✔
244
            \T_CATCH,
149✔
245
            \T_DOUBLE_COLON,
149✔
246
            \T_DOC_COMMENT,
149✔
247
            \T_EXTENDS,
149✔
248
            \T_FUNCTION,
149✔
249
            \T_IMPLEMENTS,
149✔
250
            \T_INSTANCEOF,
149✔
251
            \T_NEW,
149✔
252
            \T_VARIABLE,
149✔
253
        ]);
149✔
254
    }
255

256
    protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
257
    {
258
        return new FixerConfigurationResolver([
158✔
259
            (new FixerOptionBuilder(
158✔
260
                'leading_backslash_in_global_namespace',
158✔
261
                'Whether FQCN is prefixed with backslash when that FQCN is used in global namespace context.'
158✔
262
            ))
158✔
263
                ->setAllowedTypes(['bool'])
158✔
264
                ->setDefault(false)
158✔
265
                ->getOption(),
158✔
266
            (new FixerOptionBuilder(
158✔
267
                'import_symbols',
158✔
268
                'Whether FQCNs should be automatically imported.'
158✔
269
            ))
158✔
270
                ->setAllowedTypes(['bool'])
158✔
271
                ->setDefault(false)
158✔
272
                ->getOption(),
158✔
273
            (new FixerOptionBuilder(
158✔
274
                'phpdoc_tags',
158✔
275
                'Collection of PHPDoc annotation tags where FQCNs should be processed. As of now only simple tags with `@tag \F\Q\C\N` format are supported (no complex types).'
158✔
276
            ))
158✔
277
                ->setAllowedTypes(['string[]'])
158✔
278
                ->setDefault([
158✔
279
                    'param',
158✔
280
                    'phpstan-param',
158✔
281
                    'phpstan-property',
158✔
282
                    'phpstan-property-read',
158✔
283
                    'phpstan-property-write',
158✔
284
                    'phpstan-return',
158✔
285
                    'phpstan-var',
158✔
286
                    'property',
158✔
287
                    'property-read',
158✔
288
                    'property-write',
158✔
289
                    'psalm-param',
158✔
290
                    'psalm-property',
158✔
291
                    'psalm-property-read',
158✔
292
                    'psalm-property-write',
158✔
293
                    'psalm-return',
158✔
294
                    'psalm-var',
158✔
295
                    'return',
158✔
296
                    'see',
158✔
297
                    'throws',
158✔
298
                    'var',
158✔
299
                ])
158✔
300
                ->getOption(),
158✔
301
        ]);
158✔
302
    }
303

304
    protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
305
    {
306
        $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer();
149✔
307
        $functionsAnalyzer = new FunctionsAnalyzer();
149✔
308

309
        $this->symbolsForImport = [];
149✔
310

311
        foreach ($tokens->getNamespaceDeclarations() as $namespaceIndex => $namespace) {
149✔
312
            $namespace = $tokens->getNamespaceDeclarations()[$namespaceIndex];
149✔
313

314
            $namespaceName = $namespace->getFullName();
149✔
315

316
            $uses = [];
149✔
317
            $lastUse = null;
149✔
318

319
            foreach ($namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace, true) as $use) {
149✔
320
                if (!$use->isClass()) {
95✔
321
                    continue;
6✔
322
                }
323

324
                $uses[$use->getHumanFriendlyType()][ltrim($use->getFullName(), '\\')] = $use->getShortName();
94✔
325
                $lastUse = $use;
94✔
326
            }
327

328
            $indexDiff = 0;
149✔
329
            foreach (true === $this->configuration['import_symbols'] ? [true, false] : [false] as $discoverSymbolsPhase) {
149✔
330
                $this->discoveredSymbols = $discoverSymbolsPhase ? [] : null;
149✔
331

332
                $openedCurlyBrackets = 0;
149✔
333
                $this->reservedIdentifiersByLevel = [];
149✔
334

335
                for ($index = $namespace->getScopeStartIndex(); $index < $namespace->getScopeEndIndex() + $indexDiff; ++$index) {
149✔
336
                    $origSize = \count($tokens);
149✔
337
                    $token = $tokens[$index];
149✔
338

339
                    if ($token->equals('{')) {
149✔
340
                        ++$openedCurlyBrackets;
116✔
341
                    } elseif ($token->equals('}')) {
149✔
342
                        unset($this->reservedIdentifiersByLevel[$openedCurlyBrackets]);
53✔
343
                        --$openedCurlyBrackets;
53✔
344
                    } elseif ($token->isGivenKind(\T_VARIABLE)) {
149✔
345
                        $prevIndex = $tokens->getPrevMeaningfulToken($index);
102✔
346
                        if (null !== $prevIndex && $tokens[$prevIndex]->isGivenKind(\T_STRING)) {
102✔
347
                            $this->fixPrevName($tokens, $index, $uses, $namespaceName);
72✔
348
                        }
349
                    } elseif ($token->isGivenKind(\T_DOUBLE_COLON)) {
149✔
350
                        $this->fixPrevName($tokens, $index, $uses, $namespaceName);
11✔
351
                    } elseif ($token->isGivenKind(\T_FUNCTION)) {
149✔
352
                        $this->fixFunction($functionsAnalyzer, $tokens, $index, $uses, $namespaceName);
87✔
353
                    } elseif ($token->isGivenKind(FCT::T_ATTRIBUTE)) {
149✔
354
                        $this->fixAttribute($tokens, $index, $uses, $namespaceName);
2✔
355
                    } elseif ($token->isGivenKind(\T_CATCH)) {
149✔
356
                        $this->fixCatch($tokens, $index, $uses, $namespaceName);
8✔
357
                    } elseif ($discoverSymbolsPhase && $token->isGivenKind(self::CLASSY_KINDS)) {
149✔
358
                        $this->fixNextName($tokens, $index, $uses, $namespaceName);
11✔
359
                    } elseif ($token->isGivenKind([\T_EXTENDS, \T_IMPLEMENTS])) {
149✔
360
                        $this->fixExtendsImplements($tokens, $index, $uses, $namespaceName);
14✔
361
                    } elseif ($token->isGivenKind([\T_INSTANCEOF, \T_NEW, CT::T_USE_TRAIT, CT::T_TYPE_COLON])) {
149✔
362
                        $this->fixNextName($tokens, $index, $uses, $namespaceName);
66✔
363
                    } elseif ($discoverSymbolsPhase && $token->isGivenKind(\T_COMMENT) && Preg::match('/#\[\s*('.self::REGEX_CLASS.')/', $token->getContent(), $matches)) { // @TODO: drop when PHP 8.0+ is required
149✔
364
                        /** @var class-string $attributeClass */
UNCOV
365
                        $attributeClass = $matches[1];
×
UNCOV
366
                        $this->determineShortType($attributeClass, 'class', $uses, $namespaceName);
×
367
                    } elseif ($token->isGivenKind(\T_DOC_COMMENT)) {
149✔
368
                        Preg::matchAll('/\*\h*@(?:psalm-|phpstan-)?(?:template(?:-covariant|-contravariant)?|(?:import-)?type)\h+('.TypeExpression::REGEX_IDENTIFIER.')(?!\S)/i', $token->getContent(), $matches);
35✔
369
                        foreach ($matches[1] as $reservedIdentifier) {
35✔
370
                            $this->reservedIdentifiersByLevel[$openedCurlyBrackets + 1][$reservedIdentifier] = true;
4✔
371
                        }
372

373
                        $this->fixPhpDoc($tokens, $index, $uses, $namespaceName);
35✔
374
                    }
375

376
                    $indexDiff += \count($tokens) - $origSize;
149✔
377
                }
378

379
                $this->reservedIdentifiersByLevel = [];
149✔
380

381
                if ($discoverSymbolsPhase) {
149✔
382
                    $this->setupUsesFromDiscoveredSymbols($uses, $namespaceName);
36✔
383
                }
384
            }
385

386
            if ([] !== $this->symbolsForImport) {
149✔
387
                if (null !== $lastUse) {
22✔
388
                    $atIndex = $lastUse->getEndIndex() + 1;
4✔
389
                } elseif (0 !== $namespace->getEndIndex()) {
18✔
390
                    $atIndex = $namespace->getEndIndex() + 1;
13✔
391
                } else {
392
                    $firstTokenIndex = $tokens->getNextMeaningfulToken($namespace->getScopeStartIndex());
5✔
393
                    if (null !== $firstTokenIndex && $tokens[$firstTokenIndex]->isGivenKind(\T_DECLARE)) {
5✔
394
                        $atIndex = $tokens->getNextTokenOfKind($firstTokenIndex, [';']) + 1;
1✔
395
                    } else {
396
                        $atIndex = $namespace->getScopeStartIndex() + 1;
4✔
397
                    }
398
                }
399

400
                // Insert all registered FQCNs
401
                $this->createImportProcessor()->insertImports($tokens, $this->symbolsForImport, $atIndex);
22✔
402

403
                $this->symbolsForImport = [];
22✔
404
            }
405
        }
406
    }
407

408
    /**
409
     * @param _Uses $uses
410
     */
411
    private function refreshUsesCache(array $uses): void
412
    {
413
        if ($this->cacheUsesLast === $uses) {
140✔
414
            return;
138✔
415
        }
416

417
        $this->cacheUsesLast = $uses;
90✔
418

419
        $this->cacheUseNameByShortNameLower = [];
90✔
420
        $this->cacheUseShortNameByNameLower = [];
90✔
421

422
        foreach ($uses as $kind => $kindUses) {
90✔
423
            foreach ($kindUses as $useLongName => $useShortName) {
90✔
424
                $this->cacheUseNameByShortNameLower[$kind][strtolower($useShortName)] = $useLongName;
90✔
425

426
                /**
427
                 * @var class-string $normalisedUseLongName
428
                 *
429
                 * @phpstan-ignore varTag.nativeType
430
                 */
431
                $normalisedUseLongName = strtolower($useLongName);
90✔
432
                $this->cacheUseShortNameByNameLower[$kind][$normalisedUseLongName] = $useShortName;
90✔
433
            }
434
        }
435
    }
436

437
    private function isReservedIdentifier(string $symbol): bool
438
    {
439
        if (str_contains($symbol, '\\')) { // optimization only
144✔
440
            return false;
120✔
441
        }
442

443
        if ((new TypeAnalysis($symbol))->isReservedType()) {
134✔
444
            return true;
23✔
445
        }
446

447
        foreach ($this->reservedIdentifiersByLevel as $reservedIdentifiers) {
131✔
448
            if (isset($reservedIdentifiers[$symbol])) {
4✔
449
                return true;
4✔
450
            }
451
        }
452

453
        return false;
130✔
454
    }
455

456
    /**
457
     * Resolve absolute or relative symbol to normalized FQCN.
458
     *
459
     * @param _ImportType $importKind
460
     * @param _Uses       $uses
461
     *
462
     * @return class-string
463
     */
464
    private function resolveSymbol(string $symbol, string $importKind, array $uses, string $namespaceName): string
465
    {
466
        if (str_starts_with($symbol, '\\')) {
144✔
467
            return substr($symbol, 1); // @phpstan-ignore return.type
126✔
468
        }
469

470
        if ($this->isReservedIdentifier($symbol)) {
133✔
471
            return $symbol; // @phpstan-ignore return.type
25✔
472
        }
473

474
        $this->refreshUsesCache($uses);
127✔
475

476
        $symbolArr = explode('\\', $symbol, 2);
127✔
477
        $shortStartNameLower = strtolower($symbolArr[0]);
127✔
478
        if (isset($this->cacheUseNameByShortNameLower[$importKind][$shortStartNameLower])) {
127✔
479
            // @phpstan-ignore return.type
480
            return $this->cacheUseNameByShortNameLower[$importKind][$shortStartNameLower].(isset($symbolArr[1]) ? '\\'.$symbolArr[1] : '');
81✔
481
        }
482

483
        return ('' !== $namespaceName ? $namespaceName.'\\' : '').$symbol; // @phpstan-ignore return.type
80✔
484
    }
485

486
    /**
487
     * Shorten normalized FQCN as much as possible.
488
     *
489
     * @param _ImportType $importKind
490
     * @param _Uses       $uses
491
     */
492
    private function shortenSymbol(string $fqcn, string $importKind, array $uses, string $namespaceName): string
493
    {
494
        if ($this->isReservedIdentifier($fqcn)) {
144✔
495
            return $fqcn;
25✔
496
        }
497

498
        $this->refreshUsesCache($uses);
140✔
499

500
        $res = null;
140✔
501

502
        // try to shorten the name using namespace
503
        $iMin = 0;
140✔
504
        if (str_starts_with($fqcn, $namespaceName.'\\')) {
140✔
505
            $tmpRes = substr($fqcn, \strlen($namespaceName) + 1);
58✔
506
            if (!isset($this->cacheUseNameByShortNameLower[$importKind][strtolower(explode('\\', $tmpRes, 2)[0])]) && !$this->isReservedIdentifier($tmpRes)) {
58✔
507
                $res = $tmpRes;
54✔
508
                $iMin = substr_count($namespaceName, '\\') + 1;
54✔
509
            }
510
        }
511

512
        // try to shorten the name using uses
513
        $tmp = $fqcn;
140✔
514
        for ($i = substr_count($fqcn, '\\'); $i >= $iMin; --$i) {
140✔
515
            if (isset($this->cacheUseShortNameByNameLower[$importKind][strtolower($tmp)])) {
140✔
516
                $tmpRes = $this->cacheUseShortNameByNameLower[$importKind][strtolower($tmp)].substr($fqcn, \strlen($tmp));
81✔
517
                if (!$this->isReservedIdentifier($tmpRes)) {
81✔
518
                    $res = $tmpRes;
81✔
519

520
                    break;
81✔
521
                }
522
            }
523

524
            if ($i > 0) {
110✔
525
                $tmp = substr($tmp, 0, strrpos($tmp, '\\'));
84✔
526
            }
527
        }
528

529
        // shortening is not possible, add leading backslash if needed
530
        if (null === $res) {
140✔
531
            $res = $fqcn;
80✔
532
            if ('' !== $namespaceName
80✔
533
                || true === $this->configuration['leading_backslash_in_global_namespace']
80✔
534
                || isset($this->cacheUseNameByShortNameLower[$importKind][strtolower(explode('\\', $res, 2)[0])])
80✔
535
            ) {
536
                $res = '\\'.$res;
58✔
537
            }
538
        }
539

540
        return $res;
140✔
541
    }
542

543
    /**
544
     * @param _Uses $uses
545
     */
546
    private function setupUsesFromDiscoveredSymbols(array &$uses, string $namespaceName): void
547
    {
548
        foreach ($this->discoveredSymbols as $kind => $discoveredSymbols) {
36✔
549
            $discoveredFqcnByShortNameLower = [];
36✔
550

551
            if ('' === $namespaceName) {
36✔
552
                foreach ($discoveredSymbols as $symbol) {
8✔
553
                    if (!str_starts_with($symbol, '\\')) {
8✔
554
                        $shortStartName = explode('\\', ltrim($symbol, '\\'), 2)[0];
8✔
555
                        $shortStartNameLower = strtolower($shortStartName);
8✔
556
                        $discoveredFqcnByShortNameLower[$kind][$shortStartNameLower] = $this->resolveSymbol($shortStartName, $kind, $uses, $namespaceName);
8✔
557
                    }
558
                }
559
            }
560

561
            foreach ($uses[$kind] ?? [] as $useLongName => $useShortName) {
36✔
562
                $discoveredFqcnByShortNameLower[$kind][strtolower($useShortName)] = $useLongName;
24✔
563
            }
564

565
            $useByShortNameLower = [];
36✔
566
            foreach ($uses[$kind] ?? [] as $useShortName) {
36✔
567
                $useByShortNameLower[strtolower($useShortName)] = true;
24✔
568
            }
569

570
            uasort($discoveredSymbols, static function ($a, $b) {
36✔
571
                $res = str_starts_with($a, '\\') <=> str_starts_with($b, '\\');
34✔
572
                if (0 !== $res) {
34✔
573
                    return $res;
24✔
574
                }
575

576
                return substr_count($a, '\\') <=> substr_count($b, '\\');
28✔
577
            });
36✔
578
            foreach ($discoveredSymbols as $symbol) {
36✔
579
                while (true) {
36✔
580
                    $shortEndNameLower = strtolower(str_contains($symbol, '\\') ? substr($symbol, strrpos($symbol, '\\') + 1) : $symbol);
36✔
581
                    if (!isset($discoveredFqcnByShortNameLower[$kind][$shortEndNameLower])) {
36✔
582
                        $shortStartNameLower = strtolower(explode('\\', ltrim($symbol, '\\'), 2)[0]);
34✔
583
                        if (str_starts_with($symbol, '\\') || ('' === $namespaceName && !isset($useByShortNameLower[$shortStartNameLower]))
34✔
584
                            || !str_contains($symbol, '\\')
34✔
585
                        ) {
586
                            $discoveredFqcnByShortNameLower[$kind][$shortEndNameLower] = $this->resolveSymbol($symbol, $kind, $uses, $namespaceName);
34✔
587

588
                            break;
34✔
589
                        }
590
                    }
591
                    // else short name collision - keep unimported
592

593
                    if (str_starts_with($symbol, '\\') || '' === $namespaceName || !str_contains($symbol, '\\')) {
36✔
594
                        break;
36✔
595
                    }
596

597
                    $symbol = substr($symbol, 0, strrpos($symbol, '\\'));
5✔
598
                }
599
            }
600

601
            foreach ($uses[$kind] ?? [] as $useLongName => $useShortName) {
36✔
602
                $discoveredLongName = $discoveredFqcnByShortNameLower[$kind][strtolower($useShortName)] ?? null;
24✔
603
                if (strtolower($discoveredLongName) === strtolower($useLongName)) {
24✔
604
                    unset($discoveredFqcnByShortNameLower[$kind][strtolower($useShortName)]);
24✔
605
                }
606
            }
607

608
            foreach ($discoveredFqcnByShortNameLower[$kind] ?? [] as $fqcn) {
36✔
609
                $shortenedName = ltrim($this->shortenSymbol($fqcn, $kind, [], $namespaceName), '\\');
35✔
610
                if (str_contains($shortenedName, '\\')) { // prevent importing non-namespaced names in global namespace
35✔
611
                    $shortEndName = str_contains($fqcn, '\\') ? substr($fqcn, strrpos($fqcn, '\\') + 1) : $fqcn;
22✔
612
                    $uses[$kind][$fqcn] = $shortEndName;
22✔
613
                    $this->symbolsForImport[$kind][$shortEndName] = $fqcn;
22✔
614
                }
615
            }
616

617
            if (isset($this->symbolsForImport[$kind])) {
36✔
618
                ksort($this->symbolsForImport[$kind], \SORT_NATURAL);
22✔
619
            }
620
        }
621
    }
622

623
    /**
624
     * @param _Uses $uses
625
     */
626
    private function fixFunction(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index, array $uses, string $namespaceName): void
627
    {
628
        $arguments = $functionsAnalyzer->getFunctionArguments($tokens, $index);
87✔
629

630
        foreach ($arguments as $i => $argument) {
87✔
631
            $argument = $functionsAnalyzer->getFunctionArguments($tokens, $index)[$i];
79✔
632

633
            if ($argument->hasTypeAnalysis()) {
79✔
634
                $this->replaceByShortType($tokens, $argument->getTypeAnalysis(), $uses, $namespaceName);
66✔
635
            }
636
        }
637

638
        $returnTypeAnalysis = $functionsAnalyzer->getFunctionReturnType($tokens, $index);
87✔
639

640
        if (null !== $returnTypeAnalysis) {
87✔
641
            $this->replaceByShortType($tokens, $returnTypeAnalysis, $uses, $namespaceName);
32✔
642
        }
643
    }
644

645
    /**
646
     * @param _Uses $uses
647
     */
648
    private function fixPhpDoc(Tokens $tokens, int $index, array $uses, string $namespaceName): void
649
    {
650
        $allowedTags = $this->configuration['phpdoc_tags'];
35✔
651

652
        if ([] === $allowedTags) {
35✔
653
            return;
1✔
654
        }
655

656
        $phpDoc = $tokens[$index];
34✔
657
        $phpDocContent = $phpDoc->getContent();
34✔
658
        $phpDocContentNew = Preg::replaceCallback('/([*{]\h*@)(\S+)(\h+)('.TypeExpression::REGEX_TYPES.')(?!(?!\})\S)/', function ($matches) use ($allowedTags, $uses, $namespaceName) {
34✔
659
            if (!\in_array($matches[2], $allowedTags, true)) {
28✔
660
                return $matches[0];
7✔
661
            }
662

663
            return $matches[1].$matches[2].$matches[3].$this->fixPhpDocType($matches[4], $uses, $namespaceName);
27✔
664
        }, $phpDocContent);
34✔
665

666
        if ($phpDocContentNew !== $phpDocContent) {
34✔
667
            $tokens[$index] = new Token([\T_DOC_COMMENT, $phpDocContentNew]);
21✔
668
        }
669
    }
670

671
    /**
672
     * @param _Uses $uses
673
     */
674
    private function fixPhpDocType(string $type, array $uses, string $namespaceName): string
675
    {
676
        $typeExpression = new TypeExpression($type, null, []);
27✔
677

678
        $typeExpression = $typeExpression->mapTypes(function (TypeExpression $type) use ($uses, $namespaceName) {
27✔
679
            $currentTypeValue = $type->toString();
27✔
680

681
            if ($type->isCompositeType() || !Preg::match('/^'.self::REGEX_CLASS.'$/', $currentTypeValue) || \in_array($currentTypeValue, ['min', 'max'], true)) {
27✔
682
                return $type;
11✔
683
            }
684

685
            /** @var class-string $currentTypeValue */
686
            $shortTokens = $this->determineShortType($currentTypeValue, 'class', $uses, $namespaceName);
27✔
687

688
            if (null === $shortTokens) {
27✔
689
                return $type;
27✔
690
            }
691

692
            $newTypeValue = implode('', array_map(
21✔
693
                static fn (Token $token) => $token->getContent(),
21✔
694
                $shortTokens
21✔
695
            ));
21✔
696

697
            return $currentTypeValue === $newTypeValue
21✔
UNCOV
698
                ? $type
×
699
                : new TypeExpression($newTypeValue, null, []);
21✔
700
        });
27✔
701

702
        return $typeExpression->toString();
27✔
703
    }
704

705
    /**
706
     * @param _Uses $uses
707
     */
708
    private function fixExtendsImplements(Tokens $tokens, int $index, array $uses, string $namespaceName): void
709
    {
710
        // We handle `extends` and `implements` with similar logic, but we need to exit the loop under different conditions.
711
        $isExtends = $tokens[$index]->isGivenKind(\T_EXTENDS);
14✔
712
        $index = $tokens->getNextMeaningfulToken($index);
14✔
713

714
        $typeStartIndex = null;
14✔
715
        $typeEndIndex = null;
14✔
716

717
        while (true) {
14✔
718
            if ($tokens[$index]->equalsAny([',', '{', [\T_IMPLEMENTS]])) {
14✔
719
                if (null !== $typeStartIndex) {
14✔
720
                    $index += $this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName);
14✔
721
                }
722
                $typeStartIndex = null;
14✔
723

724
                if ($tokens[$index]->equalsAny($isExtends ? [[\T_IMPLEMENTS], '{'] : ['{'])) {
14✔
725
                    break;
14✔
726
                }
727
            } else {
728
                if (null === $typeStartIndex) {
14✔
729
                    $typeStartIndex = $index;
14✔
730
                }
731
                $typeEndIndex = $index;
14✔
732
            }
733

734
            $index = $tokens->getNextMeaningfulToken($index);
14✔
735
        }
736
    }
737

738
    /**
739
     * @param _Uses $uses
740
     */
741
    private function fixCatch(Tokens $tokens, int $index, array $uses, string $namespaceName): void
742
    {
743
        $index = $tokens->getNextMeaningfulToken($index); // '('
8✔
744
        $index = $tokens->getNextMeaningfulToken($index); // first part of first exception class to be caught
8✔
745

746
        $typeStartIndex = null;
8✔
747
        $typeEndIndex = null;
8✔
748

749
        while (true) {
8✔
750
            if ($tokens[$index]->equalsAny([')', [\T_VARIABLE], [CT::T_TYPE_ALTERNATION]])) {
8✔
751
                if (null === $typeStartIndex) {
8✔
752
                    break;
8✔
753
                }
754

755
                $index += $this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName);
8✔
756
                $typeStartIndex = null;
8✔
757

758
                if ($tokens[$index]->equals(')')) {
8✔
759
                    break;
1✔
760
                }
761
            } else {
762
                if (null === $typeStartIndex) {
8✔
763
                    $typeStartIndex = $index;
8✔
764
                }
765
                $typeEndIndex = $index;
8✔
766
            }
767

768
            $index = $tokens->getNextMeaningfulToken($index);
8✔
769
        }
770
    }
771

772
    /**
773
     * @param _Uses $uses
774
     */
775
    private function fixAttribute(Tokens $tokens, int $index, array $uses, string $namespaceName): void
776
    {
777
        $attributeAnalysis = AttributeAnalyzer::collectOne($tokens, $index);
2✔
778

779
        foreach ($attributeAnalysis->getAttributes() as $attribute) {
2✔
780
            $index = $attribute['start'];
2✔
781
            while ($tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) {
2✔
782
                $index = $tokens->getPrevMeaningfulToken($index);
2✔
783
            }
784
            $this->fixNextName($tokens, $index, $uses, $namespaceName);
2✔
785
        }
786
    }
787

788
    /**
789
     * @param _Uses $uses
790
     */
791
    private function fixPrevName(Tokens $tokens, int $index, array $uses, string $namespaceName): void
792
    {
793
        $typeStartIndex = null;
79✔
794
        $typeEndIndex = null;
79✔
795

796
        while (true) {
79✔
797
            $index = $tokens->getPrevMeaningfulToken($index);
79✔
798
            if ($tokens[$index]->isObjectOperator()) {
79✔
799
                break;
2✔
800
            }
801

802
            if ($tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) {
79✔
803
                $typeStartIndex = $index;
79✔
804
                if (null === $typeEndIndex) {
79✔
805
                    $typeEndIndex = $index;
79✔
806
                }
807
            } else {
808
                if (null !== $typeEndIndex) {
77✔
809
                    $this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName);
77✔
810
                }
811

812
                break;
77✔
813
            }
814
        }
815
    }
816

817
    /**
818
     * @param _Uses $uses
819
     */
820
    private function fixNextName(Tokens $tokens, int $index, array $uses, string $namespaceName): void
821
    {
822
        $typeStartIndex = null;
70✔
823
        $typeEndIndex = null;
70✔
824

825
        while (true) {
70✔
826
            $index = $tokens->getNextMeaningfulToken($index);
70✔
827

828
            if ($tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) {
70✔
829
                if (null === $typeStartIndex) {
65✔
830
                    $typeStartIndex = $index;
65✔
831
                }
832
                $typeEndIndex = $index;
65✔
833
            } else {
834
                if (null !== $typeStartIndex) {
70✔
835
                    $this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName);
65✔
836
                }
837

838
                break;
70✔
839
            }
840
        }
841
    }
842

843
    /**
844
     * @param _Uses $uses
845
     */
846
    private function shortenClassIfPossible(Tokens $tokens, int $typeStartIndex, int $typeEndIndex, array $uses, string $namespaceName): int
847
    {
848
        /** @var class-string $content */
849
        $content = $tokens->generatePartialCode($typeStartIndex, $typeEndIndex);
125✔
850
        $newTokens = $this->determineShortType($content, 'class', $uses, $namespaceName);
125✔
851
        if (null === $newTokens) {
125✔
852
            return 0;
125✔
853
        }
854

855
        $tokens->overrideRange($typeStartIndex, $typeEndIndex, $newTokens);
42✔
856

857
        return \count($newTokens) - ($typeEndIndex - $typeStartIndex) - 1;
42✔
858
    }
859

860
    /**
861
     * @param _Uses $uses
862
     */
863
    private function replaceByShortType(Tokens $tokens, TypeAnalysis $type, array $uses, string $namespaceName): void
864
    {
865
        $typeStartIndex = $type->getStartIndex();
74✔
866

867
        if ($tokens[$typeStartIndex]->isGivenKind(CT::T_NULLABLE_TYPE)) {
74✔
868
            $typeStartIndex = $tokens->getNextMeaningfulToken($typeStartIndex);
2✔
869
        }
870

871
        $types = $this->getTypes($tokens, $typeStartIndex, $type->getEndIndex());
74✔
872

873
        foreach ($types as [$startIndex, $endIndex]) {
74✔
874
            /** @var class-string $content */
875
            $content = $tokens->generatePartialCode($startIndex, $endIndex);
74✔
876
            $newTokens = $this->determineShortType($content, 'class', $uses, $namespaceName);
74✔
877
            if (null !== $newTokens) {
74✔
878
                $tokens->overrideRange($startIndex, $endIndex, $newTokens);
46✔
879
            }
880
        }
881
    }
882

883
    /**
884
     * Determines short type based on FQCN, current namespace and imports (`use` declarations).
885
     *
886
     * @param class-string $typeName
887
     * @param _ImportType  $importKind
888
     * @param _Uses        $uses
889
     *
890
     * @return null|non-empty-list<Token>
891
     */
892
    private function determineShortType(string $typeName, string $importKind, array $uses, string $namespaceName): ?array
893
    {
894
        if (null !== $this->discoveredSymbols) {
144✔
895
            if (!$this->isReservedIdentifier($typeName)) {
36✔
896
                $this->discoveredSymbols[$importKind][] = $typeName;
36✔
897
            }
898

899
            return null;
36✔
900
        }
901

902
        $fqcn = $this->resolveSymbol($typeName, $importKind, $uses, $namespaceName);
144✔
903
        $shortenedType = $this->shortenSymbol($fqcn, $importKind, $uses, $namespaceName);
144✔
904
        if ($shortenedType === $typeName) {
144✔
905
            return null;
144✔
906
        }
907

908
        return $this->namespacedStringToTokens($shortenedType);
101✔
909
    }
910

911
    /**
912
     * @return iterable<array{int, int}>
913
     */
914
    private function getTypes(Tokens $tokens, int $index, int $endIndex): iterable
915
    {
916
        $skipNextYield = false;
74✔
917
        $typeStartIndex = $typeEndIndex = null;
74✔
918
        while (true) {
74✔
919
            if ($tokens[$index]->isGivenKind(CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN)) {
74✔
920
                $index = $tokens->getNextMeaningfulToken($index);
1✔
921
                $typeStartIndex = $typeEndIndex = null;
1✔
922

923
                continue;
1✔
924
            }
925

926
            if (
927
                $tokens[$index]->isGivenKind([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE])
74✔
928
                || $index > $endIndex
74✔
929
            ) {
930
                if (!$skipNextYield && null !== $typeStartIndex) {
74✔
931
                    $origCount = \count($tokens);
74✔
932

933
                    yield [$typeStartIndex, $typeEndIndex];
74✔
934

935
                    $endIndex += \count($tokens) - $origCount;
74✔
936

937
                    // type tokens were possibly updated, restart type match
938
                    $skipNextYield = true;
74✔
939
                    $index = $typeEndIndex = $typeStartIndex;
74✔
940
                } else {
941
                    $skipNextYield = false;
74✔
942
                    $index = $tokens->getNextMeaningfulToken($index);
74✔
943
                    $typeStartIndex = $typeEndIndex = null;
74✔
944
                }
945

946
                if ($index > $endIndex) {
74✔
947
                    break;
74✔
948
                }
949

950
                continue;
74✔
951
            }
952

953
            if (null === $typeStartIndex) {
74✔
954
                $typeStartIndex = $index;
74✔
955
            }
956
            $typeEndIndex = $index;
74✔
957

958
            $index = $tokens->getNextMeaningfulToken($index);
74✔
959
        }
960
    }
961

962
    /**
963
     * @return non-empty-list<Token>
964
     */
965
    private function namespacedStringToTokens(string $input): array
966
    {
967
        $tokens = [];
101✔
968

969
        if (str_starts_with($input, '\\')) {
101✔
970
            $tokens[] = new Token([\T_NS_SEPARATOR, '\\']);
11✔
971
            $input = substr($input, 1);
11✔
972
        }
973

974
        $parts = explode('\\', $input);
101✔
975
        foreach ($parts as $index => $part) {
101✔
976
            $tokens[] = new Token([\T_STRING, $part]);
101✔
977

978
            if ($index !== \count($parts) - 1) {
101✔
979
                $tokens[] = new Token([\T_NS_SEPARATOR, '\\']);
22✔
980
            }
981
        }
982

983
        return $tokens;
101✔
984
    }
985

986
    /**
987
     * We need to create import processor dynamically (not in costructor), because actual whitespace configuration
988
     * is set later, not when fixer's instance is created.
989
     */
990
    private function createImportProcessor(): ImportProcessor
991
    {
992
        return new ImportProcessor($this->whitespacesConfig);
22✔
993
    }
994
}
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