Skip to content

Commit 4879172

Browse files
committed
UnusedVariableSniff: Fixed false positives
1 parent 2654744 commit 4879172

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

SlevomatCodingStandard/Sniffs/Variables/UnusedVariableSniff.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
use const T_MOD_EQUAL;
3131
use const T_MUL_EQUAL;
3232
use const T_OBJECT_OPERATOR;
33+
use const T_OPEN_SHORT_ARRAY;
3334
use const T_OPEN_TAG;
3435
use const T_OR_EQUAL;
3536
use const T_PLUS_EQUAL;
@@ -95,6 +96,10 @@ public function process(File $phpcsFile, $variablePointer): void
9596
return;
9697
}
9798

99+
if ($this->isUsedAsKeyOrValueInArray($phpcsFile, $variablePointer)) {
100+
return;
101+
}
102+
98103
$scopeOwnerPointer = TokenHelper::findPrevious($phpcsFile, T_OPEN_TAG, $variablePointer - 1);
99104
foreach (array_reverse($tokens[$variablePointer]['conditions'], true) as $conditionPointer => $conditionTokenCode) {
100105
if (in_array($conditionTokenCode, TokenHelper::$functionTokenCodes, true)) {
@@ -316,6 +321,29 @@ private function isUsedInLoop(File $phpcsFile, int $variablePointer, string $var
316321
return false;
317322
}
318323

324+
private function isUsedAsKeyOrValueInArray(File $phpcsFile, int $variablePointer): bool
325+
{
326+
$tokens = $phpcsFile->getTokens();
327+
328+
$arrayOpenerPointer = TokenHelper::findPrevious($phpcsFile, T_OPEN_SHORT_ARRAY, $variablePointer - 1);
329+
if ($arrayOpenerPointer === null) {
330+
return false;
331+
}
332+
333+
$arrayCloserPointer = $tokens[$arrayOpenerPointer]['bracket_closer'];
334+
if ($arrayCloserPointer < $variablePointer) {
335+
return false;
336+
}
337+
338+
$pointerAfterArrayCloser = TokenHelper::findNextEffective($phpcsFile, $arrayCloserPointer + 1);
339+
if ($tokens[$pointerAfterArrayCloser]['code'] === T_EQUAL) {
340+
return false;
341+
}
342+
343+
$pointerBeforeVariable = TokenHelper::findPreviousEffective($phpcsFile, $variablePointer - 1);
344+
return in_array($tokens[$pointerBeforeVariable]['code'], [T_OPEN_SHORT_ARRAY, T_COMMA, T_DOUBLE_ARROW], true);
345+
}
346+
319347
private function isStaticVariable(File $phpcsFile, int $functionPointer, string $variableName): bool
320348
{
321349
$tokens = $phpcsFile->getTokens();

tests/Sniffs/Variables/data/unusedVariableNoErrors.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,3 +142,12 @@ function () {
142142
$a = 10;
143143
max(1, $a += 10);
144144
};
145+
146+
function () {
147+
$a = 1;
148+
$b = 1;
149+
$c = [
150+
$b-- => $a++
151+
];
152+
return $c;
153+
};

0 commit comments

Comments
 (0)