Skip to content

Commit

Permalink
UnusedUseStatement sniff - better recognise classes in doc-block anno…
Browse files Browse the repository at this point in the history
…tations
  • Loading branch information
michalbundyra committed May 11, 2019
1 parent 740631f commit aa8d6af
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@ public function process(File $phpcsFile, $stackPtr)
while ($classUsed !== false) {
$isStringToken = $tokens[$classUsed]['code'] === T_STRING;

$match = null;

if (($isStringToken && strtolower($tokens[$classUsed]['content']) === $lowerClassName)
|| ($tokens[$classUsed]['code'] === T_DOC_COMMENT_STRING
&& preg_match(
Expand All @@ -136,6 +138,16 @@ public function process(File $phpcsFile, $stackPtr)
'/@' . preg_quote($lowerClassName, '/') . '(\(|\\\\|$)/i',
$tokens[$classUsed]['content']
))
|| (! $isStringToken
&& ! preg_match(
'/"[^"]*' . preg_quote($lowerClassName, '/') . '\b[^"]*"/i',
$tokens[$classUsed]['content']
)
&& preg_match(
'/(?<!")@' . preg_quote($lowerClassName, '/') . '\b/i',
$tokens[$classUsed]['content'],
$match
))
) {
$beforeUsage = $phpcsFile->findPrevious(
$isStringToken ? Tokens::$emptyTokens : $emptyTokens,
Expand Down Expand Up @@ -167,6 +179,10 @@ public function process(File $phpcsFile, $stackPtr)
) {
return;
}

if ($match) {
return;
}
} else {
return;
}
Expand Down
13 changes: 13 additions & 0 deletions test/Sniffs/Namespaces/UnusedUseStatementUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ use BarBaz\Unused14;
use Unused15;
use Used19;
use Used20;
use Used21;
use Used22;
use FooBar;
use FooB;
use Unused16;
use Unused17;

/**
* @Used10
Expand Down Expand Up @@ -123,4 +129,11 @@ class Foo
new /** hey */ Used18 \ World();
MyClass::Unused14;
}

/**
* @Used21(param=@Used22, value=@Used23, key=@FooBar, foo="@Unused16", bar="something @Unused17 bar")
*/
protected function testAnnotations()
{
}
}
10 changes: 10 additions & 0 deletions test/Sniffs/Namespaces/UnusedUseStatementUnitTest.inc.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ use FooBar\Used17;
use FooBar\Used18;
use Used19;
use Used20;
use Used21;
use Used22;
use FooBar;

/**
* @Used10
Expand Down Expand Up @@ -109,4 +112,11 @@ class Foo
new /** hey */ Used18 \ World();
MyClass::Unused14;
}

/**
* @Used21(param=@Used22, value=@Used23, key=@FooBar, foo="@Unused16", bar="something @Unused17 bar")
*/
protected function testAnnotations()
{
}
}
3 changes: 3 additions & 0 deletions test/Sniffs/Namespaces/UnusedUseStatementUnitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ protected function getErrorList(string $testFile = '') : array
37 => 1,
38 => 1,
39 => 1,
45 => 1,
46 => 1,
47 => 1,
];
}

Expand Down

0 comments on commit aa8d6af

Please sign in to comment.