Skip to content

Commit 9801fc0

Browse files
committed
SlevomatCodingStandard.Namespaces.ReferenceUsedNamesOnly: New option "allowWhenNoNamespace"
1 parent c8ceb17 commit 9801fc0

File tree

4 files changed

+21
-2
lines changed

4 files changed

+21
-2
lines changed

SlevomatCodingStandard/Sniffs/Namespaces/ReferenceUsedNamesOnlySniff.php

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,9 @@ class ReferenceUsedNamesOnlySniff implements Sniff
8686
/** @var bool */
8787
public $allowFallbackGlobalConstants = true;
8888

89+
/** @var bool */
90+
public $allowWhenNoNamespace = true;
91+
8992
/** @var list<string> */
9093
public $specialExceptionNames = [];
9194

@@ -140,6 +143,12 @@ public function process(File $phpcsFile, $openTagPointer): void
140143
return;
141144
}
142145

146+
$namespacePointers = NamespaceHelper::getAllNamespacesPointers($phpcsFile);
147+
148+
if ($namespacePointers === [] && !$this->allowWhenNoNamespace) {
149+
return;
150+
}
151+
143152
$tokens = $phpcsFile->getTokens();
144153

145154
$references = $this->getReferences($phpcsFile, $openTagPointer);
@@ -171,8 +180,6 @@ public function process(File $phpcsFile, $openTagPointer): void
171180
);
172181
}
173182

174-
$namespacePointers = NamespaceHelper::getAllNamespacesPointers($phpcsFile);
175-
176183
$referenceErrors = [];
177184

178185
foreach ($references as $reference) {

doc/namespaces.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ Sniff provides the following settings:
129129
* `allowFallbackGlobalFunctions`: allows using global functions via fallback name without `use` (i.e. `phpversion()`).
130130
* `allowFallbackGlobalConstants`: allows using global constants via fallback name without `use` (i.e. `PHP_VERSION`).
131131
* `allowPartialUses`: allows using and referencing whole namespaces.
132+
* `allowWhenNoNamespace` (default: `true`): force even when there's no namespace in the file.
132133

133134
#### SlevomatCodingStandard.Namespaces.UseDoesNotStartWithBackslash 🔧
134135

tests/Sniffs/Namespaces/ReferenceUsedNamesOnlySniffTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1251,4 +1251,12 @@ public function testReservedWord(): void
12511251
self::assertNoSniffErrorInFile($report);
12521252
}
12531253

1254+
public function testDisabledWhenNoNamespace(): void
1255+
{
1256+
$report = self::checkFile(__DIR__ . '/data/referenceUsedNamesOnlyDisabledWhenNoNamespace.php', [
1257+
'allowWhenNoNamespace' => false,
1258+
]);
1259+
self::assertNoSniffErrorInFile($report);
1260+
}
1261+
12541262
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
<?php
2+
3+
$latte = new Latte\Engine;

0 commit comments

Comments
 (0)