Skip to content

Commit 126dc6e

Browse files
committed
UnusedPrivateElementsSniff: fixed false positive for write-only properties
1 parent accf5e3 commit 126dc6e

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

SlevomatCodingStandard/Sniffs/Classes/UnusedPrivateElementsSniff.php

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,23 @@ public function process(\PHP_CodeSniffer\Files\File $phpcsFile, $classPointer):
127127

128128
$possibleAssignTokenPointer = TokenHelper::findNextEffective($phpcsFile, $propertyNameTokenPointer + 1);
129129
$possibleAssignToken = $tokens[$possibleAssignTokenPointer];
130-
if (in_array($possibleAssignToken['code'], \PHP_CodeSniffer\Util\Tokens::$assignmentTokens, true)) {
130+
if (
131+
in_array($possibleAssignToken['code'], [
132+
T_EQUAL,
133+
T_PLUS_EQUAL,
134+
T_MINUS_EQUAL,
135+
T_MUL_EQUAL,
136+
T_DIV_EQUAL,
137+
T_POW_EQUAL,
138+
T_MOD_EQUAL,
139+
T_AND_EQUAL,
140+
T_OR_EQUAL,
141+
T_XOR_EQUAL,
142+
T_SL_EQUAL,
143+
T_SR_EQUAL,
144+
T_CONCAT_EQUAL,
145+
], true)
146+
) {
131147
$writeOnlyProperties[$propertyName] = $propertyNameTokenPointer;
132148
return;
133149
}

tests/Sniffs/Classes/UnusedPrivateElementsSniffTest.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,8 @@ public function testErrors(): void
9999
UnusedPrivateElementsSniff::CODE_UNUSED_PROPERTY,
100100
'Class ClassWithSomeUnusedProperties contains unused property $unusedStaticProperty2.'
101101
);
102+
103+
$this->assertNoSniffError($resultFile, 123);
102104
}
103105

104106
public function testOnlyPublicElements(): void

tests/Sniffs/Classes/data/classWithSomeUnusedElements.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,4 +120,11 @@ public function methodCalledUsedPrivateMethodWithIncorrectCase()
120120
private static $unusedStaticProperty1;
121121
static private $unusedStaticProperty2;
122122

123+
private $propertyUsedAsArrayKey;
124+
125+
public function propertyUsedAsArrayKey()
126+
{
127+
return [$this->propertyUsedAsArrayKey => true];
128+
}
129+
123130
}

0 commit comments

Comments
 (0)