Skip to content

Commit

Permalink
Bug fix: false negative unused var
Browse files Browse the repository at this point in the history
As reported in 111, if a variable is assigned a value with a combined assignment operator, it would not be reported as unused.

Includes unit tests.

Fixes 111
  • Loading branch information
jrfnl committed Jan 19, 2020
1 parent 891b3e1 commit 65479d5
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
7 changes: 6 additions & 1 deletion VariableAnalysis/Lib/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace VariableAnalysis\Lib;

use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Util\Tokens;

class Helpers {
/**
Expand Down Expand Up @@ -256,7 +257,11 @@ public static function getNextAssignPointer(File $phpcsFile, $stackPtr) {

// Is the next non-whitespace an assignment?
$nextPtr = $phpcsFile->findNext(T_WHITESPACE, $stackPtr + 1, null, true, null, true);
if (is_int($nextPtr) && $tokens[$nextPtr]['code'] === T_EQUAL) {
if (is_int($nextPtr)
&& isset(Tokens::$assignmentTokens[$tokens[$nextPtr]['code']])
// Ignore double arrow to prevent triggering on `foreach ( $array as $k => $v )`.
&& $tokens[$nextPtr]['code'] !== T_DOUBLE_ARROW
) {
return $nextPtr;
}
return null;
Expand Down
13 changes: 13 additions & 0 deletions VariableAnalysis/Tests/CodeAnalysis/VariableAnalysisTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -907,4 +907,17 @@ public function testGetDefinedVarsCountsAsRead() {
];
$this->assertEquals($expectedWarnings, $lines);
}

public function testUnusedVarWithValueChange() {
$fixtureFile = $this->getFixture('UnusedVarWithValueChangeFixture.php');
$phpcsFile = $this->prepareLocalFileForSniffs($fixtureFile);
$phpcsFile->process();
$lines = $this->getWarningLineNumbersFromFile($phpcsFile);
$expectedWarnings = [
5,
8,
11,
];
$this->assertEquals($expectedWarnings, $lines);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

// Issue #111.
function foo() {
$var = 'abc';
$var = 'def';

$var2 = 'def';
$var2 .= 'ghi';

$var3 = 10;
$var3 += 20;
}

// Safeguard that this change doesn't influence (not) reporting on assignments to parameters passed by reference.
function bar(&$param) {
$param .= 'foo';
}

0 comments on commit 65479d5

Please sign in to comment.