Skip to content

Commit d20d29c

Browse files
committed
UselessVariableSniff: Fixed false positives
1 parent a108576 commit d20d29c

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

SlevomatCodingStandard/Sniffs/Variables/UselessVariableSniff.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use const T_CLOSE_CURLY_BRACKET;
1010
use const T_CONCAT_EQUAL;
1111
use const T_DIV_EQUAL;
12+
use const T_DOC_COMMENT_CLOSE_TAG;
1213
use const T_EQUAL;
1314
use const T_MINUS_EQUAL;
1415
use const T_MOD_EQUAL;
@@ -20,12 +21,16 @@
2021
use const T_SEMICOLON;
2122
use const T_SL_EQUAL;
2223
use const T_SR_EQUAL;
24+
use const T_STATIC;
2325
use const T_VARIABLE;
26+
use const T_WHITESPACE;
2427
use const T_XOR_EQUAL;
2528
use function array_key_exists;
2629
use function array_reverse;
2730
use function count;
2831
use function in_array;
32+
use function preg_match;
33+
use function preg_quote;
2934
use function sprintf;
3035

3136
class UselessVariableSniff implements Sniff
@@ -94,6 +99,21 @@ public function process(File $phpcsFile, $returnPointer): void
9499
return;
95100
}
96101

102+
$effectivePointerBeforePreviousVariable = TokenHelper::findPreviousEffective($phpcsFile, $previousVariablePointer - 1);
103+
if ($tokens[$effectivePointerBeforePreviousVariable]['code'] === T_STATIC) {
104+
return;
105+
}
106+
107+
$pointerBeforePreviousVariable = TokenHelper::findPreviousExcluding($phpcsFile, T_WHITESPACE, $previousVariablePointer - 1);
108+
if (
109+
$tokens[$pointerBeforePreviousVariable]['code'] === T_DOC_COMMENT_CLOSE_TAG
110+
) {
111+
$docCommentContent = TokenHelper::getContent($phpcsFile, $tokens[$pointerBeforePreviousVariable]['comment_opener'], $pointerBeforePreviousVariable);
112+
if (preg_match('~@var\\s+\\S+\\s+' . preg_quote($variableName, '~') . '~', $docCommentContent)) {
113+
return;
114+
}
115+
}
116+
97117
/** @var int $assigmentPointer */
98118
$assigmentPointer = TokenHelper::findNextEffective($phpcsFile, $previousVariablePointer + 1);
99119
if (!in_array($tokens[$assigmentPointer]['code'], [

tests/Sniffs/Variables/data/uselessVariableNoErrors.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,14 @@ function differentVariable() {
3636
$e = 10;
3737
return $f;
3838
}
39+
40+
function staticVariable() {
41+
static $g = null;
42+
return $g;
43+
}
44+
45+
function withDocComment() {
46+
/** @var string $h */
47+
$h = 'h';
48+
return $h;
49+
}

0 commit comments

Comments
 (0)