Skip to content

Commit 0b230c3

Browse files
jrfnlsirbrillig
andcommitted
Bug fix: recognize use of self/static within anonymous class (#110)
The use of `self::$property`/`static::$property` in non-nested anonymous classes was incorrectly flagged as `SelfOutsideClass`/`StaticOutsideClass` (false positive). For use within anonymous classes nested within another class, the only reason these weren't flagged was the fact that they were nested. Fixed now. Includes unit tests. Co-authored-by: Payton Swick <payton@foolord.com>
1 parent 5081118 commit 0b230c3

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

VariableAnalysis/Lib/Helpers.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ public static function areAnyConditionsAClosure(File $phpcsFile, array $conditio
101101
*/
102102
public static function areAnyConditionsAClass(array $conditions) {
103103
foreach (array_reverse($conditions, true) as $scopePtr => $scopeCode) {
104-
if ($scopeCode === T_CLASS || $scopeCode === T_TRAIT) {
104+
if ($scopeCode === T_CLASS || $scopeCode === T_ANON_CLASS || $scopeCode === T_TRAIT) {
105105
return true;
106106
}
107107
}

VariableAnalysis/Tests/CodeAnalysis/VariableAnalysisTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,7 @@ public function testAnonymousClassAllowPropertyDefinitions() {
580580
$lines = $this->getWarningLineNumbersFromFile($phpcsFile);
581581
$expectedWarnings = [
582582
17,
583+
38,
583584
];
584585
$this->assertEquals($expectedWarnings, $lines);
585586
$lines = $this->getErrorLineNumbersFromFile($phpcsFile);

VariableAnalysis/Tests/CodeAnalysis/fixtures/AnonymousClassWithPropertiesFixture.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,29 @@ public function sayHelloWorld() {
1515

1616
public function methodWithStaticVar() {
1717
static $myStaticVar; // should trigger unused warning
18+
19+
echo self::$storedHello;
20+
echo static::$storedHello;
1821
}
1922
};
2023
}
2124
}
25+
26+
$anonClass = new class() {
27+
protected $storedHello;
28+
private static $storedHello2;
29+
private $storedHello3;
30+
public $helloOptions = [];
31+
static $aStaticOne;
32+
var $aVarOne;
33+
public function sayHelloWorld() {
34+
echo "hello world";
35+
}
36+
37+
public function methodWithStaticVar() {
38+
static $myStaticVar; // should trigger unused warning
39+
40+
echo self::$storedHello;
41+
echo static::$storedHello;
42+
}
43+
};

0 commit comments

Comments
 (0)