Skip to content

Commit 52056c3

Browse files
khromalabsRuben Gomez
andauthored
Added property validUndefinedVariableRegexp to VariableAnalysisSniff (#173)
* Added property validUndefinedVariableRegexp to VariableAnalysisSniff * Tests: Add test for validUndefinedVariableRegexp Co-authored-by: Ruben Gomez <ruben@khromalabs.org>
1 parent 9acf2ca commit 52056c3

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

Tests/VariableAnalysisSniff/VariableAnalysisTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -793,6 +793,25 @@ public function testValidUndefinedVariableNamesIgnoresUndefinedProperties() {
793793
$this->assertEquals($expectedWarnings, $lines);
794794
}
795795

796+
public function testValidUndefinedVariableRegexpIgnoresUndefinedProperties() {
797+
$fixtureFile = $this->getFixture('ClassReferenceFixture.php');
798+
$phpcsFile = $this->prepareLocalFileForSniffs($fixtureFile);
799+
$phpcsFile->ruleset->setSniffProperty(
800+
'VariableAnalysis\Sniffs\CodeAnalysis\VariableAnalysisSniff',
801+
'validUndefinedVariableRegexp',
802+
'/^undefined_/'
803+
);
804+
$phpcsFile->process();
805+
$lines = $this->getWarningLineNumbersFromFile($phpcsFile);
806+
$expectedWarnings = [
807+
12,
808+
13,
809+
24,
810+
25
811+
];
812+
$this->assertEquals($expectedWarnings, $lines);
813+
}
814+
796815
public function testUnusedArgumentsBeforeUsedArgumentsAreFoundIfFalse() {
797816
$fixtureFile = $this->getFixture('UnusedAfterUsedFixture.php');
798817
$phpcsFile = $this->prepareLocalFileForSniffs($fixtureFile);

VariableAnalysis/Sniffs/CodeAnalysis/VariableAnalysisSniff.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,15 @@ class VariableAnalysisSniff implements Sniff {
9090
*/
9191
public $validUndefinedVariableNames = null;
9292

93+
/**
94+
* A PHP regexp string for variables that you want to ignore from undefined
95+
* variable warnings. For example, to ignore the variables `$_junk` and
96+
* `$_unused`, this could be set to `'/^_/'`.
97+
*
98+
* @var string|null
99+
*/
100+
public $validUndefinedVariableRegexp = null;
101+
93102
/**
94103
* Allows unused arguments in a function definition if they are
95104
* followed by an argument which is used.
@@ -264,6 +273,9 @@ protected function getOrCreateVariableInfo($varName, $currScope) {
264273
if (in_array($varName, $validUndefinedVariableNames)) {
265274
$scopeInfo->variables[$varName]->ignoreUndefined = true;
266275
}
276+
if (isset($this->validUndefinedVariableRegexp) && preg_match($this->validUndefinedVariableRegexp, $varName) === 1) {
277+
$scopeInfo->variables[$varName]->ignoreUndefined = true;
278+
}
267279
}
268280
return $scopeInfo->variables[$varName];
269281
}

0 commit comments

Comments
 (0)