Browse Source

fix: import detection for attributes at `NoUnusedImportsFixer` (#7246)

Javier Spagnoletti 1 year ago
parent
commit
93eb1d4d75

+ 4 - 4
src/Fixer/Import/NoUnusedImportsFixer.php

@@ -131,10 +131,6 @@ final class NoUnusedImportsFixer extends AbstractFixer
                     continue;
                 }
 
-                if ($inAttribute) {
-                    return true;
-                }
-
                 $prevMeaningfulToken = $tokens[$tokens->getPrevMeaningfulToken($index)];
 
                 if ($prevMeaningfulToken->isGivenKind(T_NAMESPACE)) {
@@ -150,6 +146,10 @@ final class NoUnusedImportsFixer extends AbstractFixer
                     continue;
                 }
 
+                if ($inAttribute) {
+                    return true;
+                }
+
                 $nextMeaningfulIndex = $tokens->getNextMeaningfulToken($index);
 
                 if ($gotoLabelAnalyzer->belongsToGoToLabel($tokens, $nextMeaningfulIndex)) {

+ 34 - 0
tests/Fixer/Import/NoUnusedImportsFixerTest.php

@@ -630,6 +630,40 @@ final class NoUnusedImportsFixerTest extends AbstractFixerTestCase
             ,
         ];
 
+        yield 'no_import_in_global_namespace' => [
+            <<<'EOF'
+                <?php
+                namespace A;
+                new \SplFileInfo(__FILE__);
+                EOF
+            ,
+            <<<'EOF'
+                <?php
+                namespace A;
+                use SplFileInfo;
+                new \SplFileInfo(__FILE__);
+                EOF
+            ,
+        ];
+
+        yield 'no_import_attribute_in_global_namespace' => [
+            <<<'EOF'
+                <?php
+                namespace A;
+                #[\Attribute(\Attribute::TARGET_PROPERTY)]
+                final class B {}
+                EOF
+            ,
+            <<<'EOF'
+                <?php
+                namespace A;
+                use Attribute;
+                #[\Attribute(\Attribute::TARGET_PROPERTY)]
+                final class B {}
+                EOF
+            ,
+        ];
+
         yield 'use_as_last_statement' => [
             <<<'EOF'
                 <?php