Browse Source

bug: FullyQualifiedStrictTypesFixer - fix for FQCN type with class with the same name being imported (#6923)

Co-authored-by: Greg Korba <greg@codito.dev>
Kuba Werłos 1 year ago
parent
commit
aa3955e815

+ 11 - 0
src/Fixer/Import/FullyQualifiedStrictTypesFixer.php

@@ -177,6 +177,17 @@ class SomeClass
             } elseif ($typeNameLower !== $namespaceName && str_starts_with($typeNameLower, $namespaceName)) {
                 // if the type starts with namespace and the type is not the same as the namespace it can be shortened
                 $typeNameShort = substr($typeName, $namespaceNameLength + 1);
+
+                // if short names are the same, but long one are different then it cannot be shortened
+                foreach ($uses as $useLongName => $useShortName) {
+                    if (
+                        strtolower($typeNameShort) === strtolower($useShortName)
+                        && strtolower($typeName) !== strtolower($useLongName)
+                    ) {
+                        continue 2;
+                    }
+                }
+
                 $tokens->overrideRange($startIndex, $endIndex, $this->namespacedStringToTokens($typeNameShort));
             }
         }

+ 13 - 1
tests/Fixer/Import/FullyQualifiedStrictTypesFixerTest.php

@@ -527,7 +527,7 @@ class SomeClass
     public function doSomething(
         \Ping\Something $something,
         Pung\Pang $other,
-        Pung $other1,
+        \Ping\Pong\Pung $other1,
         Pang\Pung $other2,
         Pyng\Pung\Pong $other3,
         \Foo\Bar\Baz\Buz $other4
@@ -576,6 +576,18 @@ namespace {
     }
 ',
         ];
+
+        yield 'Test FQCN is not removed when class with the same name, but different namespace, is imported' => [
+            '<?php namespace Foo;
+                use Bar\TheClass;
+                class Test
+                {
+                    public function __construct(
+                        \Foo\TheClass $x
+                    ) {}
+                }
+            ',
+        ];
     }
 
     public static function provideCodeWithReturnTypesCasesWithNullableCases(): array