Skip to content

Commit 0d4fdd9

Browse files
Majkl578kukulich
authored andcommitted
ReferenceUsedNamesOnlySniff: Add option to allow fully-qualified global classes
1 parent 9cd089e commit 0d4fdd9

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

SlevomatCodingStandard/Sniffs/Namespaces/ReferenceUsedNamesOnlySniff.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ class ReferenceUsedNamesOnlySniff implements \PHP_CodeSniffer_Sniff
2929
/** @var bool */
3030
public $allowFullyQualifiedExceptions = false;
3131

32+
/** @var bool */
33+
public $allowFullyQualifiedGlobalClasses = false;
34+
3235
/** @var string[] */
3336
public $specialExceptionNames = [];
3437

@@ -185,7 +188,7 @@ function (ReferencedName $referencedName): string {
185188
$phpcsFile->fixer->replaceToken($nameStartPointer, substr($tokens[$nameStartPointer]['content'], 1));
186189
$phpcsFile->fixer->endChangeset();
187190
}
188-
} else {
191+
} elseif (!$this->allowFullyQualifiedGlobalClasses || NamespaceHelper::hasNamespace($name)) {
189192
$fix = $phpcsFile->addFixableError(sprintf(
190193
'Type %s should not be referenced via a fully qualified name, but via a use statement.',
191194
$name

tests/Sniffs/Namespaces/ReferenceUsedNamesOnlySniffTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -541,6 +541,17 @@ public function testThrowExceptionForUndefinedKeyword()
541541
$this->assertContains('Value for keyword token not found, constant "T_FOO" is not defined', $report->getErrors()[1][1][0]['message']);
542542
}
543543

544+
public function testAllowingFullyQualifiedGlobalTypes()
545+
{
546+
$report = $this->checkFile(
547+
__DIR__ . '/data/fullyQualifiedGlobalClassesInNamespace.php',
548+
[
549+
'allowFullyQualifiedGlobalClasses' => true,
550+
]
551+
);
552+
$this->assertNoSniffErrorInFile($report);
553+
}
554+
544555

545556
public function testFixableReferenceViaFullyQualifiedName()
546557
{
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
3+
namespace Foo;
4+
5+
class Bar implements \Iterator
6+
{
7+
8+
public function baz(\DateTimeInterface $date)
9+
{
10+
11+
}
12+
13+
}
14+
15+
new \DateTimeImmutable();
16+
17+
echo \DateTime::ISO8601;

0 commit comments

Comments
 (0)