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

Simplify detecting class properties to improve detection for anonymous classes #337

Merged
merged 3 commits into from
Nov 30, 2024
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
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
Loading