diff --git a/Tests/VariableAnalysisSniff/VariableAnalysisTest.php b/Tests/VariableAnalysisSniff/VariableAnalysisTest.php index e9cf2b11..c259a528 100644 --- a/Tests/VariableAnalysisSniff/VariableAnalysisTest.php +++ b/Tests/VariableAnalysisSniff/VariableAnalysisTest.php @@ -793,6 +793,25 @@ public function testValidUndefinedVariableNamesIgnoresUndefinedProperties() { $this->assertEquals($expectedWarnings, $lines); } + public function testValidUndefinedVariableRegexpIgnoresUndefinedProperties() { + $fixtureFile = $this->getFixture('ClassReferenceFixture.php'); + $phpcsFile = $this->prepareLocalFileForSniffs($fixtureFile); + $phpcsFile->ruleset->setSniffProperty( + 'VariableAnalysis\Sniffs\CodeAnalysis\VariableAnalysisSniff', + 'validUndefinedVariableRegexp', + '/^undefined_/' + ); + $phpcsFile->process(); + $lines = $this->getWarningLineNumbersFromFile($phpcsFile); + $expectedWarnings = [ + 12, + 13, + 24, + 25 + ]; + $this->assertEquals($expectedWarnings, $lines); + } + public function testUnusedArgumentsBeforeUsedArgumentsAreFoundIfFalse() { $fixtureFile = $this->getFixture('UnusedAfterUsedFixture.php'); $phpcsFile = $this->prepareLocalFileForSniffs($fixtureFile); diff --git a/VariableAnalysis/Sniffs/CodeAnalysis/VariableAnalysisSniff.php b/VariableAnalysis/Sniffs/CodeAnalysis/VariableAnalysisSniff.php index 265a72a4..90ad91db 100644 --- a/VariableAnalysis/Sniffs/CodeAnalysis/VariableAnalysisSniff.php +++ b/VariableAnalysis/Sniffs/CodeAnalysis/VariableAnalysisSniff.php @@ -90,6 +90,15 @@ class VariableAnalysisSniff implements Sniff { */ public $validUndefinedVariableNames = null; + /** + * A PHP regexp string for variables that you want to ignore from undefined + * variable warnings. For example, to ignore the variables `$_junk` and + * `$_unused`, this could be set to `'/^_/'`. + * + * @var string|null + */ + public $validUndefinedVariableRegexp = null; + /** * Allows unused arguments in a function definition if they are * followed by an argument which is used. @@ -264,6 +273,9 @@ protected function getOrCreateVariableInfo($varName, $currScope) { if (in_array($varName, $validUndefinedVariableNames)) { $scopeInfo->variables[$varName]->ignoreUndefined = true; } + if (isset($this->validUndefinedVariableRegexp) && preg_match($this->validUndefinedVariableRegexp, $varName) === 1) { + $scopeInfo->variables[$varName]->ignoreUndefined = true; + } } return $scopeInfo->variables[$varName]; }