Skip to content

Commit

Permalink
Fixes detecting usage of $this variable
Browse files Browse the repository at this point in the history
Recursion for anonymous classes as $this can be used in the constructor
parameter. Fixes failing tests.
  • Loading branch information
michalbundyra committed Jan 6, 2020
1 parent 6c9b326 commit 10b6b2a
Showing 1 changed file with 26 additions and 3 deletions.
29 changes: 26 additions & 3 deletions src/Standards/Squiz/Sniffs/Scope/StaticThisUsageSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,22 +68,45 @@ public function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope)
$next = $stackPtr;
$end = $tokens[$stackPtr]['scope_closer'];

$this->checkThisUsage($phpcsFile, $next, $end);

}//end processTokenWithinScope()


/**
* Check for $this variable usage between $next and $end tokens.
*
* @param File $phpcsFile The current file being scanned.
* @param int $next The position of the next token to check.
* @param int $end The position of the last token to check.
*
* @return void
*/
private function checkThisUsage(File $phpcsFile, $next, $end)
{
$tokens = $phpcsFile->getTokens();

do {
$next = $phpcsFile->findNext([T_VARIABLE, T_ANON_CLASS], ($next + 1), $end);
if ($next === false) {
continue;
} else if ($tokens[$next]['code'] === T_ANON_CLASS) {
}

if ($tokens[$next]['code'] === T_ANON_CLASS) {
$this->checkThisUsage($phpcsFile, $next, $tokens[$next]['scope_opener']);
$next = $tokens[$next]['scope_closer'];
continue;
} else if ($tokens[$next]['content'] !== '$this') {
}

if ($tokens[$next]['content'] !== '$this') {
continue;
}

$error = 'Usage of "$this" in static methods will cause runtime errors';
$phpcsFile->addError($error, $next, 'Found');
} while ($next !== false);

}//end processTokenWithinScope()
}//end checkThisUsage()


/**
Expand Down

0 comments on commit 10b6b2a

Please sign in to comment.