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

keradus / PHP-CS-Fixer / 17642215709

11 Sep 2025 10:50AM UTC coverage: 94.689% (+0.003%) from 94.686%
17642215709

push

github

keradus
Merge remote-tracking branch 'upstream/master' into __modifier_keywords

10 of 10 new or added lines in 2 files covered. (100.0%)

77 existing lines in 10 files now uncovered.

28421 of 30015 relevant lines covered (94.69%)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

454
        return false;
130✔
455
    }
456

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

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

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

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

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

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

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

501
        $res = null;
140✔
502

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

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

521
                    break;
81✔
522
                }
523
            }
524

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

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

541
        return $res;
140✔
542
    }
543

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

900
            return null;
36✔
901
        }
902

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

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

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

924
                continue;
1✔
925
            }
926

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

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

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

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

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

951
                continue;
74✔
952
            }
953

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

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

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

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

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

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

984
        return $tokens;
101✔
985
    }
986

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