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

keradus / PHP-CS-Fixer / 17319949156

29 Aug 2025 09:20AM UTC coverage: 94.696% (-0.05%) from 94.744%
17319949156

push

github

keradus
CS

28333 of 29920 relevant lines covered (94.7%)

45.63 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

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

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

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

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

159
    public function doX(\Foo\Bar $foo, \Exception $e): \Foo\Bar\Baz
160
    {
161
        try {}
162
        catch (\Foo\SomeException $e) {}
163
    }
164
}
165
'
3✔
166
                ),
3✔
167
                new CodeSample(
3✔
168
                    '<?php
3✔
169

170
class SomeClass
171
{
172
    public function doY(Foo\NotImported $u, \Foo\NotImported $v)
173
    {
174
    }
175
}
176
',
3✔
177
                    ['leading_backslash_in_global_namespace' => true]
3✔
178
                ),
3✔
179
                new CodeSample(
3✔
180
                    '<?php
3✔
181
namespace {
182
    use Foo\A;
183
    try {
184
        foo();
185
    } catch (\Exception|\Foo\A $e) {
186
    }
187
}
188
namespace Foo\Bar {
189
    class SomeClass implements \Foo\Bar\Baz
190
    {
191
    }
192
}
193
',
3✔
194
                    ['leading_backslash_in_global_namespace' => true]
3✔
195
                ),
3✔
196
                new CodeSample(
3✔
197
                    '<?php
3✔
198

199
namespace Foo\Test;
200

201
class Foo extends \Other\BaseClass implements \Other\Interface1, \Other\Interface2
202
{
203
    /** @var \Other\PropertyPhpDoc */
204
    private $array;
205
    public function __construct(\Other\FunctionArgument $arg) {}
206
    public function foo(): \Other\FunctionReturnType
207
    {
208
        try {
209
            \Other\StaticFunctionCall::bar();
210
        } catch (\Other\CaughtThrowable $e) {}
211
    }
212
}
213
',
3✔
214
                    ['import_symbols' => true]
3✔
215
                ),
3✔
216
            ]
3✔
217
        );
3✔
218
    }
219

220
    /**
221
     * {@inheritdoc}
222
     *
223
     * Must run before NoSuperfluousPhpdocTagsFixer, OrderedAttributesFixer, OrderedImportsFixer, OrderedInterfacesFixer, StatementIndentationFixer.
224
     * Must run after ClassKeywordFixer, PhpUnitAttributesFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer.
225
     */
226
    public function getPriority(): int
227
    {
228
        return 7;
1✔
229
    }
230

231
    public function isCandidate(Tokens $tokens): bool
232
    {
233
        return $tokens->isAnyTokenKindsFound([
149✔
234
            CT::T_USE_TRAIT,
149✔
235
            FCT::T_ATTRIBUTE,
149✔
236
            \T_CATCH,
149✔
237
            \T_DOUBLE_COLON,
149✔
238
            \T_DOC_COMMENT,
149✔
239
            \T_EXTENDS,
149✔
240
            \T_FUNCTION,
149✔
241
            \T_IMPLEMENTS,
149✔
242
            \T_INSTANCEOF,
149✔
243
            \T_NEW,
149✔
244
            \T_VARIABLE,
149✔
245
        ]);
149✔
246
    }
247

248
    protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
249
    {
250
        return new FixerConfigurationResolver([
158✔
251
            (new FixerOptionBuilder(
158✔
252
                'leading_backslash_in_global_namespace',
158✔
253
                'Whether FQCN is prefixed with backslash when that FQCN is used in global namespace context.'
158✔
254
            ))
158✔
255
                ->setAllowedTypes(['bool'])
158✔
256
                ->setDefault(false)
158✔
257
                ->getOption(),
158✔
258
            (new FixerOptionBuilder(
158✔
259
                'import_symbols',
158✔
260
                'Whether FQCNs should be automatically imported.'
158✔
261
            ))
158✔
262
                ->setAllowedTypes(['bool'])
158✔
263
                ->setDefault(false)
158✔
264
                ->getOption(),
158✔
265
            (new FixerOptionBuilder(
158✔
266
                'phpdoc_tags',
158✔
267
                '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✔
268
            ))
158✔
269
                ->setAllowedTypes(['string[]'])
158✔
270
                ->setDefault([
158✔
271
                    'param',
158✔
272
                    'phpstan-param',
158✔
273
                    'phpstan-property',
158✔
274
                    'phpstan-property-read',
158✔
275
                    'phpstan-property-write',
158✔
276
                    'phpstan-return',
158✔
277
                    'phpstan-var',
158✔
278
                    'property',
158✔
279
                    'property-read',
158✔
280
                    'property-write',
158✔
281
                    'psalm-param',
158✔
282
                    'psalm-property',
158✔
283
                    'psalm-property-read',
158✔
284
                    'psalm-property-write',
158✔
285
                    'psalm-return',
158✔
286
                    'psalm-var',
158✔
287
                    'return',
158✔
288
                    'see',
158✔
289
                    'throws',
158✔
290
                    'var',
158✔
291
                ])
158✔
292
                ->getOption(),
158✔
293
        ]);
158✔
294
    }
295

296
    protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
297
    {
298
        $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer();
149✔
299
        $functionsAnalyzer = new FunctionsAnalyzer();
149✔
300

301
        $this->symbolsForImport = [];
149✔
302

303
        foreach ($tokens->getNamespaceDeclarations() as $namespaceIndex => $namespace) {
149✔
304
            $namespace = $tokens->getNamespaceDeclarations()[$namespaceIndex];
149✔
305

306
            $namespaceName = $namespace->getFullName();
149✔
307

308
            $uses = [];
149✔
309
            $lastUse = null;
149✔
310

311
            foreach ($namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace, true) as $use) {
149✔
312
                if (!$use->isClass()) {
95✔
313
                    continue;
6✔
314
                }
315

316
                $uses[$use->getHumanFriendlyType()][ltrim($use->getFullName(), '\\')] = $use->getShortName();
94✔
317
                $lastUse = $use;
94✔
318
            }
319

320
            $indexDiff = 0;
149✔
321
            foreach (true === $this->configuration['import_symbols'] ? [true, false] : [false] as $discoverSymbolsPhase) {
149✔
322
                $this->discoveredSymbols = $discoverSymbolsPhase ? [] : null;
149✔
323

324
                $openedCurlyBrackets = 0;
149✔
325
                $this->reservedIdentifiersByLevel = [];
149✔
326

327
                for ($index = $namespace->getScopeStartIndex(); $index < $namespace->getScopeEndIndex() + $indexDiff; ++$index) {
149✔
328
                    $origSize = \count($tokens);
149✔
329
                    $token = $tokens[$index];
149✔
330

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

365
                        $this->fixPhpDoc($tokens, $index, $uses, $namespaceName);
35✔
366
                    }
367

368
                    $indexDiff += \count($tokens) - $origSize;
149✔
369
                }
370

371
                $this->reservedIdentifiersByLevel = [];
149✔
372

373
                if ($discoverSymbolsPhase) {
149✔
374
                    $this->setupUsesFromDiscoveredSymbols($uses, $namespaceName);
36✔
375
                }
376
            }
377

378
            if ([] !== $this->symbolsForImport) {
149✔
379
                if (null !== $lastUse) {
22✔
380
                    $atIndex = $lastUse->getEndIndex() + 1;
4✔
381
                } elseif (0 !== $namespace->getEndIndex()) {
18✔
382
                    $atIndex = $namespace->getEndIndex() + 1;
13✔
383
                } else {
384
                    $firstTokenIndex = $tokens->getNextMeaningfulToken($namespace->getScopeStartIndex());
5✔
385
                    if (null !== $firstTokenIndex && $tokens[$firstTokenIndex]->isGivenKind(\T_DECLARE)) {
5✔
386
                        $atIndex = $tokens->getNextTokenOfKind($firstTokenIndex, [';']) + 1;
1✔
387
                    } else {
388
                        $atIndex = $namespace->getScopeStartIndex() + 1;
4✔
389
                    }
390
                }
391

392
                // Insert all registered FQCNs
393
                $this->createImportProcessor()->insertImports($tokens, $this->symbolsForImport, $atIndex);
22✔
394

395
                $this->symbolsForImport = [];
22✔
396
            }
397
        }
398
    }
399

400
    /**
401
     * @param _Uses $uses
402
     */
403
    private function refreshUsesCache(array $uses): void
404
    {
405
        if ($this->cacheUsesLast === $uses) {
140✔
406
            return;
138✔
407
        }
408

409
        $this->cacheUsesLast = $uses;
90✔
410

411
        $this->cacheUseNameByShortNameLower = [];
90✔
412
        $this->cacheUseShortNameByNameLower = [];
90✔
413

414
        foreach ($uses as $kind => $kindUses) {
90✔
415
            foreach ($kindUses as $useLongName => $useShortName) {
90✔
416
                $this->cacheUseNameByShortNameLower[$kind][strtolower($useShortName)] = $useLongName;
90✔
417

418
                /**
419
                 * @var class-string $normalisedUseLongName
420
                 *
421
                 * @phpstan-ignore varTag.nativeType
422
                 */
423
                $normalisedUseLongName = strtolower($useLongName);
90✔
424
                $this->cacheUseShortNameByNameLower[$kind][$normalisedUseLongName] = $useShortName;
90✔
425
            }
426
        }
427
    }
428

429
    private function isReservedIdentifier(string $symbol): bool
430
    {
431
        if (str_contains($symbol, '\\')) { // optimization only
144✔
432
            return false;
120✔
433
        }
434

435
        if ((new TypeAnalysis($symbol))->isReservedType()) {
134✔
436
            return true;
23✔
437
        }
438

439
        foreach ($this->reservedIdentifiersByLevel as $reservedIdentifiers) {
131✔
440
            if (isset($reservedIdentifiers[$symbol])) {
4✔
441
                return true;
4✔
442
            }
443
        }
444

445
        return false;
130✔
446
    }
447

448
    /**
449
     * Resolve absolute or relative symbol to normalized FQCN.
450
     *
451
     * @param _ImportType $importKind
452
     * @param _Uses       $uses
453
     *
454
     * @return class-string
455
     */
456
    private function resolveSymbol(string $symbol, string $importKind, array $uses, string $namespaceName): string
457
    {
458
        if (str_starts_with($symbol, '\\')) {
144✔
459
            return substr($symbol, 1); // @phpstan-ignore return.type
126✔
460
        }
461

462
        if ($this->isReservedIdentifier($symbol)) {
133✔
463
            return $symbol; // @phpstan-ignore return.type
25✔
464
        }
465

466
        $this->refreshUsesCache($uses);
127✔
467

468
        $symbolArr = explode('\\', $symbol, 2);
127✔
469
        $shortStartNameLower = strtolower($symbolArr[0]);
127✔
470
        if (isset($this->cacheUseNameByShortNameLower[$importKind][$shortStartNameLower])) {
127✔
471
            // @phpstan-ignore return.type
472
            return $this->cacheUseNameByShortNameLower[$importKind][$shortStartNameLower].(isset($symbolArr[1]) ? '\\'.$symbolArr[1] : '');
81✔
473
        }
474

475
        return ('' !== $namespaceName ? $namespaceName.'\\' : '').$symbol; // @phpstan-ignore return.type
80✔
476
    }
477

478
    /**
479
     * Shorten normalized FQCN as much as possible.
480
     *
481
     * @param _ImportType $importKind
482
     * @param _Uses       $uses
483
     */
484
    private function shortenSymbol(string $fqcn, string $importKind, array $uses, string $namespaceName): string
485
    {
486
        if ($this->isReservedIdentifier($fqcn)) {
144✔
487
            return $fqcn;
25✔
488
        }
489

490
        $this->refreshUsesCache($uses);
140✔
491

492
        $res = null;
140✔
493

494
        // try to shorten the name using namespace
495
        $iMin = 0;
140✔
496
        if (str_starts_with($fqcn, $namespaceName.'\\')) {
140✔
497
            $tmpRes = substr($fqcn, \strlen($namespaceName) + 1);
58✔
498
            if (!isset($this->cacheUseNameByShortNameLower[$importKind][strtolower(explode('\\', $tmpRes, 2)[0])]) && !$this->isReservedIdentifier($tmpRes)) {
58✔
499
                $res = $tmpRes;
54✔
500
                $iMin = substr_count($namespaceName, '\\') + 1;
54✔
501
            }
502
        }
503

504
        // try to shorten the name using uses
505
        $tmp = $fqcn;
140✔
506
        for ($i = substr_count($fqcn, '\\'); $i >= $iMin; --$i) {
140✔
507
            if (isset($this->cacheUseShortNameByNameLower[$importKind][strtolower($tmp)])) {
140✔
508
                $tmpRes = $this->cacheUseShortNameByNameLower[$importKind][strtolower($tmp)].substr($fqcn, \strlen($tmp));
81✔
509
                if (!$this->isReservedIdentifier($tmpRes)) {
81✔
510
                    $res = $tmpRes;
81✔
511

512
                    break;
81✔
513
                }
514
            }
515

516
            if ($i > 0) {
110✔
517
                $tmp = substr($tmp, 0, strrpos($tmp, '\\'));
84✔
518
            }
519
        }
520

521
        // shortening is not possible, add leading backslash if needed
522
        if (null === $res) {
140✔
523
            $res = $fqcn;
80✔
524
            if ('' !== $namespaceName
80✔
525
                || true === $this->configuration['leading_backslash_in_global_namespace']
80✔
526
                || isset($this->cacheUseNameByShortNameLower[$importKind][strtolower(explode('\\', $res, 2)[0])])
80✔
527
            ) {
528
                $res = '\\'.$res;
58✔
529
            }
530
        }
531

532
        return $res;
140✔
533
    }
534

535
    /**
536
     * @param _Uses $uses
537
     */
538
    private function setupUsesFromDiscoveredSymbols(array &$uses, string $namespaceName): void
539
    {
540
        foreach ($this->discoveredSymbols as $kind => $discoveredSymbols) {
36✔
541
            $discoveredFqcnByShortNameLower = [];
36✔
542

543
            if ('' === $namespaceName) {
36✔
544
                foreach ($discoveredSymbols as $symbol) {
8✔
545
                    if (!str_starts_with($symbol, '\\')) {
8✔
546
                        $shortStartName = explode('\\', ltrim($symbol, '\\'), 2)[0];
8✔
547
                        $shortStartNameLower = strtolower($shortStartName);
8✔
548
                        $discoveredFqcnByShortNameLower[$kind][$shortStartNameLower] = $this->resolveSymbol($shortStartName, $kind, $uses, $namespaceName);
8✔
549
                    }
550
                }
551
            }
552

553
            foreach ($uses[$kind] ?? [] as $useLongName => $useShortName) {
36✔
554
                $discoveredFqcnByShortNameLower[$kind][strtolower($useShortName)] = $useLongName;
24✔
555
            }
556

557
            $useByShortNameLower = [];
36✔
558
            foreach ($uses[$kind] ?? [] as $useShortName) {
36✔
559
                $useByShortNameLower[strtolower($useShortName)] = true;
24✔
560
            }
561

562
            uasort($discoveredSymbols, static function ($a, $b) {
36✔
563
                $res = str_starts_with($a, '\\') <=> str_starts_with($b, '\\');
34✔
564
                if (0 !== $res) {
34✔
565
                    return $res;
24✔
566
                }
567

568
                return substr_count($a, '\\') <=> substr_count($b, '\\');
28✔
569
            });
36✔
570
            foreach ($discoveredSymbols as $symbol) {
36✔
571
                while (true) {
36✔
572
                    $shortEndNameLower = strtolower(str_contains($symbol, '\\') ? substr($symbol, strrpos($symbol, '\\') + 1) : $symbol);
36✔
573
                    if (!isset($discoveredFqcnByShortNameLower[$kind][$shortEndNameLower])) {
36✔
574
                        $shortStartNameLower = strtolower(explode('\\', ltrim($symbol, '\\'), 2)[0]);
34✔
575
                        if (str_starts_with($symbol, '\\') || ('' === $namespaceName && !isset($useByShortNameLower[$shortStartNameLower]))
34✔
576
                            || !str_contains($symbol, '\\')
34✔
577
                        ) {
578
                            $discoveredFqcnByShortNameLower[$kind][$shortEndNameLower] = $this->resolveSymbol($symbol, $kind, $uses, $namespaceName);
34✔
579

580
                            break;
34✔
581
                        }
582
                    }
583
                    // else short name collision - keep unimported
584

585
                    if (str_starts_with($symbol, '\\') || '' === $namespaceName || !str_contains($symbol, '\\')) {
36✔
586
                        break;
36✔
587
                    }
588

589
                    $symbol = substr($symbol, 0, strrpos($symbol, '\\'));
5✔
590
                }
591
            }
592

593
            foreach ($uses[$kind] ?? [] as $useLongName => $useShortName) {
36✔
594
                $discoveredLongName = $discoveredFqcnByShortNameLower[$kind][strtolower($useShortName)] ?? null;
24✔
595
                if (strtolower($discoveredLongName) === strtolower($useLongName)) {
24✔
596
                    unset($discoveredFqcnByShortNameLower[$kind][strtolower($useShortName)]);
24✔
597
                }
598
            }
599

600
            foreach ($discoveredFqcnByShortNameLower[$kind] ?? [] as $fqcn) {
36✔
601
                $shortenedName = ltrim($this->shortenSymbol($fqcn, $kind, [], $namespaceName), '\\');
35✔
602
                if (str_contains($shortenedName, '\\')) { // prevent importing non-namespaced names in global namespace
35✔
603
                    $shortEndName = str_contains($fqcn, '\\') ? substr($fqcn, strrpos($fqcn, '\\') + 1) : $fqcn;
22✔
604
                    $uses[$kind][$fqcn] = $shortEndName;
22✔
605
                    $this->symbolsForImport[$kind][$shortEndName] = $fqcn;
22✔
606
                }
607
            }
608

609
            if (isset($this->symbolsForImport[$kind])) {
36✔
610
                ksort($this->symbolsForImport[$kind], \SORT_NATURAL);
22✔
611
            }
612
        }
613
    }
614

615
    /**
616
     * @param _Uses $uses
617
     */
618
    private function fixFunction(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index, array $uses, string $namespaceName): void
619
    {
620
        $arguments = $functionsAnalyzer->getFunctionArguments($tokens, $index);
87✔
621

622
        foreach ($arguments as $i => $argument) {
87✔
623
            $argument = $functionsAnalyzer->getFunctionArguments($tokens, $index)[$i];
79✔
624

625
            if ($argument->hasTypeAnalysis()) {
79✔
626
                $this->replaceByShortType($tokens, $argument->getTypeAnalysis(), $uses, $namespaceName);
66✔
627
            }
628
        }
629

630
        $returnTypeAnalysis = $functionsAnalyzer->getFunctionReturnType($tokens, $index);
87✔
631

632
        if (null !== $returnTypeAnalysis) {
87✔
633
            $this->replaceByShortType($tokens, $returnTypeAnalysis, $uses, $namespaceName);
32✔
634
        }
635
    }
636

637
    /**
638
     * @param _Uses $uses
639
     */
640
    private function fixPhpDoc(Tokens $tokens, int $index, array $uses, string $namespaceName): void
641
    {
642
        $allowedTags = $this->configuration['phpdoc_tags'];
35✔
643

644
        if ([] === $allowedTags) {
35✔
645
            return;
1✔
646
        }
647

648
        $phpDoc = $tokens[$index];
34✔
649
        $phpDocContent = $phpDoc->getContent();
34✔
650
        $phpDocContentNew = Preg::replaceCallback('/([*{]\h*@)(\S+)(\h+)('.TypeExpression::REGEX_TYPES.')(?!(?!\})\S)/', function ($matches) use ($allowedTags, $uses, $namespaceName) {
34✔
651
            if (!\in_array($matches[2], $allowedTags, true)) {
28✔
652
                return $matches[0];
7✔
653
            }
654

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

658
        if ($phpDocContentNew !== $phpDocContent) {
34✔
659
            $tokens[$index] = new Token([\T_DOC_COMMENT, $phpDocContentNew]);
21✔
660
        }
661
    }
662

663
    /**
664
     * @param _Uses $uses
665
     */
666
    private function fixPhpDocType(string $type, array $uses, string $namespaceName): string
667
    {
668
        $typeExpression = new TypeExpression($type, null, []);
27✔
669

670
        $typeExpression = $typeExpression->mapTypes(function (TypeExpression $type) use ($uses, $namespaceName) {
27✔
671
            $currentTypeValue = $type->toString();
27✔
672

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

677
            /** @var class-string $currentTypeValue */
678
            $shortTokens = $this->determineShortType($currentTypeValue, 'class', $uses, $namespaceName);
27✔
679

680
            if (null === $shortTokens) {
27✔
681
                return $type;
27✔
682
            }
683

684
            $newTypeValue = implode('', array_map(
21✔
685
                static fn (Token $token) => $token->getContent(),
21✔
686
                $shortTokens
21✔
687
            ));
21✔
688

689
            return $currentTypeValue === $newTypeValue
21✔
690
                ? $type
×
691
                : new TypeExpression($newTypeValue, null, []);
21✔
692
        });
27✔
693

694
        return $typeExpression->toString();
27✔
695
    }
696

697
    /**
698
     * @param _Uses $uses
699
     */
700
    private function fixExtendsImplements(Tokens $tokens, int $index, array $uses, string $namespaceName): void
701
    {
702
        // We handle `extends` and `implements` with similar logic, but we need to exit the loop under different conditions.
703
        $isExtends = $tokens[$index]->isGivenKind(\T_EXTENDS);
14✔
704
        $index = $tokens->getNextMeaningfulToken($index);
14✔
705

706
        $typeStartIndex = null;
14✔
707
        $typeEndIndex = null;
14✔
708

709
        while (true) {
14✔
710
            if ($tokens[$index]->equalsAny([',', '{', [\T_IMPLEMENTS]])) {
14✔
711
                if (null !== $typeStartIndex) {
14✔
712
                    $index += $this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName);
14✔
713
                }
714
                $typeStartIndex = null;
14✔
715

716
                if ($tokens[$index]->equalsAny($isExtends ? [[\T_IMPLEMENTS], '{'] : ['{'])) {
14✔
717
                    break;
14✔
718
                }
719
            } else {
720
                if (null === $typeStartIndex) {
14✔
721
                    $typeStartIndex = $index;
14✔
722
                }
723
                $typeEndIndex = $index;
14✔
724
            }
725

726
            $index = $tokens->getNextMeaningfulToken($index);
14✔
727
        }
728
    }
729

730
    /**
731
     * @param _Uses $uses
732
     */
733
    private function fixCatch(Tokens $tokens, int $index, array $uses, string $namespaceName): void
734
    {
735
        $index = $tokens->getNextMeaningfulToken($index); // '('
8✔
736
        $index = $tokens->getNextMeaningfulToken($index); // first part of first exception class to be caught
8✔
737

738
        $typeStartIndex = null;
8✔
739
        $typeEndIndex = null;
8✔
740

741
        while (true) {
8✔
742
            if ($tokens[$index]->equalsAny([')', [\T_VARIABLE], [CT::T_TYPE_ALTERNATION]])) {
8✔
743
                if (null === $typeStartIndex) {
8✔
744
                    break;
8✔
745
                }
746

747
                $index += $this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName);
8✔
748
                $typeStartIndex = null;
8✔
749

750
                if ($tokens[$index]->equals(')')) {
8✔
751
                    break;
1✔
752
                }
753
            } else {
754
                if (null === $typeStartIndex) {
8✔
755
                    $typeStartIndex = $index;
8✔
756
                }
757
                $typeEndIndex = $index;
8✔
758
            }
759

760
            $index = $tokens->getNextMeaningfulToken($index);
8✔
761
        }
762
    }
763

764
    /**
765
     * @param _Uses $uses
766
     */
767
    private function fixAttribute(Tokens $tokens, int $index, array $uses, string $namespaceName): void
768
    {
769
        $attributeAnalysis = AttributeAnalyzer::collectOne($tokens, $index);
2✔
770

771
        foreach ($attributeAnalysis->getAttributes() as $attribute) {
2✔
772
            $index = $attribute['start'];
2✔
773
            while ($tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) {
2✔
774
                $index = $tokens->getPrevMeaningfulToken($index);
2✔
775
            }
776
            $this->fixNextName($tokens, $index, $uses, $namespaceName);
2✔
777
        }
778
    }
779

780
    /**
781
     * @param _Uses $uses
782
     */
783
    private function fixPrevName(Tokens $tokens, int $index, array $uses, string $namespaceName): void
784
    {
785
        $typeStartIndex = null;
79✔
786
        $typeEndIndex = null;
79✔
787

788
        while (true) {
79✔
789
            $index = $tokens->getPrevMeaningfulToken($index);
79✔
790
            if ($tokens[$index]->isObjectOperator()) {
79✔
791
                break;
2✔
792
            }
793

794
            if ($tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) {
79✔
795
                $typeStartIndex = $index;
79✔
796
                if (null === $typeEndIndex) {
79✔
797
                    $typeEndIndex = $index;
79✔
798
                }
799
            } else {
800
                if (null !== $typeEndIndex) {
77✔
801
                    $this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName);
77✔
802
                }
803

804
                break;
77✔
805
            }
806
        }
807
    }
808

809
    /**
810
     * @param _Uses $uses
811
     */
812
    private function fixNextName(Tokens $tokens, int $index, array $uses, string $namespaceName): void
813
    {
814
        $typeStartIndex = null;
70✔
815
        $typeEndIndex = null;
70✔
816

817
        while (true) {
70✔
818
            $index = $tokens->getNextMeaningfulToken($index);
70✔
819

820
            if ($tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) {
70✔
821
                if (null === $typeStartIndex) {
65✔
822
                    $typeStartIndex = $index;
65✔
823
                }
824
                $typeEndIndex = $index;
65✔
825
            } else {
826
                if (null !== $typeStartIndex) {
70✔
827
                    $this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName);
65✔
828
                }
829

830
                break;
70✔
831
            }
832
        }
833
    }
834

835
    /**
836
     * @param _Uses $uses
837
     */
838
    private function shortenClassIfPossible(Tokens $tokens, int $typeStartIndex, int $typeEndIndex, array $uses, string $namespaceName): int
839
    {
840
        /** @var class-string $content */
841
        $content = $tokens->generatePartialCode($typeStartIndex, $typeEndIndex);
125✔
842
        $newTokens = $this->determineShortType($content, 'class', $uses, $namespaceName);
125✔
843
        if (null === $newTokens) {
125✔
844
            return 0;
125✔
845
        }
846

847
        $tokens->overrideRange($typeStartIndex, $typeEndIndex, $newTokens);
42✔
848

849
        return \count($newTokens) - ($typeEndIndex - $typeStartIndex) - 1;
42✔
850
    }
851

852
    /**
853
     * @param _Uses $uses
854
     */
855
    private function replaceByShortType(Tokens $tokens, TypeAnalysis $type, array $uses, string $namespaceName): void
856
    {
857
        $typeStartIndex = $type->getStartIndex();
74✔
858

859
        if ($tokens[$typeStartIndex]->isGivenKind(CT::T_NULLABLE_TYPE)) {
74✔
860
            $typeStartIndex = $tokens->getNextMeaningfulToken($typeStartIndex);
2✔
861
        }
862

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

865
        foreach ($types as [$startIndex, $endIndex]) {
74✔
866
            /** @var class-string $content */
867
            $content = $tokens->generatePartialCode($startIndex, $endIndex);
74✔
868
            $newTokens = $this->determineShortType($content, 'class', $uses, $namespaceName);
74✔
869
            if (null !== $newTokens) {
74✔
870
                $tokens->overrideRange($startIndex, $endIndex, $newTokens);
46✔
871
            }
872
        }
873
    }
874

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

891
            return null;
36✔
892
        }
893

894
        $fqcn = $this->resolveSymbol($typeName, $importKind, $uses, $namespaceName);
144✔
895
        $shortenedType = $this->shortenSymbol($fqcn, $importKind, $uses, $namespaceName);
144✔
896
        if ($shortenedType === $typeName) {
144✔
897
            return null;
144✔
898
        }
899

900
        return $this->namespacedStringToTokens($shortenedType);
101✔
901
    }
902

903
    /**
904
     * @return iterable<array{int, int}>
905
     */
906
    private function getTypes(Tokens $tokens, int $index, int $endIndex): iterable
907
    {
908
        $skipNextYield = false;
74✔
909
        $typeStartIndex = $typeEndIndex = null;
74✔
910
        while (true) {
74✔
911
            if ($tokens[$index]->isGivenKind(CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN)) {
74✔
912
                $index = $tokens->getNextMeaningfulToken($index);
1✔
913
                $typeStartIndex = $typeEndIndex = null;
1✔
914

915
                continue;
1✔
916
            }
917

918
            if (
919
                $tokens[$index]->isGivenKind([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE])
74✔
920
                || $index > $endIndex
74✔
921
            ) {
922
                if (!$skipNextYield && null !== $typeStartIndex) {
74✔
923
                    $origCount = \count($tokens);
74✔
924

925
                    yield [$typeStartIndex, $typeEndIndex];
74✔
926

927
                    $endIndex += \count($tokens) - $origCount;
74✔
928

929
                    // type tokens were possibly updated, restart type match
930
                    $skipNextYield = true;
74✔
931
                    $index = $typeEndIndex = $typeStartIndex;
74✔
932
                } else {
933
                    $skipNextYield = false;
74✔
934
                    $index = $tokens->getNextMeaningfulToken($index);
74✔
935
                    $typeStartIndex = $typeEndIndex = null;
74✔
936
                }
937

938
                if ($index > $endIndex) {
74✔
939
                    break;
74✔
940
                }
941

942
                continue;
74✔
943
            }
944

945
            if (null === $typeStartIndex) {
74✔
946
                $typeStartIndex = $index;
74✔
947
            }
948
            $typeEndIndex = $index;
74✔
949

950
            $index = $tokens->getNextMeaningfulToken($index);
74✔
951
        }
952
    }
953

954
    /**
955
     * @return non-empty-list<Token>
956
     */
957
    private function namespacedStringToTokens(string $input): array
958
    {
959
        $tokens = [];
101✔
960

961
        if (str_starts_with($input, '\\')) {
101✔
962
            $tokens[] = new Token([\T_NS_SEPARATOR, '\\']);
11✔
963
            $input = substr($input, 1);
11✔
964
        }
965

966
        $parts = explode('\\', $input);
101✔
967
        foreach ($parts as $index => $part) {
101✔
968
            $tokens[] = new Token([\T_STRING, $part]);
101✔
969

970
            if ($index !== \count($parts) - 1) {
101✔
971
                $tokens[] = new Token([\T_NS_SEPARATOR, '\\']);
22✔
972
            }
973
        }
974

975
        return $tokens;
101✔
976
    }
977

978
    /**
979
     * We need to create import processor dynamically (not in costructor), because actual whitespace configuration
980
     * is set later, not when fixer's instance is created.
981
     */
982
    private function createImportProcessor(): ImportProcessor
983
    {
984
        return new ImportProcessor($this->whitespacesConfig);
22✔
985
    }
986
}
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