Skip to content

Commit 2654744

Browse files
committed
UselessVariableSniff: Fixed false positive
1 parent de61dd2 commit 2654744

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

SlevomatCodingStandard/Sniffs/Variables/UselessVariableSniff.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,14 @@
1010
use const T_CONCAT_EQUAL;
1111
use const T_DIV_EQUAL;
1212
use const T_DOC_COMMENT_CLOSE_TAG;
13+
use const T_ELSEIF;
1314
use const T_EQUAL;
15+
use const T_IF;
1416
use const T_MINUS_EQUAL;
1517
use const T_MOD_EQUAL;
1618
use const T_MUL_EQUAL;
1719
use const T_OPEN_CURLY_BRACKET;
20+
use const T_OPEN_PARENTHESIS;
1821
use const T_OR_EQUAL;
1922
use const T_PLUS_EQUAL;
2023
use const T_POW_EQUAL;
@@ -24,8 +27,10 @@
2427
use const T_SR_EQUAL;
2528
use const T_STATIC;
2629
use const T_VARIABLE;
30+
use const T_WHILE;
2731
use const T_WHITESPACE;
2832
use const T_XOR_EQUAL;
33+
use function array_key_exists;
2934
use function count;
3035
use function in_array;
3136
use function preg_match;
@@ -101,6 +106,14 @@ public function process(File $phpcsFile, $returnPointer): void
101106
];
102107

103108
$pointerBeforePreviousVariable = TokenHelper::findPreviousEffective($phpcsFile, $previousVariablePointer - 1);
109+
if (
110+
$tokens[$pointerBeforePreviousVariable]['code'] === T_OPEN_PARENTHESIS
111+
&& array_key_exists('parenthesis_owner', $tokens[$pointerBeforePreviousVariable])
112+
&& in_array($tokens[$tokens[$pointerBeforePreviousVariable]['parenthesis_owner']]['code'], [T_IF, T_ELSEIF, T_WHILE], true)
113+
) {
114+
return;
115+
}
116+
104117
if (!in_array($tokens[$pointerBeforePreviousVariable]['code'], [T_SEMICOLON, T_OPEN_CURLY_BRACKET], true)) {
105118
$phpcsFile->addError(...$errorParameters);
106119
return;

tests/Sniffs/Variables/data/uselessVariableNoErrors.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,3 +67,11 @@ function differentScope() {
6767
return $k;
6868
}
6969
}
70+
71+
function assigmentInCondition() {
72+
if ($l = 'l') {
73+
$this->doSomething();
74+
return $l;
75+
}
76+
77+
}

0 commit comments

Comments
 (0)