Skip to content

Commit

Permalink
Merge branch 'feature/psr12-classinstantiation-bug-fix-attributes-vs-…
Browse files Browse the repository at this point in the history
  • Loading branch information
gsherwood committed Dec 12, 2021
2 parents 5b660ae + 76faf86 commit 40afa3d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/Standards/PSR12/Sniffs/Classes/ClassInstantiationSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,14 @@ public function process(File $phpcsFile, $stackPtr)
continue;
}

// Skip over potential attributes for anonymous classes.
if ($tokens[$i]['code'] === T_ATTRIBUTE
&& isset($tokens[$i]['attribute_closer']) === true
) {
$i = $tokens[$i]['attribute_closer'];
continue;
}

if ($tokens[$i]['code'] === T_OPEN_SQUARE_BRACKET
|| $tokens[$i]['code'] === T_OPEN_CURLY_BRACKET
) {
Expand All @@ -72,7 +80,7 @@ public function process(File $phpcsFile, $stackPtr)

$classNameEnd = $i;
break;
}
}//end for

if ($classNameEnd === null) {
return;
Expand All @@ -88,6 +96,11 @@ public function process(File $phpcsFile, $stackPtr)
return;
}

if ($classNameEnd === $stackPtr) {
// Failed to find the class name.
return;
}

$error = 'Parentheses must be used when instantiating a new class';
$fix = $phpcsFile->addFixableError($error, $stackPtr, 'MissingParentheses');
if ($fix === true) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,9 @@ $a = new ${$varHoldingClassName};
$class = new $obj?->classname();
$class = new $obj?->classname;
$class = new ${$obj?->classname};

// Issue 3456.
// Anon classes should be skipped, even when there is an attribute between the new and the class keywords.
$anonWithAttribute = new #[SomeAttribute('summary')] class {
public const SOME_STUFF = 'foo';
};
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,9 @@ $a = new ${$varHoldingClassName}();
$class = new $obj?->classname();
$class = new $obj?->classname();
$class = new ${$obj?->classname}();

// Issue 3456.
// Anon classes should be skipped, even when there is an attribute between the new and the class keywords.
$anonWithAttribute = new #[SomeAttribute('summary')] class {
public const SOME_STUFF = 'foo';
};

0 comments on commit 40afa3d

Please sign in to comment.