diff --git a/VariableAnalysis/Sniffs/CodeAnalysis/VariableAnalysisSniff.php b/VariableAnalysis/Sniffs/CodeAnalysis/VariableAnalysisSniff.php index 9be9f2fc..7a4b5250 100644 --- a/VariableAnalysis/Sniffs/CodeAnalysis/VariableAnalysisSniff.php +++ b/VariableAnalysis/Sniffs/CodeAnalysis/VariableAnalysisSniff.php @@ -608,6 +608,10 @@ protected function checkForStaticDeclaration(File $phpcsFile, $stackPtr, $varNam return true; } + protected function checkForNumericVariable($varName) { + return is_numeric(substr($varName, 0, 1)); + } + protected function checkForForeachLoopVar(File $phpcsFile, $stackPtr, $varName, $currScope) { $tokens = $phpcsFile->getTokens(); $token = $tokens[$stackPtr]; @@ -827,6 +831,11 @@ protected function processVariable(File $phpcsFile, $stackPtr) { return; } + // Are we a numeric variable used for constructs like preg_replace? + if ($this->checkForNumericVariable($varName)) { + return; + } + // OK, we don't appear to be a write to the var, assume we're a read. $this->markVariableReadAndWarnIfUndefined($phpcsFile, $varName, $stackPtr, $currScope); } @@ -855,9 +864,16 @@ protected function processVariableInString(File $phpcsFile, $stackPtr) { if ($this->checkForThisWithinClass($phpcsFile, $stackPtr, $varName, $currScope)) { continue; } + if ($this->checkForSuperGlobal($phpcsFile, $stackPtr, $varName, $currScope)) { continue; } + + // Are we a numeric variable used for constructs like preg_replace? + if ($this->checkForNumericVariable($varName)) { + continue; + } + $this->markVariableReadAndWarnIfUndefined($phpcsFile, $varName, $stackPtr, $currScope); } } diff --git a/VariableAnalysis/Tests/CodeAnalysis/VariableAnalysisTest.php b/VariableAnalysis/Tests/CodeAnalysis/VariableAnalysisTest.php index f570496f..8bc0c217 100644 --- a/VariableAnalysis/Tests/CodeAnalysis/VariableAnalysisTest.php +++ b/VariableAnalysis/Tests/CodeAnalysis/VariableAnalysisTest.php @@ -688,4 +688,16 @@ public function testUnusedArgumentsBeforeUsedArgumentsAreIgnoredByDefault() { ]; $this->assertEquals($expectedWarnings, $lines); } + + public function testPregReplaceIgnoresNumericVariables() { + $fixtureFile = $this->getFixture('PregReplaceFixture.php'); + $phpcsFile = $this->prepareLocalFileForSniffs($this->getSniffFiles(), $fixtureFile); + $phpcsFile->process(); + $lines = $this->getWarningLineNumbersFromFile($phpcsFile); + $expectedWarnings = [ + 15, + 20, + ]; + $this->assertEquals($expectedWarnings, $lines); + } } diff --git a/VariableAnalysis/Tests/CodeAnalysis/fixtures/PregReplaceFixture.php b/VariableAnalysis/Tests/CodeAnalysis/fixtures/PregReplaceFixture.php new file mode 100644 index 00000000..3d5717ea --- /dev/null +++ b/VariableAnalysis/Tests/CodeAnalysis/fixtures/PregReplaceFixture.php @@ -0,0 +1,21 @@ +