Skip to content

Commit

Permalink
Simplify detecting class properties to improve detection for anonymou…
Browse files Browse the repository at this point in the history
…s classes (#337)

* Add test for anon class with typehint properties

* Remove search for visibility keywords to find properties

This defaults to only using the condition: if a variable is defined
inside a class and not inside a method within a class, then it's a
property.

* Add readonly properties
  • Loading branch information
sirbrillig authored Nov 30, 2024
1 parent e9dae13 commit 04e3d23
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,28 @@ public function methodWithStaticVar() {
echo static::$storedHello;
}
};

class ClassWithAnonymousClassAndTypeHints
{
readonly int $main_id;
public int $id = 1;
public \My\Data|bool $data;

public function test_1(): object
{
return new class
{
readonly int $main_id;
public int $id = 123456;
public \My\Data|bool $data;
};
}

public function test_2(): object
{
return new class
{
public $id = 123456;
};
}
}
24 changes: 1 addition & 23 deletions VariableAnalysis/Sniffs/CodeAnalysis/VariableAnalysisSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -864,29 +864,7 @@ protected function processVariableAsUseImportDefinition(File $phpcsFile, $stackP
*/
protected function processVariableAsClassProperty(File $phpcsFile, $stackPtr)
{
$propertyDeclarationKeywords = [
T_PUBLIC,
T_PRIVATE,
T_PROTECTED,
T_VAR,
];
$stopAtPtr = $stackPtr - 2;
$visibilityPtr = $phpcsFile->findPrevious($propertyDeclarationKeywords, $stackPtr - 1, $stopAtPtr > 0 ? $stopAtPtr : 0);
if ($visibilityPtr) {
return true;
}
$staticPtr = $phpcsFile->findPrevious(T_STATIC, $stackPtr - 1, $stopAtPtr > 0 ? $stopAtPtr : 0);
if (! $staticPtr) {
return false;
}
$stopAtPtr = $staticPtr - 2;
$visibilityPtr = $phpcsFile->findPrevious($propertyDeclarationKeywords, $staticPtr - 1, $stopAtPtr > 0 ? $stopAtPtr : 0);
if ($visibilityPtr) {
return true;
}
// it's legal to use `static` to define properties as well as to
// define variables, so make sure we are not in a function before
// assuming it's a property.
// Make sure we are not in a class method before assuming it's a property.
$tokens = $phpcsFile->getTokens();

/** @var array{conditions?: (int|string)[], content?: string}|null */
Expand Down

0 comments on commit 04e3d23

Please sign in to comment.