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

keradus / PHP-CS-Fixer / 18589345849

16 Oct 2025 09:31PM UTC coverage: 94.158% (+0.01%) from 94.148%
18589345849

push

github

web-flow
docs: update usage documentation for describe `--expand` and `@` (#9119)

28675 of 30454 relevant lines covered (94.16%)

45.16 hits per line

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

99.29
/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<non-empty-string, non-empty-string>,
52
 *   class?: array<non-empty-string, non-empty-string>,
53
 *   function?: array<non-empty-string, non-empty-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<non-empty-string>,
80
     *     class?: list<non-empty-string>,
81
     *     function?: list<non-empty-string>
82
     * }
83
     */
84
    private ?array $discoveredSymbols;
85

86
    /**
87
     * @var array{
88
     *     constant?: array<string, non-empty-string>,
89
     *     class?: array<string, non-empty-string>,
90
     *     function?: array<string, non-empty-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<non-empty-lowercase-string, non-empty-string>,
112
     *     class?: array<non-empty-lowercase-string, non-empty-string>,
113
     *     function?: array<non-empty-lowercase-string, non-empty-string>
114
     * }
115
     */
116
    private array $cacheUseNameByShortNameLower;
117

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

121
    /** @var _Uses */
122
    private array $cacheUseShortNameByNormalizedName;
123

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

133
                        use Foo\Bar;
134
                        use Foo\Bar\Baz;
135
                        use Foo\OtherClass;
136
                        use Foo\SomeContract;
137
                        use Foo\SomeException;
138

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

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

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

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

170
                        PHP
3✔
171
                ),
3✔
172
                new CodeSample(
3✔
173
                    <<<'PHP'
3✔
174
                        <?php
175

176
                        class SomeClass
177
                        {
178
                            public function doY(Foo\NotImported $u, \Foo\NotImported $v)
179
                            {
180
                            }
181
                        }
182

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

202
                        PHP,
3✔
203
                    ['leading_backslash_in_global_namespace' => true]
3✔
204
                ),
3✔
205
                new CodeSample(
3✔
206
                    <<<'PHP'
3✔
207
                        <?php
208

209
                        namespace Foo\Test;
210

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

224
                        PHP,
3✔
225
                    ['import_symbols' => true]
3✔
226
                ),
3✔
227
            ]
3✔
228
        );
3✔
229
    }
230

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

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

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

307
    protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
308
    {
309
        $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer();
153✔
310
        $functionsAnalyzer = new FunctionsAnalyzer();
153✔
311

312
        $this->symbolsForImport = [];
153✔
313

314
        foreach ($tokens->getNamespaceDeclarations() as $namespaceIndex => $namespace) {
153✔
315
            $namespace = $tokens->getNamespaceDeclarations()[$namespaceIndex];
153✔
316

317
            $namespaceName = $namespace->getFullName();
153✔
318

319
            $uses = [];
153✔
320
            $lastUse = null;
153✔
321

322
            foreach ($namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace, true) as $use) {
153✔
323
                if (!$use->isClass()) {
99✔
324
                    continue;
6✔
325
                }
326

327
                $fullName = ltrim($use->getFullName(), '\\');
98✔
328
                \assert('' !== $fullName);
98✔
329
                $uses[$use->getHumanFriendlyType()][$fullName] = $use->getShortName();
98✔
330
                $lastUse = $use;
98✔
331
            }
332

333
            $indexDiff = 0;
153✔
334
            foreach (true === $this->configuration['import_symbols'] ? [true, false] : [false] as $discoverSymbolsPhase) {
153✔
335
                $this->discoveredSymbols = $discoverSymbolsPhase ? [] : null;
153✔
336

337
                $openedCurlyBrackets = 0;
153✔
338
                $this->reservedIdentifiersByLevel = [];
153✔
339

340
                for ($index = $namespace->getScopeStartIndex(); $index < $namespace->getScopeEndIndex() + $indexDiff; ++$index) {
153✔
341
                    $origSize = \count($tokens);
153✔
342
                    $token = $tokens[$index];
153✔
343

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

378
                        $this->fixPhpDoc($tokens, $index, $uses, $namespaceName);
35✔
379
                    }
380

381
                    $indexDiff += \count($tokens) - $origSize;
153✔
382
                }
383

384
                $this->reservedIdentifiersByLevel = [];
153✔
385

386
                if ($discoverSymbolsPhase) {
153✔
387
                    $this->setupUsesFromDiscoveredSymbols($uses, $namespaceName);
38✔
388
                }
389
            }
390

391
            if ([] !== $this->symbolsForImport) {
153✔
392
                if (null !== $lastUse) {
24✔
393
                    $atIndex = $lastUse->getEndIndex() + 1;
6✔
394
                } elseif (0 !== $namespace->getEndIndex()) {
18✔
395
                    $atIndex = $namespace->getEndIndex() + 1;
13✔
396
                } else {
397
                    $firstTokenIndex = $tokens->getNextMeaningfulToken($namespace->getScopeStartIndex());
5✔
398
                    if (null !== $firstTokenIndex && $tokens[$firstTokenIndex]->isGivenKind(\T_DECLARE)) {
5✔
399
                        $atIndex = $tokens->getNextTokenOfKind($firstTokenIndex, [';']) + 1;
1✔
400
                    } else {
401
                        $atIndex = $namespace->getScopeStartIndex() + 1;
4✔
402
                    }
403
                }
404

405
                // Insert all registered FQCNs
406
                $this->createImportProcessor()->insertImports($tokens, $this->symbolsForImport, $atIndex);
24✔
407

408
                $this->symbolsForImport = [];
24✔
409
            }
410
        }
411
    }
412

413
    /**
414
     * @param _Uses $uses
415
     */
416
    private function refreshUsesCache(array $uses): void
417
    {
418
        if ($this->cacheUsesLast === $uses) {
144✔
419
            return;
142✔
420
        }
421

422
        $this->cacheUsesLast = $uses;
94✔
423

424
        $this->cacheUseNameByShortNameLower = [];
94✔
425
        $this->cacheUseShortNameByName = [];
94✔
426
        $this->cacheUseShortNameByNormalizedName = [];
94✔
427

428
        foreach ($uses as $kind => $kindUses) {
94✔
429
            foreach ($kindUses as $useLongName => $useShortName) {
94✔
430
                $this->cacheUseNameByShortNameLower[$kind][strtolower($useShortName)] = $useLongName;
94✔
431
                $this->cacheUseShortNameByName[$kind][$useLongName] = $useShortName;
94✔
432

433
                /** @var non-empty-string */
434
                $normalizedUseLongName = $this->normalizeFqcn($useLongName);
94✔
435
                $this->cacheUseShortNameByNormalizedName[$kind][$normalizedUseLongName] = $useShortName;
94✔
436
            }
437
        }
438
    }
439

440
    private function isReservedIdentifier(string $symbol): bool
441
    {
442
        if (str_contains($symbol, '\\')) { // optimization only
148✔
443
            return false;
124✔
444
        }
445

446
        if ((new TypeAnalysis($symbol))->isReservedType()) {
138✔
447
            return true;
23✔
448
        }
449

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

456
        return false;
134✔
457
    }
458

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

473
        if ($this->isReservedIdentifier($symbol)) {
137✔
474
            return $symbol; // @phpstan-ignore return.type
25✔
475
        }
476

477
        $this->refreshUsesCache($uses);
131✔
478

479
        $symbolArr = explode('\\', $symbol, 2);
131✔
480
        $shortStartNameLower = strtolower($symbolArr[0]);
131✔
481
        if (isset($this->cacheUseNameByShortNameLower[$importKind][$shortStartNameLower])) {
131✔
482
            return $this->cacheUseNameByShortNameLower[$importKind][$shortStartNameLower].(isset($symbolArr[1]) ? '\\'.$symbolArr[1] : '');
85✔
483
        }
484

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

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

500
        $this->refreshUsesCache($uses);
144✔
501

502
        $res = null;
144✔
503

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

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

522
                    break;
85✔
523
                }
524
            }
525

526
            if ($i > 0) {
115✔
527
                $tmp = substr($tmp, 0, strrpos($tmp, '\\'));
89✔
528
            }
529
        }
530

531
        if (null === $res) {
144✔
532
            $normalizedFqcn = $this->normalizeFqcn($fqcn);
85✔
533
            $tmpRes = $this->cacheUseShortNameByNormalizedName[$importKind][$normalizedFqcn] ?? null;
85✔
534
            if (null !== $tmpRes && !$this->isReservedIdentifier($tmpRes)) {
85✔
535
                $res = $tmpRes;
1✔
536
            }
537
        }
538

539
        // shortening is not possible, add leading backslash if needed
540
        if (null === $res) {
144✔
541
            $res = $fqcn;
84✔
542
            if ('' !== $namespaceName
84✔
543
                || true === $this->configuration['leading_backslash_in_global_namespace']
84✔
544
                || isset($this->cacheUseNameByShortNameLower[$importKind][strtolower(explode('\\', $res, 2)[0])])
84✔
545
            ) {
546
                $res = '\\'.$res;
62✔
547
            }
548
        }
549

550
        return $res;
144✔
551
    }
552

553
    /**
554
     * @param _Uses $uses
555
     */
556
    private function setupUsesFromDiscoveredSymbols(array &$uses, string $namespaceName): void
557
    {
558
        foreach ($this->discoveredSymbols as $kind => $discoveredSymbols) {
38✔
559
            $discoveredFqcnByShortNameLower = [];
38✔
560

561
            if ('' === $namespaceName) {
38✔
562
                foreach ($discoveredSymbols as $symbol) {
10✔
563
                    if (!str_starts_with($symbol, '\\')) {
10✔
564
                        $shortStartName = explode('\\', ltrim($symbol, '\\'), 2)[0];
10✔
565
                        \assert('' !== $shortStartName);
10✔
566
                        $shortStartNameLower = strtolower($shortStartName);
10✔
567
                        $discoveredFqcnByShortNameLower[$kind][$shortStartNameLower] = $this->resolveSymbol($shortStartName, $kind, $uses, $namespaceName);
10✔
568
                    }
569
                }
570
            }
571

572
            foreach ($uses[$kind] ?? [] as $useLongName => $useShortName) {
38✔
573
                $discoveredFqcnByShortNameLower[$kind][strtolower($useShortName)] = $useLongName;
26✔
574
            }
575

576
            $useByShortNameLower = [];
38✔
577
            foreach ($uses[$kind] ?? [] as $useShortName) {
38✔
578
                $useByShortNameLower[strtolower($useShortName)] = true;
26✔
579
            }
580

581
            uasort($discoveredSymbols, static function ($a, $b) {
38✔
582
                $res = str_starts_with($a, '\\') <=> str_starts_with($b, '\\');
36✔
583
                if (0 !== $res) {
36✔
584
                    return $res;
26✔
585
                }
586

587
                return substr_count($a, '\\') <=> substr_count($b, '\\');
30✔
588
            });
38✔
589
            foreach ($discoveredSymbols as $symbol) {
38✔
590
                while (true) {
38✔
591
                    $shortEndNameLower = strtolower(str_contains($symbol, '\\') ? substr($symbol, strrpos($symbol, '\\') + 1) : $symbol);
38✔
592
                    if (!isset($discoveredFqcnByShortNameLower[$kind][$shortEndNameLower])) {
38✔
593
                        $shortStartNameLower = strtolower(explode('\\', ltrim($symbol, '\\'), 2)[0]);
36✔
594
                        if (str_starts_with($symbol, '\\') || ('' === $namespaceName && !isset($useByShortNameLower[$shortStartNameLower]))
36✔
595
                            || !str_contains($symbol, '\\')
36✔
596
                        ) {
597
                            $discoveredFqcnByShortNameLower[$kind][$shortEndNameLower] = $this->resolveSymbol($symbol, $kind, $uses, $namespaceName);
36✔
598

599
                            break;
36✔
600
                        }
601
                    }
602
                    // else short name collision - keep unimported
603

604
                    if (str_starts_with($symbol, '\\') || '' === $namespaceName || !str_contains($symbol, '\\')) {
38✔
605
                        break;
38✔
606
                    }
607

608
                    $symbol = substr($symbol, 0, strrpos($symbol, '\\'));
5✔
609
                }
610
            }
611

612
            foreach ($uses[$kind] ?? [] as $useLongName => $useShortName) {
38✔
613
                $discoveredLongName = $discoveredFqcnByShortNameLower[$kind][strtolower($useShortName)] ?? null;
26✔
614
                if (strtolower($discoveredLongName) === strtolower($useLongName)) {
26✔
615
                    unset($discoveredFqcnByShortNameLower[$kind][strtolower($useShortName)]);
26✔
616
                }
617
            }
618

619
            foreach ($discoveredFqcnByShortNameLower[$kind] ?? [] as $fqcn) {
38✔
620
                $shortenedName = ltrim($this->shortenSymbol($fqcn, $kind, [], $namespaceName), '\\');
37✔
621
                if (str_contains($shortenedName, '\\')) { // prevent importing non-namespaced names in global namespace
37✔
622
                    $shortEndName = str_contains($fqcn, '\\') ? substr($fqcn, strrpos($fqcn, '\\') + 1) : $fqcn;
24✔
623
                    \assert('' !== $shortEndName);
24✔
624
                    $uses[$kind][$fqcn] = $shortEndName;
24✔
625
                    $this->symbolsForImport[$kind][$shortEndName] = $fqcn;
24✔
626
                }
627
            }
628

629
            if (isset($this->symbolsForImport[$kind])) {
38✔
630
                ksort($this->symbolsForImport[$kind], \SORT_NATURAL);
24✔
631
            }
632
        }
633
    }
634

635
    /**
636
     * @param _Uses $uses
637
     */
638
    private function fixFunction(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index, array $uses, string $namespaceName): void
639
    {
640
        $arguments = $functionsAnalyzer->getFunctionArguments($tokens, $index);
91✔
641

642
        foreach ($arguments as $i => $argument) {
91✔
643
            $argument = $functionsAnalyzer->getFunctionArguments($tokens, $index)[$i];
79✔
644

645
            if ($argument->hasTypeAnalysis()) {
79✔
646
                $this->replaceByShortType($tokens, $argument->getTypeAnalysis(), $uses, $namespaceName);
66✔
647
            }
648
        }
649

650
        $returnTypeAnalysis = $functionsAnalyzer->getFunctionReturnType($tokens, $index);
91✔
651

652
        if (null !== $returnTypeAnalysis) {
91✔
653
            $this->replaceByShortType($tokens, $returnTypeAnalysis, $uses, $namespaceName);
32✔
654
        }
655
    }
656

657
    /**
658
     * @param _Uses $uses
659
     */
660
    private function fixPhpDoc(Tokens $tokens, int $index, array $uses, string $namespaceName): void
661
    {
662
        $allowedTags = $this->configuration['phpdoc_tags'];
35✔
663

664
        if ([] === $allowedTags) {
35✔
665
            return;
1✔
666
        }
667

668
        $phpDoc = $tokens[$index];
34✔
669
        $phpDocContent = $phpDoc->getContent();
34✔
670
        $phpDocContentNew = Preg::replaceCallback('/([*{]\h*@)(\S+)(\h+)('.TypeExpression::REGEX_TYPES.')(?!(?!\})\S)/', function ($matches) use ($allowedTags, $uses, $namespaceName) {
34✔
671
            if (!\in_array($matches[2], $allowedTags, true)) {
28✔
672
                return $matches[0];
7✔
673
            }
674

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

678
        if ($phpDocContentNew !== $phpDocContent) {
34✔
679
            $tokens[$index] = new Token([\T_DOC_COMMENT, $phpDocContentNew]);
21✔
680
        }
681
    }
682

683
    /**
684
     * @param _Uses $uses
685
     */
686
    private function fixPhpDocType(string $type, array $uses, string $namespaceName): string
687
    {
688
        $typeExpression = new TypeExpression($type, null, []);
27✔
689

690
        $typeExpression = $typeExpression->mapTypes(function (TypeExpression $type) use ($uses, $namespaceName) {
27✔
691
            $currentTypeValue = $type->toString();
27✔
692

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

697
            /** @var non-empty-string $currentTypeValue */
698
            $shortTokens = $this->determineShortType($currentTypeValue, 'class', $uses, $namespaceName);
27✔
699

700
            if (null === $shortTokens) {
27✔
701
                return $type;
27✔
702
            }
703

704
            $newTypeValue = implode('', array_map(
21✔
705
                static fn (Token $token) => $token->getContent(),
21✔
706
                $shortTokens
21✔
707
            ));
21✔
708

709
            return $currentTypeValue === $newTypeValue
21✔
710
                ? $type
×
711
                : new TypeExpression($newTypeValue, null, []);
21✔
712
        });
27✔
713

714
        return $typeExpression->toString();
27✔
715
    }
716

717
    /**
718
     * @param _Uses $uses
719
     */
720
    private function fixExtendsImplements(Tokens $tokens, int $index, array $uses, string $namespaceName): void
721
    {
722
        // We handle `extends` and `implements` with similar logic, but we need to exit the loop under different conditions.
723
        $isExtends = $tokens[$index]->isGivenKind(\T_EXTENDS);
18✔
724
        $index = $tokens->getNextMeaningfulToken($index);
18✔
725

726
        $typeStartIndex = null;
18✔
727
        $typeEndIndex = null;
18✔
728

729
        while (true) {
18✔
730
            if ($tokens[$index]->equalsAny([',', '{', [\T_IMPLEMENTS]])) {
18✔
731
                if (null !== $typeStartIndex) {
18✔
732
                    $index += $this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName);
18✔
733
                }
734
                $typeStartIndex = null;
18✔
735

736
                if ($tokens[$index]->equalsAny($isExtends ? [[\T_IMPLEMENTS], '{'] : ['{'])) {
18✔
737
                    break;
18✔
738
                }
739
            } else {
740
                if (null === $typeStartIndex) {
18✔
741
                    $typeStartIndex = $index;
18✔
742
                }
743
                $typeEndIndex = $index;
18✔
744
            }
745

746
            $index = $tokens->getNextMeaningfulToken($index);
18✔
747
        }
748
    }
749

750
    /**
751
     * @param _Uses $uses
752
     */
753
    private function fixCatch(Tokens $tokens, int $index, array $uses, string $namespaceName): void
754
    {
755
        $index = $tokens->getNextMeaningfulToken($index); // '('
8✔
756
        $index = $tokens->getNextMeaningfulToken($index); // first part of first exception class to be caught
8✔
757

758
        $typeStartIndex = null;
8✔
759
        $typeEndIndex = null;
8✔
760

761
        while (true) {
8✔
762
            if ($tokens[$index]->equalsAny([')', [\T_VARIABLE], [CT::T_TYPE_ALTERNATION]])) {
8✔
763
                if (null === $typeStartIndex) {
8✔
764
                    break;
8✔
765
                }
766

767
                $index += $this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName);
8✔
768
                $typeStartIndex = null;
8✔
769

770
                if ($tokens[$index]->equals(')')) {
8✔
771
                    break;
1✔
772
                }
773
            } else {
774
                if (null === $typeStartIndex) {
8✔
775
                    $typeStartIndex = $index;
8✔
776
                }
777
                $typeEndIndex = $index;
8✔
778
            }
779

780
            $index = $tokens->getNextMeaningfulToken($index);
8✔
781
        }
782
    }
783

784
    /**
785
     * @param _Uses $uses
786
     */
787
    private function fixAttribute(Tokens $tokens, int $index, array $uses, string $namespaceName): void
788
    {
789
        $attributeAnalysis = AttributeAnalyzer::collectOne($tokens, $index);
2✔
790

791
        foreach ($attributeAnalysis->getAttributes() as $attribute) {
2✔
792
            $index = $attribute['start'];
2✔
793
            while ($tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) {
2✔
794
                $index = $tokens->getPrevMeaningfulToken($index);
2✔
795
            }
796
            $this->fixNextName($tokens, $index, $uses, $namespaceName);
2✔
797
        }
798
    }
799

800
    /**
801
     * @param _Uses $uses
802
     */
803
    private function fixPrevName(Tokens $tokens, int $index, array $uses, string $namespaceName): void
804
    {
805
        $typeStartIndex = null;
83✔
806
        $typeEndIndex = null;
83✔
807

808
        while (true) {
83✔
809
            $index = $tokens->getPrevMeaningfulToken($index);
83✔
810
            if ($tokens[$index]->isObjectOperator()) {
83✔
811
                break;
2✔
812
            }
813

814
            if ($tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) {
83✔
815
                $typeStartIndex = $index;
83✔
816
                if (null === $typeEndIndex) {
83✔
817
                    $typeEndIndex = $index;
83✔
818
                }
819
            } else {
820
                if (null !== $typeEndIndex) {
81✔
821
                    $this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName);
81✔
822
                }
823

824
                break;
81✔
825
            }
826
        }
827
    }
828

829
    /**
830
     * @param _Uses $uses
831
     */
832
    private function fixNextName(Tokens $tokens, int $index, array $uses, string $namespaceName): void
833
    {
834
        $typeStartIndex = null;
74✔
835
        $typeEndIndex = null;
74✔
836

837
        while (true) {
74✔
838
            $index = $tokens->getNextMeaningfulToken($index);
74✔
839

840
            if ($tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) {
74✔
841
                if (null === $typeStartIndex) {
69✔
842
                    $typeStartIndex = $index;
69✔
843
                }
844
                $typeEndIndex = $index;
69✔
845
            } else {
846
                if (null !== $typeStartIndex) {
74✔
847
                    $this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName);
69✔
848
                }
849

850
                break;
74✔
851
            }
852
        }
853
    }
854

855
    /**
856
     * @param _Uses $uses
857
     */
858
    private function shortenClassIfPossible(Tokens $tokens, int $typeStartIndex, int $typeEndIndex, array $uses, string $namespaceName): int
859
    {
860
        /** @var non-empty-string $content */
861
        $content = $tokens->generatePartialCode($typeStartIndex, $typeEndIndex);
129✔
862
        $newTokens = $this->determineShortType($content, 'class', $uses, $namespaceName);
129✔
863
        if (null === $newTokens) {
129✔
864
            return 0;
129✔
865
        }
866

867
        $tokens->overrideRange($typeStartIndex, $typeEndIndex, $newTokens);
44✔
868

869
        return \count($newTokens) - ($typeEndIndex - $typeStartIndex) - 1;
44✔
870
    }
871

872
    /**
873
     * @param _Uses $uses
874
     */
875
    private function replaceByShortType(Tokens $tokens, TypeAnalysis $type, array $uses, string $namespaceName): void
876
    {
877
        $typeStartIndex = $type->getStartIndex();
74✔
878

879
        if ($tokens[$typeStartIndex]->isGivenKind(CT::T_NULLABLE_TYPE)) {
74✔
880
            $typeStartIndex = $tokens->getNextMeaningfulToken($typeStartIndex);
2✔
881
        }
882

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

885
        foreach ($types as [$startIndex, $endIndex]) {
74✔
886
            /** @var non-empty-string $content */
887
            $content = $tokens->generatePartialCode($startIndex, $endIndex);
74✔
888
            $newTokens = $this->determineShortType($content, 'class', $uses, $namespaceName);
74✔
889
            if (null !== $newTokens) {
74✔
890
                $tokens->overrideRange($startIndex, $endIndex, $newTokens);
46✔
891
            }
892
        }
893
    }
894

895
    /**
896
     * Determines short type based on FQCN, current namespace and imports (`use` declarations).
897
     *
898
     * @param non-empty-string $typeName
899
     * @param _ImportType      $importKind
900
     * @param _Uses            $uses
901
     *
902
     * @return null|non-empty-list<Token>
903
     */
904
    private function determineShortType(string $typeName, string $importKind, array $uses, string $namespaceName): ?array
905
    {
906
        if (null !== $this->discoveredSymbols) {
148✔
907
            if (!$this->isReservedIdentifier($typeName)) {
38✔
908
                $this->discoveredSymbols[$importKind][] = $typeName;
38✔
909
            }
910

911
            return null;
38✔
912
        }
913

914
        $fqcn = $this->resolveSymbol($typeName, $importKind, $uses, $namespaceName);
148✔
915
        $shortenedType = $this->shortenSymbol($fqcn, $importKind, $uses, $namespaceName);
148✔
916
        if ($shortenedType === $typeName) {
148✔
917
            return null;
148✔
918
        }
919

920
        return $this->namespacedStringToTokens($shortenedType);
103✔
921
    }
922

923
    /**
924
     * @return iterable<array{int, int}>
925
     */
926
    private function getTypes(Tokens $tokens, int $index, int $endIndex): iterable
927
    {
928
        $skipNextYield = false;
74✔
929
        $typeStartIndex = $typeEndIndex = null;
74✔
930
        while (true) {
74✔
931
            if ($tokens[$index]->isGivenKind(CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN)) {
74✔
932
                $index = $tokens->getNextMeaningfulToken($index);
1✔
933
                $typeStartIndex = $typeEndIndex = null;
1✔
934

935
                continue;
1✔
936
            }
937

938
            if (
939
                $tokens[$index]->isGivenKind([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE])
74✔
940
                || $index > $endIndex
74✔
941
            ) {
942
                if (!$skipNextYield && null !== $typeStartIndex) {
74✔
943
                    $origCount = \count($tokens);
74✔
944

945
                    yield [$typeStartIndex, $typeEndIndex];
74✔
946

947
                    $endIndex += \count($tokens) - $origCount;
74✔
948

949
                    // type tokens were possibly updated, restart type match
950
                    $skipNextYield = true;
74✔
951
                    $index = $typeEndIndex = $typeStartIndex;
74✔
952
                } else {
953
                    $skipNextYield = false;
74✔
954
                    $index = $tokens->getNextMeaningfulToken($index);
74✔
955
                    $typeStartIndex = $typeEndIndex = null;
74✔
956
                }
957

958
                if ($index > $endIndex) {
74✔
959
                    break;
74✔
960
                }
961

962
                continue;
74✔
963
            }
964

965
            if (null === $typeStartIndex) {
74✔
966
                $typeStartIndex = $index;
74✔
967
            }
968
            $typeEndIndex = $index;
74✔
969

970
            $index = $tokens->getNextMeaningfulToken($index);
74✔
971
        }
972
    }
973

974
    /**
975
     * @return non-empty-list<Token>
976
     */
977
    private function namespacedStringToTokens(string $input): array
978
    {
979
        $tokens = [];
103✔
980

981
        if (str_starts_with($input, '\\')) {
103✔
982
            $tokens[] = new Token([\T_NS_SEPARATOR, '\\']);
11✔
983
            $input = substr($input, 1);
11✔
984
        }
985

986
        $parts = explode('\\', $input);
103✔
987
        foreach ($parts as $index => $part) {
103✔
988
            $tokens[] = new Token([\T_STRING, $part]);
103✔
989

990
            if ($index !== \count($parts) - 1) {
103✔
991
                $tokens[] = new Token([\T_NS_SEPARATOR, '\\']);
22✔
992
            }
993
        }
994

995
        return $tokens;
103✔
996
    }
997

998
    private function normalizeFqcn(string $input): string
999
    {
1000
        $backslashPosition = strrpos($input, '\\');
133✔
1001
        if (false === $backslashPosition) {
133✔
1002
            return strtolower($input);
54✔
1003
        }
1004

1005
        $namespacePartEndPosition = $backslashPosition + 1;
115✔
1006
        $mainPart = substr($input, 0, $namespacePartEndPosition);
115✔
1007
        $lastPart = substr($input, $namespacePartEndPosition);
115✔
1008

1009
        return $mainPart.strtolower($lastPart);
115✔
1010
    }
1011

1012
    /**
1013
     * We need to create import processor dynamically (not in constructor), because actual whitespace configuration
1014
     * is set later, not when fixer's instance is created.
1015
     */
1016
    private function createImportProcessor(): ImportProcessor
1017
    {
1018
        return new ImportProcessor($this->whitespacesConfig);
24✔
1019
    }
1020
}
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