Browse Source

fix: NoUnneededBracesFixer - improve handling of global namespace (#7639)

Co-authored-by: Greg Korba <wirone@gmail.com>
Dariusz Rumiński 1 year ago
parent
commit
858cd04ec0

+ 10 - 2
src/Fixer/ControlStructure/NoUnneededBracesFixer.php

@@ -134,9 +134,17 @@ namespace Foo {
 
         $index = $tokens->getNextTokenOfKind(0, [[T_NAMESPACE]]);
 
-        do {
+        $namespaceIsNamed = false;
+
+        $index = $tokens->getNextMeaningfulToken($index);
+        while ($tokens[$index]->isGivenKind([T_STRING, T_NS_SEPARATOR])) {
             $index = $tokens->getNextMeaningfulToken($index);
-        } while ($tokens[$index]->isGivenKind([T_STRING, T_NS_SEPARATOR]));
+            $namespaceIsNamed = true;
+        }
+
+        if (!$namespaceIsNamed) {
+            return;
+        }
 
         if (!$tokens[$index]->equals('{')) {
             return; // `;`

+ 21 - 0
tests/Fixer/ControlStructure/NoUnneededBracesFixerTest.php

@@ -182,6 +182,27 @@ namespace Foo {
             } ?>",
             ['namespaces' => true],
         ];
+
+        yield [
+            '<?php
+            namespace A;
+                class X {}
+            ',
+            '<?php
+            namespace A {
+                class X {}
+            }',
+            ['namespaces' => true],
+        ];
+
+        yield [
+            '<?php
+            namespace {
+                class X {}
+            }',
+            null,
+            ['namespaces' => true],
+        ];
     }
 
     /**