Skip to content

Commit 4cd09a1

Browse files
committed
UselessVariableSniff: Fixed false positive
1 parent 8a2d1c8 commit 4cd09a1

File tree

2 files changed

+31
-7
lines changed

2 files changed

+31
-7
lines changed

SlevomatCodingStandard/Sniffs/Variables/UselessVariableSniff.php

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -123,14 +123,29 @@ public function process(File $phpcsFile, $returnPointer): void
123123
self::CODE_USELESS_VARIABLE,
124124
];
125125

126+
$searchBefore = $previousVariablePointer;
127+
do {
128+
$previousOpenParenthesisPointer = TokenHelper::findPrevious($phpcsFile, T_OPEN_PARENTHESIS, $searchBefore - 1);
129+
130+
if (
131+
$previousOpenParenthesisPointer === null
132+
|| $tokens[$previousOpenParenthesisPointer]['parenthesis_closer'] < $previousVariablePointer
133+
) {
134+
break;
135+
}
136+
137+
if (
138+
array_key_exists('parenthesis_owner', $tokens[$previousOpenParenthesisPointer])
139+
&& in_array($tokens[$tokens[$previousOpenParenthesisPointer]['parenthesis_owner']]['code'], [T_IF, T_ELSEIF, T_WHILE], true)
140+
) {
141+
return;
142+
}
143+
144+
$searchBefore = $previousOpenParenthesisPointer;
145+
146+
} while (true);
147+
126148
$pointerBeforePreviousVariable = TokenHelper::findPreviousEffective($phpcsFile, $previousVariablePointer - 1);
127-
if (
128-
$tokens[$pointerBeforePreviousVariable]['code'] === T_OPEN_PARENTHESIS
129-
&& array_key_exists('parenthesis_owner', $tokens[$pointerBeforePreviousVariable])
130-
&& in_array($tokens[$tokens[$pointerBeforePreviousVariable]['parenthesis_owner']]['code'], [T_IF, T_ELSEIF, T_WHILE], true)
131-
) {
132-
return;
133-
}
134149

135150
if (
136151
!in_array($tokens[$pointerBeforePreviousVariable]['code'], [T_SEMICOLON, T_OPEN_CURLY_BRACKET, T_CLOSE_CURLY_BRACKET], true)

tests/Sniffs/Variables/data/uselessVariableNoErrors.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,15 @@ function assigmentInCondition() {
152152

153153
}
154154

155+
function assigmentInConditionAgain($file) {
156+
if (file_exists($path = realpath($file))) {
157+
doAnything();
158+
return $path;
159+
}
160+
161+
return null;
162+
}
163+
155164
class Foo
156165
{
157166

0 commit comments

Comments
 (0)