Skip to content

Commit 10b6b2a

Browse files
committed
Fixes detecting usage of $this variable
Recursion for anonymous classes as $this can be used in the constructor parameter. Fixes failing tests.
1 parent 6c9b326 commit 10b6b2a

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

src/Standards/Squiz/Sniffs/Scope/StaticThisUsageSniff.php

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,22 +68,45 @@ public function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope)
6868
$next = $stackPtr;
6969
$end = $tokens[$stackPtr]['scope_closer'];
7070

71+
$this->checkThisUsage($phpcsFile, $next, $end);
72+
73+
}//end processTokenWithinScope()
74+
75+
76+
/**
77+
* Check for $this variable usage between $next and $end tokens.
78+
*
79+
* @param File $phpcsFile The current file being scanned.
80+
* @param int $next The position of the next token to check.
81+
* @param int $end The position of the last token to check.
82+
*
83+
* @return void
84+
*/
85+
private function checkThisUsage(File $phpcsFile, $next, $end)
86+
{
87+
$tokens = $phpcsFile->getTokens();
88+
7189
do {
7290
$next = $phpcsFile->findNext([T_VARIABLE, T_ANON_CLASS], ($next + 1), $end);
7391
if ($next === false) {
7492
continue;
75-
} else if ($tokens[$next]['code'] === T_ANON_CLASS) {
93+
}
94+
95+
if ($tokens[$next]['code'] === T_ANON_CLASS) {
96+
$this->checkThisUsage($phpcsFile, $next, $tokens[$next]['scope_opener']);
7697
$next = $tokens[$next]['scope_closer'];
7798
continue;
78-
} else if ($tokens[$next]['content'] !== '$this') {
99+
}
100+
101+
if ($tokens[$next]['content'] !== '$this') {
79102
continue;
80103
}
81104

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

86-
}//end processTokenWithinScope()
109+
}//end checkThisUsage()
87110

88111

89112
/**

0 commit comments

Comments
 (0)