Skip to content

Commit

Permalink
Merge pull request #324 from PHPCSStandards/php-8.3/psr12-classinstan…
Browse files Browse the repository at this point in the history
…tiation-allow-for-readonly-anon-classes

PHP 8.3 | PSR12/ClassInstantiation: allow for readonly anonymous classes
  • Loading branch information
jrfnl committed Feb 8, 2024
2 parents 675d8f3 + 5fd4059 commit 10249a2
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 9 deletions.
15 changes: 6 additions & 9 deletions src/Standards/PSR12/Sniffs/Classes/ClassInstantiationSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,14 @@ public function process(File $phpcsFile, $stackPtr)
continue;
}

// Skip over potential attributes for anonymous classes.
// Bow out when this is an anonymous class.
// Anonymous classes are the only situation which would allow for an attribute
// or for the readonly keyword between "new" and the class "name".
if ($tokens[$i]['code'] === T_ATTRIBUTE
&& isset($tokens[$i]['attribute_closer']) === true
|| $tokens[$i]['code'] === T_READONLY
|| $tokens[$i]['code'] === T_ANON_CLASS
) {
$i = $tokens[$i]['attribute_closer'];
continue;
return;
}

if ($tokens[$i]['code'] === T_OPEN_SQUARE_BRACKET
Expand All @@ -87,11 +89,6 @@ public function process(File $phpcsFile, $stackPtr)
return;
}

if ($tokens[$classNameEnd]['code'] === T_ANON_CLASS) {
// Ignore anon classes.
return;
}

if ($tokens[$classNameEnd]['code'] === T_OPEN_PARENTHESIS) {
// Using parenthesis.
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,7 @@ $anonWithAttribute = new #[SomeAttribute('summary')] class {

$foo = new parent();
$foo = new parent;

// PHP 8.3: safeguard that the sniff ignores anonymous classes, even when declared as readonly.
$anon = new readonly class {};
$anon = new #[MyAttribute] readonly class {};
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,7 @@ $anonWithAttribute = new #[SomeAttribute('summary')] class {

$foo = new parent();
$foo = new parent();

// PHP 8.3: safeguard that the sniff ignores anonymous classes, even when declared as readonly.
$anon = new readonly class {};
$anon = new #[MyAttribute] readonly class {};

0 comments on commit 10249a2

Please sign in to comment.