Skip to content

Commit

Permalink
UselessVariableSniff: Fixed false positive
Browse files Browse the repository at this point in the history
  • Loading branch information
kukulich committed Aug 25, 2020
1 parent 8a2d1c8 commit 4cd09a1
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
29 changes: 22 additions & 7 deletions SlevomatCodingStandard/Sniffs/Variables/UselessVariableSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,14 +123,29 @@ public function process(File $phpcsFile, $returnPointer): void
self::CODE_USELESS_VARIABLE,
];

$searchBefore = $previousVariablePointer;
do {
$previousOpenParenthesisPointer = TokenHelper::findPrevious($phpcsFile, T_OPEN_PARENTHESIS, $searchBefore - 1);

if (
$previousOpenParenthesisPointer === null
|| $tokens[$previousOpenParenthesisPointer]['parenthesis_closer'] < $previousVariablePointer
) {
break;
}

if (
array_key_exists('parenthesis_owner', $tokens[$previousOpenParenthesisPointer])
&& in_array($tokens[$tokens[$previousOpenParenthesisPointer]['parenthesis_owner']]['code'], [T_IF, T_ELSEIF, T_WHILE], true)
) {
return;
}

$searchBefore = $previousOpenParenthesisPointer;

} while (true);

$pointerBeforePreviousVariable = TokenHelper::findPreviousEffective($phpcsFile, $previousVariablePointer - 1);
if (
$tokens[$pointerBeforePreviousVariable]['code'] === T_OPEN_PARENTHESIS
&& array_key_exists('parenthesis_owner', $tokens[$pointerBeforePreviousVariable])
&& in_array($tokens[$tokens[$pointerBeforePreviousVariable]['parenthesis_owner']]['code'], [T_IF, T_ELSEIF, T_WHILE], true)
) {
return;
}

if (
!in_array($tokens[$pointerBeforePreviousVariable]['code'], [T_SEMICOLON, T_OPEN_CURLY_BRACKET, T_CLOSE_CURLY_BRACKET], true)
Expand Down
9 changes: 9 additions & 0 deletions tests/Sniffs/Variables/data/uselessVariableNoErrors.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,15 @@ function assigmentInCondition() {

}

function assigmentInConditionAgain($file) {
if (file_exists($path = realpath($file))) {
doAnything();
return $path;
}

return null;
}

class Foo
{

Expand Down

0 comments on commit 4cd09a1

Please sign in to comment.