Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added property validUndefinedVariableRegexp to VariableAnalysisSniff #173

Merged
merged 2 commits into from
Jun 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Tests/VariableAnalysisSniff/VariableAnalysisTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
12 changes: 12 additions & 0 deletions VariableAnalysis/Sniffs/CodeAnalysis/VariableAnalysisSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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];
}
Expand Down