Skip to content
Snippets Groups Projects
Commit 1c8b5a4f authored by Alex Pott's avatar Alex Pott Committed by Klaus Purer
Browse files

Issue #2685877 by alexpott, klausi: UnusedUseStatement sniff should report...

Issue #2685877 by alexpott, klausi: UnusedUseStatement sniff should report classes in the same namespace
parent b86411ee
Branches
Tags
No related merge requests found
......@@ -73,6 +73,39 @@ class Drupal_Sniffs_Classes_UnusedUseStatementSniff implements PHP_CodeSniffer_S
$classUsed = $phpcsFile->findNext(T_STRING, ($classPtr + 1));
$lowerClassName = strtolower($tokens[$classPtr]['content']);
// Check if the referenced class is in the same namespace as the current
// file. If it is then the use statement is not necessary.
$namespacePtr = $phpcsFile->findPrevious([T_NAMESPACE], $stackPtr);
if ($namespacePtr !== false) {
$nsEnd = $phpcsFile->findNext(
[
T_NS_SEPARATOR,
T_STRING,
T_WHITESPACE,
],
($namespacePtr + 1),
null,
true
);
$namespace = trim($phpcsFile->getTokensAsString(($namespacePtr + 1), ($nsEnd - $namespacePtr - 1)));
$useNamespacePtr = $phpcsFile->findNext([T_STRING], ($stackPtr + 1));
$useNamespaceEnd = $phpcsFile->findNext(
[
T_NS_SEPARATOR,
T_STRING,
],
($useNamespacePtr + 1),
null,
true
);
$use_namespace = rtrim($phpcsFile->getTokensAsString($useNamespacePtr, ($useNamespaceEnd - $useNamespacePtr - 1)), '\\');
if (strcasecmp($namespace, $use_namespace) === 0) {
$classUsed = false;
}
}//end if
while ($classUsed !== false) {
if (strtolower($tokens[$classUsed]['content']) === $lowerClassName) {
$beforeUsage = $phpcsFile->findPrevious(
......
<?php
namespace MyNamespace\Depth;
use Foo\Bar;
use Bar\Fail;
use Test\Bar\Thing;
......@@ -11,6 +13,8 @@ use Thing\SomeName as OtherName;
use Thing\DifferentName as UsedOtherName;
use Another\UnusedUse;
use Example\MyUrlHelper;
use MyNamespace\Depth\UnusedSameNamespace;
use /* I like weird comment placements */ MyNamespace\Depth\AnotherUnusedSameNamespace /* Oh yes I do */;
/**
* Bla.
......@@ -40,4 +44,11 @@ class Pum {
}
/**
* Don't need to use classes in the same namespace.
*/
protected function test4(UnusedSameNamespace $x, AnotherUnusedSameNamespace $y) {
}
}
<?php
/**
* @file
*/
namespace MyNamespace\Depth;
use Thing\Fail\ActuallyUsed;
use Test\TraitTest;
......@@ -37,4 +35,11 @@ class Pum {
}
/**
* Don't need to use classes in the same namespace.
*/
protected function test4(UnusedSameNamespace $x, AnotherUnusedSameNamespace $y) {
}
}
......@@ -30,13 +30,15 @@ class Drupal_Sniffs_Classes_UnusedUseStatementUnitTest extends CoderSniffUnitTes
public function getWarningList($testFile)
{
return array(
3 => 1,
4 => 1,
5 => 1,
8 => 1,
9 => 1,
6 => 1,
7 => 1,
10 => 1,
11 => 1,
12 => 1,
14 => 1,
16 => 1,
17 => 1,
);
}//end getWarningList()
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment