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

feature: [PHP8.2] Support for readonly classes #6745

Merged
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/AbstractDoctrineAnnotationFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -207,13 +207,19 @@ protected function createConfigurationDefinition(): FixerConfigurationResolverIn

private function nextElementAcceptsDoctrineAnnotations(Tokens $tokens, int $index): bool
{
$classModifiers = [T_ABSTRACT, T_FINAL];

if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.2+ is required
$classModifiers[] = T_READONLY;
}

do {
$index = $tokens->getNextMeaningfulToken($index);

if (null === $index) {
return false;
}
} while ($tokens[$index]->isGivenKind([T_ABSTRACT, T_FINAL]));
} while ($tokens[$index]->isGivenKind($classModifiers));

if ($tokens[$index]->isGivenKind(T_CLASS)) {
return true;
Expand Down
8 changes: 7 additions & 1 deletion src/Fixer/AbstractPhpUnitFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,15 @@ abstract protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex

final protected function getDocBlockIndex(Tokens $tokens, int $index): int
{
$modifiers = [T_PUBLIC, T_PROTECTED, T_PRIVATE, T_FINAL, T_ABSTRACT, T_COMMENT];

if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.2+ is required
$modifiers[] = T_READONLY;
}

do {
$index = $tokens->getPrevNonWhitespace($index);
} while ($tokens[$index]->isGivenKind([T_PUBLIC, T_PROTECTED, T_PRIVATE, T_FINAL, T_ABSTRACT, T_COMMENT]));
} while ($tokens[$index]->isGivenKind($modifiers));

return $index;
}
Expand Down
87 changes: 69 additions & 18 deletions src/Fixer/ClassNotation/ClassDefinitionFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,8 @@ private function fixClassyDefinition(Tokens $tokens, int $classyIndex): void

// 4.1 The extends and implements keywords MUST be declared on the same line as the class name.
$this->makeClassyDefinitionSingleLine($tokens, $classDefInfo['start'], $end);

$this->sortClassModifiers($tokens, $classDefInfo);
}

private function fixClassyDefinitionExtends(Tokens $tokens, int $classOpenIndex, array $classExtendsInfo): array
Expand Down Expand Up @@ -294,42 +296,56 @@ private function fixClassyDefinitionOpenSpacing(Tokens $tokens, array $classDefI
* extends: false|array{start: int, numberOfExtends: int, multiLine: bool},
* implements: false|array{start: int, numberOfImplements: int, multiLine: bool},
* anonymousClass: bool,
* final: false|int,
* abstract: false|int,
* readonly: false|int,
* }
*/
private function getClassyDefinitionInfo(Tokens $tokens, int $classyIndex): array
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
$openIndex = $tokens->getNextTokenOfKind($classyIndex, ['{']);
$extends = false;
$implements = false;
$anonymousClass = false;
$def = [
'classy' => $classyIndex,
'open' => $openIndex,
'extends' => false,
'implements' => false,
'anonymousClass' => false,
'final' => false,
'abstract' => false,
'readonly' => false,
];

if (!$tokens[$classyIndex]->isGivenKind(T_TRAIT)) {
$extends = $tokens->findGivenKind(T_EXTENDS, $classyIndex, $openIndex);
$extends = \count($extends) ? $this->getClassyInheritanceInfo($tokens, key($extends), 'numberOfExtends') : false;
$def['extends'] = \count($extends) ? $this->getClassyInheritanceInfo($tokens, key($extends), 'numberOfExtends') : false;

if (!$tokens[$classyIndex]->isGivenKind(T_INTERFACE)) {
$implements = $tokens->findGivenKind(T_IMPLEMENTS, $classyIndex, $openIndex);
$implements = \count($implements) ? $this->getClassyInheritanceInfo($tokens, key($implements), 'numberOfImplements') : false;
$tokensAnalyzer = new TokensAnalyzer($tokens);
$anonymousClass = $tokensAnalyzer->isAnonymousClass($classyIndex);
$def['implements'] = \count($implements) ? $this->getClassyInheritanceInfo($tokens, key($implements), 'numberOfImplements') : false;
$def['anonymousClass'] = $tokensAnalyzer->isAnonymousClass($classyIndex);
}
}

if ($anonymousClass) {
if ($def['anonymousClass']) {
$startIndex = $tokens->getPrevMeaningfulToken($classyIndex); // go to "new" for anonymous class
} else {
$prev = $tokens->getPrevMeaningfulToken($classyIndex);
$startIndex = $tokens[$prev]->isGivenKind([T_FINAL, T_ABSTRACT]) ? $prev : $classyIndex;
$modifiers = $tokensAnalyzer->getClassyModifiers($classyIndex);
$startIndex = $classyIndex;

foreach (['final', 'abstract', 'readonly'] as $modifier) {
if (isset($modifiers[$modifier])) {
$def[$modifier] = $modifiers[$modifier];
$startIndex = min($startIndex, $modifiers[$modifier]);
} else {
$def[$modifier] = false;
}
}
}

return [
'start' => $startIndex,
'classy' => $classyIndex,
'open' => $openIndex,
'extends' => $extends,
'implements' => $implements,
'anonymousClass' => $anonymousClass,
];
$def['start'] = $startIndex;

return $def;
}

private function getClassyInheritanceInfo(Tokens $tokens, int $startIndex, string $label): array
Expand Down Expand Up @@ -457,4 +473,39 @@ private function makeClassyInheritancePartMultiLine(Tokens $tokens, int $startIn
$i = $previousInterfaceImplementingIndex + 1;
}
}

/**
* @param array{
* final: false|int,
* abstract: false|int,
* readonly: false|int,
* } $classDefInfo
*/
private function sortClassModifiers(Tokens $tokens, array $classDefInfo): void
{
if (false === $classDefInfo['readonly']) {
return;
}

$readonlyIndex = $classDefInfo['readonly'];

foreach (['final', 'abstract'] as $accessModifier) {
if (false === $classDefInfo[$accessModifier] || $classDefInfo[$accessModifier] < $readonlyIndex) {
continue;
}

$accessModifierIndex = $classDefInfo[$accessModifier];

/** @var Token $readonlyToken */
$readonlyToken = clone $tokens[$readonlyIndex];

/** @var Token $accessToken */
$accessToken = clone $tokens[$accessModifierIndex];

$tokens[$readonlyIndex] = $accessToken;
$tokens[$accessModifierIndex] = $readonlyToken;

break;
}
}
}
16 changes: 12 additions & 4 deletions src/Fixer/ClassNotation/FinalInternalClassFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
$tokensAnalyzer = new TokensAnalyzer($tokens);

for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
if (!$tokens[$index]->isGivenKind(T_CLASS) || $tokensAnalyzer->isAnonymousClass($index) || !$this->isClassCandidate($tokens, $index)) {
if (!$tokens[$index]->isGivenKind(T_CLASS) || !$this->isClassCandidate($tokensAnalyzer, $tokens, $index)) {
continue;
}

Expand Down Expand Up @@ -142,7 +142,7 @@ protected function createConfigurationDefinition(): FixerConfigurationResolverIn
$annotationsNormalizer = static function (Options $options, array $value): array {
$newValue = [];
foreach ($value as $key) {
if ('@' === $key[0]) {
if (str_starts_with($key, '@')) {
$key = substr($key, 1);
}

Expand Down Expand Up @@ -183,9 +183,15 @@ protected function createConfigurationDefinition(): FixerConfigurationResolverIn
/**
* @param int $index T_CLASS index
*/
private function isClassCandidate(Tokens $tokens, int $index): bool
private function isClassCandidate(TokensAnalyzer $tokensAnalyzer, Tokens $tokens, int $index): bool
{
if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind([T_ABSTRACT, T_FINAL])) {
if ($tokensAnalyzer->isAnonymousClass($index)) {
return false;
}

$modifiers = $tokensAnalyzer->getClassyModifiers($index);

if (isset($modifiers['final']) || isset($modifiers['abstract'])) {
return false; // ignore class; it is abstract or already final
}

Expand All @@ -202,7 +208,9 @@ private function isClassCandidate(Tokens $tokens, int $index): bool
if (1 !== Preg::match('/@\S+(?=\s|$)/', $annotation->getContent(), $matches)) {
continue;
}

$tag = strtolower(substr(array_shift($matches), 1));

foreach ($this->configuration['annotation_exclude'] as $tagStart => $true) {
if (str_starts_with($tag, $tagStart)) {
return false; // ignore class: class-level PHPDoc contains tag that has been excluded through configuration
Expand Down
4 changes: 2 additions & 2 deletions src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -181,8 +181,8 @@ private function getMethods(Tokens $tokens): \Generator
}

if (!\array_key_exists($classIndex, $classesAreFinal)) {
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($classIndex)];
$classesAreFinal[$classIndex] = $prevToken->isGivenKind(T_FINAL);
$modifiers = $tokensAnalyzer->getClassyModifiers($classIndex);
$classesAreFinal[$classIndex] = isset($modifiers['final']);
}

$element['method_of_enum'] = false;
Expand Down
25 changes: 20 additions & 5 deletions src/Fixer/ClassNotation/ProtectedToPrivateFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
*/
final class ProtectedToPrivateFixer extends AbstractFixer
{
private TokensAnalyzer $tokensAnalyzer;

/**
* {@inheritdoc}
*/
Expand Down Expand Up @@ -80,7 +82,7 @@ public function isCandidate(Tokens $tokens): bool
*/
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
$this->tokensAnalyzer = new TokensAnalyzer($tokens);
$modifierKinds = [T_PUBLIC, T_PROTECTED, T_PRIVATE, T_FINAL, T_ABSTRACT, T_NS_SEPARATOR, T_STRING, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, T_STATIC, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION];

if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.1+ is required
Expand All @@ -90,15 +92,15 @@ protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
$classesCandidate = [];
$classElementTypes = ['method' => true, 'property' => true, 'const' => true];

foreach ($tokensAnalyzer->getClassyElements() as $index => $element) {
foreach ($this->tokensAnalyzer->getClassyElements() as $index => $element) {
$classIndex = $element['classIndex'];

if (!\array_key_exists($classIndex, $classesCandidate)) {
$classesCandidate[$classIndex] = $this->isClassCandidate($tokens, $classIndex);
}

if (false === $classesCandidate[$classIndex]) {
continue; // not "final" class, "extends", is "anonymous", enum or uses trait
continue;
}

if (!isset($classElementTypes[$element['type']])) {
Expand Down Expand Up @@ -132,15 +134,28 @@ protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
}
}

/**
* Consider symbol as candidate for fixing if it's:
* - an Enum (PHP8.1+)
* - a class, which:
* - is not anonymous
* - is not final
* - does not use traits
* - does not extend other class.
*/
private function isClassCandidate(Tokens $tokens, int $classIndex): bool
{
if (\defined('T_ENUM') && $tokens[$classIndex]->isGivenKind(T_ENUM)) { // @TODO: drop condition when PHP 8.1+ is required
return true;
}

$prevToken = $tokens[$tokens->getPrevMeaningfulToken($classIndex)];
if (!$tokens[$classIndex]->isGivenKind(T_CLASS) || $this->tokensAnalyzer->isAnonymousClass($classIndex)) {
return false;
}

$modifiers = $this->tokensAnalyzer->getClassyModifiers($classIndex);

if (!$prevToken->isGivenKind(T_FINAL)) {
if (!isset($modifiers['final'])) {
return false;
}

Expand Down
13 changes: 4 additions & 9 deletions src/Fixer/ClassNotation/SelfStaticAccessorFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@

final class SelfStaticAccessorFixer extends AbstractFixer
{
/**
* @var TokensAnalyzer
*/
private $tokensAnalyzer;
private TokensAnalyzer $tokensAnalyzer;

/**
* {@inheritdoc}
Expand Down Expand Up @@ -115,14 +112,12 @@ public function getPriority(): int
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$this->tokensAnalyzer = new TokensAnalyzer($tokens);

$classIndex = $tokens->getNextTokenOfKind(0, [[T_CLASS]]);

while (null !== $classIndex) {
if (
$this->tokensAnalyzer->isAnonymousClass($classIndex)
|| $tokens[$tokens->getPrevMeaningfulToken($classIndex)]->isGivenKind(T_FINAL)
) {
$modifiers = $this->tokensAnalyzer->getClassyModifiers($classIndex);

if (isset($modifiers['final']) || $this->tokensAnalyzer->isAnonymousClass($classIndex)) {
$classIndex = $this->fixClass($tokens, $classIndex);
}

Expand Down
24 changes: 14 additions & 10 deletions src/Fixer/PhpUnit/PhpUnitInternalClassFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;

/**
* @author Gert de Pagter <BackEndTea@gmail.com>
Expand Down Expand Up @@ -98,14 +99,16 @@ protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $en
}
}

private function isAllowedByConfiguration(Tokens $tokens, int $i): bool
private function isAllowedByConfiguration(Tokens $tokens, int $index): bool
{
$typeIndex = $tokens->getPrevMeaningfulToken($i);
if ($tokens[$typeIndex]->isGivenKind(T_FINAL)) {
$tokensAnalyzer = new TokensAnalyzer($tokens);
$modifiers = $tokensAnalyzer->getClassyModifiers($index);

if (isset($modifiers['final'])) {
return \in_array('final', $this->configuration['types'], true);
}

if ($tokens[$typeIndex]->isGivenKind(T_ABSTRACT)) {
if (isset($modifiers['abstract'])) {
return \in_array('abstract', $this->configuration['types'], true);
}

Expand All @@ -116,12 +119,13 @@ private function createDocBlock(Tokens $tokens, int $docBlockIndex): void
{
$lineEnd = $this->whitespacesConfig->getLineEnding();
$originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex));
$toInsert = [
new Token([T_DOC_COMMENT, '/**'.$lineEnd."{$originalIndent} * @internal".$lineEnd."{$originalIndent} */"]),
new Token([T_WHITESPACE, $lineEnd.$originalIndent]),
];
$index = $tokens->getNextMeaningfulToken($docBlockIndex);
$tokens->insertAt($index, $toInsert);

$tokens->insertSlices([
$tokens->getNextMeaningfulToken($docBlockIndex) => [
new Token([T_DOC_COMMENT, '/**'.$lineEnd."{$originalIndent} * @internal".$lineEnd."{$originalIndent} */"]),
new Token([T_WHITESPACE, $lineEnd.$originalIndent]),
],
]);
}

private function updateDocBlockIfNeeded(Tokens $tokens, int $docBlockIndex): void
Expand Down
18 changes: 13 additions & 5 deletions src/Fixer/PhpUnit/PhpUnitTestClassRequiresCoversFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;

/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
Expand Down Expand Up @@ -59,14 +60,21 @@ public function testSomeTest()
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$classIndex = $tokens->getPrevTokenOfKind($startIndex, [[T_CLASS]]);
$prevIndex = $tokens->getPrevMeaningfulToken($classIndex);

// don't add `@covers` annotation for abstract base classes
if ($tokens[$prevIndex]->isGivenKind(T_ABSTRACT)) {
return;
$tokensAnalyzer = new TokensAnalyzer($tokens);
$modifiers = $tokensAnalyzer->getClassyModifiers($classIndex);

if (isset($modifiers['abstract'])) {
return; // don't add `@covers` annotation for abstract base classes
}

$index = $tokens[$prevIndex]->isGivenKind(T_FINAL) ? $prevIndex : $classIndex;
$index = $classIndex;

foreach ($modifiers as $modifier => $modifierIndex) {
if (null !== $modifierIndex) {
$index = min($index, $modifierIndex);
}
}

$indent = $tokens[$index - 1]->isGivenKind(T_WHITESPACE)
? Preg::replace('/^.*\R*/', '', $tokens[$index - 1]->getContent())
Expand Down