repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Operator/TernaryOperatorSpacesFixer.php | src/Fixer/Operator/TernaryOperatorSpacesFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\SwitchAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class TernaryOperatorSpacesFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Standardize spaces around ternary operator.',
[new CodeSample("<?php \$a = \$a ?1 :0;\n")],
);
}
/**
* {@inheritdoc}
*
* Must run after ArraySyntaxFixer, ListSyntaxFixer, TernaryToElvisOperatorFixer.
*/
public function getPriority(): int
{
return 1;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAllTokenKindsFound(['?', ':']);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$alternativeSyntaxAnalyzer = new AlternativeSyntaxAnalyzer();
$gotoLabelAnalyzer = new GotoLabelAnalyzer();
$ternaryOperatorIndices = [];
foreach ($tokens as $index => $token) {
if (!$token->equalsAny(['?', ':'])) {
continue;
}
if (SwitchAnalyzer::belongsToSwitch($tokens, $index)) {
continue;
}
if ($alternativeSyntaxAnalyzer->belongsToAlternativeSyntax($tokens, $index)) {
continue;
}
if ($gotoLabelAnalyzer->belongsToGoToLabel($tokens, $index)) {
continue;
}
$ternaryOperatorIndices[] = $index;
}
foreach (array_reverse($ternaryOperatorIndices) as $index) {
$token = $tokens[$index];
if ($token->equals('?')) {
$nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($index);
if ($tokens[$nextNonWhitespaceIndex]->equals(':')) {
// for `$a ?: $b` remove spaces between `?` and `:`
$tokens->ensureWhitespaceAtIndex($index + 1, 0, '');
} else {
// for `$a ? $b : $c` ensure space after `?`
$this->ensureWhitespaceExistence($tokens, $index + 1, true);
}
// for `$a ? $b : $c` ensure space before `?`
$this->ensureWhitespaceExistence($tokens, $index - 1, false);
continue;
}
if ($token->equals(':')) {
// for `$a ? $b : $c` ensure space after `:`
$this->ensureWhitespaceExistence($tokens, $index + 1, true);
$prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)];
if (!$prevNonWhitespaceToken->equals('?')) {
// for `$a ? $b : $c` ensure space before `:`
$this->ensureWhitespaceExistence($tokens, $index - 1, false);
}
}
}
}
private function ensureWhitespaceExistence(Tokens $tokens, int $index, bool $after): void
{
if ($tokens[$index]->isWhitespace()) {
if (
!str_contains($tokens[$index]->getContent(), "\n")
&& !$tokens[$index - 1]->isComment()
) {
$tokens[$index] = new Token([\T_WHITESPACE, ' ']);
}
return;
}
$index += $after ? 0 : 1;
$tokens->insertAt($index, new Token([\T_WHITESPACE, ' ']));
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Operator/NoSpaceAroundDoubleColonFixer.php | src/Fixer/Operator/NoSpaceAroundDoubleColonFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoSpaceAroundDoubleColonFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There must be no space around double colons (also called Scope Resolution Operator or Paamayim Nekudotayim).',
[new CodeSample("<?php\n\necho Foo\\Bar :: class;\n")],
);
}
/**
* {@inheritdoc}
*
* Must run before MethodChainingIndentationFixer.
*/
public function getPriority(): int
{
return 1;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_DOUBLE_COLON);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = \count($tokens) - 2; $index > 1; --$index) {
if ($tokens[$index]->isGivenKind(\T_DOUBLE_COLON)) {
$this->removeSpace($tokens, $index, 1);
$this->removeSpace($tokens, $index, -1);
}
}
}
/**
* @param -1|1 $direction
*/
private function removeSpace(Tokens $tokens, int $index, int $direction): void
{
if (!$tokens[$index + $direction]->isWhitespace()) {
return;
}
if ($tokens[$tokens->getNonWhitespaceSibling($index, $direction)]->isComment()) {
return;
}
$tokens->clearAt($index + $direction);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Operator/TernaryToNullCoalescingFixer.php | src/Fixer/Operator/TernaryToNullCoalescingFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Filippo Tessarotto <zoeslam@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class TernaryToNullCoalescingFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Use `null` coalescing operator `??` where possible.',
[
new CodeSample(
"<?php\n\$sample = isset(\$a) ? \$a : \$b;\n",
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before AssignNullCoalescingToCoalesceEqualFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_ISSET);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$issetIndices = array_keys($tokens->findGivenKind(\T_ISSET));
foreach (array_reverse($issetIndices) as $issetIndex) {
$this->fixIsset($tokens, $issetIndex);
}
}
/**
* @param int $index of `T_ISSET` token
*/
private function fixIsset(Tokens $tokens, int $index): void
{
$prevTokenIndex = $tokens->getPrevMeaningfulToken($index);
if ($this->isHigherPrecedenceAssociativityOperator($tokens[$prevTokenIndex])) {
return;
}
$startBraceIndex = $tokens->getNextTokenOfKind($index, ['(']);
$endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startBraceIndex);
$ternaryQuestionMarkIndex = $tokens->getNextMeaningfulToken($endBraceIndex);
if (!$tokens[$ternaryQuestionMarkIndex]->equals('?')) {
return; // we are not in a ternary operator
}
// search what is inside the isset()
$issetTokens = $this->getMeaningfulSequence($tokens, $startBraceIndex, $endBraceIndex);
if ($this->hasChangingContent($issetTokens)) {
return; // some weird stuff inside the isset
}
$issetCode = $issetTokens->generateCode();
if ('$this' === $issetCode) {
return; // null coalescing operator does not with $this
}
// search what is inside the middle argument of ternary operator
$ternaryColonIndex = $tokens->getNextTokenOfKind($ternaryQuestionMarkIndex, [':']);
$ternaryFirstOperandTokens = $this->getMeaningfulSequence($tokens, $ternaryQuestionMarkIndex, $ternaryColonIndex);
if ($issetCode !== $ternaryFirstOperandTokens->generateCode()) {
return; // regardless of non-meaningful tokens, the operands are different
}
$ternaryFirstOperandIndex = $tokens->getNextMeaningfulToken($ternaryQuestionMarkIndex);
// preserve comments and spaces
$comments = [];
$commentStarted = false;
for ($loopIndex = $index; $loopIndex < $ternaryFirstOperandIndex; ++$loopIndex) {
if ($tokens[$loopIndex]->isComment()) {
$comments[] = $tokens[$loopIndex];
$commentStarted = true;
} elseif ($commentStarted) {
if ($tokens[$loopIndex]->isWhitespace()) {
$comments[] = $tokens[$loopIndex];
}
$commentStarted = false;
}
}
$tokens[$ternaryColonIndex] = new Token([\T_COALESCE, '??']);
$tokens->overrideRange($index, $ternaryFirstOperandIndex - 1, $comments);
}
/**
* Get the sequence of meaningful tokens and returns a new Tokens instance.
*
* @param int $start start index
* @param int $end end index
*/
private function getMeaningfulSequence(Tokens $tokens, int $start, int $end): Tokens
{
$sequence = [];
$index = $start;
while ($index < $end) {
$index = $tokens->getNextMeaningfulToken($index);
if ($index >= $end || null === $index) {
break;
}
$sequence[] = $tokens[$index];
}
return Tokens::fromArray($sequence);
}
/**
* Check if the requested token is an operator computed
* before the ternary operator along with the `isset()`.
*/
private function isHigherPrecedenceAssociativityOperator(Token $token): bool
{
return
$token->isGivenKind([
\T_ARRAY_CAST,
\T_BOOLEAN_AND,
\T_BOOLEAN_OR,
\T_BOOL_CAST,
\T_COALESCE,
\T_DEC,
\T_DOUBLE_CAST,
\T_INC,
\T_INT_CAST,
\T_IS_EQUAL,
\T_IS_GREATER_OR_EQUAL,
\T_IS_IDENTICAL,
\T_IS_NOT_EQUAL,
\T_IS_NOT_IDENTICAL,
\T_IS_SMALLER_OR_EQUAL,
\T_OBJECT_CAST,
\T_POW,
\T_SL,
\T_SPACESHIP,
\T_SR,
\T_STRING_CAST,
\T_UNSET_CAST,
])
|| $token->equalsAny([
'!',
'%',
'&',
'*',
'+',
'-',
'/',
':',
'^',
'|',
'~',
'.',
]);
}
/**
* Check if the `isset()` content may change if called multiple times.
*
* @param Tokens $tokens The original token list
*/
private function hasChangingContent(Tokens $tokens): bool
{
foreach ($tokens as $token) {
if ($token->isGivenKind([
\T_DEC,
\T_INC,
\T_YIELD,
\T_YIELD_FROM,
]) || $token->equals('(')) {
return true;
}
}
return false;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Operator/OperatorLinebreakFixer.php | src/Fixer/Operator/OperatorLinebreakFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\ReferenceAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\SwitchAnalyzer;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* only_booleans?: bool,
* position?: 'beginning'|'end',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* only_booleans: bool,
* position: 'beginning'|'end',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @phpstan-import-type _PhpTokenPrototypePartial from Token
*
* @author Kuba Werłos <werlos@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class OperatorLinebreakFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private const BOOLEAN_OPERATORS = [[\T_BOOLEAN_AND], [\T_BOOLEAN_OR], [\T_LOGICAL_AND], [\T_LOGICAL_OR], [\T_LOGICAL_XOR]];
private string $position = 'beginning';
/**
* @var list<_PhpTokenPrototypePartial>
*/
private array $operators = [];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Operators - when multiline - must always be at the beginning or at the end of the line.',
[
new CodeSample(
<<<'PHP'
<?php
$a = $b ||
$c;
$d = $e +
$f;
PHP,
),
new CodeSample(
<<<'PHP'
<?php
$a = $b ||
$c;
$d = $e +
$f;
PHP,
['only_booleans' => true],
),
new CodeSample(
<<<'PHP'
<?php
$a = $b
|| $c;
$d = $e
+ $f;
PHP,
['position' => 'end'],
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return true;
}
protected function configurePostNormalisation(): void
{
$this->position = $this->configuration['position'];
$this->operators = self::BOOLEAN_OPERATORS;
if (false === $this->configuration['only_booleans']) {
$this->operators = array_merge($this->operators, self::getNonBooleanOperators());
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('only_booleans', 'Whether to limit operators to only boolean ones.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
(new FixerOptionBuilder('position', 'Whether to place operators at the beginning or at the end of the line.'))
->setAllowedValues(['beginning', 'end'])
->setDefault($this->position)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$referenceAnalyzer = new ReferenceAnalyzer();
$gotoLabelAnalyzer = new GotoLabelAnalyzer();
$alternativeSyntaxAnalyzer = new AlternativeSyntaxAnalyzer();
$index = $tokens->count();
while ($index > 1) {
--$index;
if (!$tokens[$index]->equalsAny($this->operators, false)) {
continue;
}
if ($gotoLabelAnalyzer->belongsToGoToLabel($tokens, $index)) {
continue;
}
if ($referenceAnalyzer->isReference($tokens, $index)) {
continue;
}
if ($alternativeSyntaxAnalyzer->belongsToAlternativeSyntax($tokens, $index)) {
continue;
}
if (SwitchAnalyzer::belongsToSwitch($tokens, $index)) {
continue;
}
$operatorIndices = [$index];
if ($tokens[$index]->equals(':')) {
/** @var int $prevIndex */
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevIndex]->equals('?')) {
$operatorIndices = [$prevIndex, $index];
$index = $prevIndex;
}
}
$this->fixOperatorLinebreak($tokens, $operatorIndices);
}
}
/**
* @param non-empty-list<int> $operatorIndices
*/
private function fixOperatorLinebreak(Tokens $tokens, array $operatorIndices): void
{
/** @var int $prevIndex */
$prevIndex = $tokens->getPrevMeaningfulToken(min($operatorIndices));
$indexStart = $prevIndex + 1;
/** @var int $nextIndex */
$nextIndex = $tokens->getNextMeaningfulToken(max($operatorIndices));
$indexEnd = $nextIndex - 1;
if (!$this->isMultiline($tokens, $indexStart, $indexEnd)) {
return; // operator is not surrounded by multiline whitespaces, do not touch it
}
if ('beginning' === $this->position) {
if (!$this->isMultiline($tokens, max($operatorIndices), $indexEnd)) {
return; // operator already is placed correctly
}
$this->fixMoveToTheBeginning($tokens, $operatorIndices);
return;
}
if (!$this->isMultiline($tokens, $indexStart, min($operatorIndices))) {
return; // operator already is placed correctly
}
$this->fixMoveToTheEnd($tokens, $operatorIndices);
}
/**
* @param non-empty-list<int> $operatorIndices
*/
private function fixMoveToTheBeginning(Tokens $tokens, array $operatorIndices): void
{
/** @var int $prevIndex */
$prevIndex = $tokens->getNonEmptySibling(min($operatorIndices), -1);
/** @var int $nextIndex */
$nextIndex = $tokens->getNextMeaningfulToken(max($operatorIndices));
for ($i = $nextIndex - 1; $i > max($operatorIndices); --$i) {
if ($tokens[$i]->isWhitespace() && Preg::match('/\R/u', $tokens[$i]->getContent())) {
$isWhitespaceBefore = $tokens[$prevIndex]->isWhitespace();
$inserts = $this->getReplacementsAndClear($tokens, $operatorIndices, -1);
if ($isWhitespaceBefore) {
$inserts[] = new Token([\T_WHITESPACE, ' ']);
}
$tokens->insertAt($nextIndex, $inserts);
break;
}
}
}
/**
* @param non-empty-list<int> $operatorIndices
*/
private function fixMoveToTheEnd(Tokens $tokens, array $operatorIndices): void
{
/** @var int $prevIndex */
$prevIndex = $tokens->getPrevMeaningfulToken(min($operatorIndices));
/** @var int $nextIndex */
$nextIndex = $tokens->getNonEmptySibling(max($operatorIndices), 1);
for ($i = $prevIndex + 1; $i < max($operatorIndices); ++$i) {
if ($tokens[$i]->isWhitespace() && Preg::match('/\R/u', $tokens[$i]->getContent())) {
$isWhitespaceAfter = $tokens[$nextIndex]->isWhitespace();
$inserts = $this->getReplacementsAndClear($tokens, $operatorIndices, 1);
if ($isWhitespaceAfter) {
array_unshift($inserts, new Token([\T_WHITESPACE, ' ']));
}
$tokens->insertAt($prevIndex + 1, $inserts);
break;
}
}
}
/**
* @param list<int> $indices
*
* @return list<Token>
*/
private function getReplacementsAndClear(Tokens $tokens, array $indices, int $direction): array
{
return array_map(
static function (int $index) use ($tokens, $direction): Token {
$clone = $tokens[$index];
if ($tokens[$index + $direction]->isWhitespace()) {
$tokens->clearAt($index + $direction);
}
$tokens->clearAt($index);
return $clone;
},
$indices,
);
}
private function isMultiline(Tokens $tokens, int $indexStart, int $indexEnd): bool
{
for ($index = $indexStart; $index <= $indexEnd; ++$index) {
if (str_contains($tokens[$index]->getContent(), "\n")) {
return true;
}
}
return false;
}
/**
* @return non-empty-list<_PhpTokenPrototypePartial>
*/
private static function getNonBooleanOperators(): array
{
return array_merge(
[
'%', '&', '*', '+', '-', '.', '/', ':', '<', '=', '>', '?', '^', '|',
[\T_AND_EQUAL], [\T_CONCAT_EQUAL], [\T_DIV_EQUAL], [\T_DOUBLE_ARROW], [\T_IS_EQUAL], [\T_IS_GREATER_OR_EQUAL],
[\T_IS_IDENTICAL], [\T_IS_NOT_EQUAL], [\T_IS_NOT_IDENTICAL], [\T_IS_SMALLER_OR_EQUAL], [\T_MINUS_EQUAL],
[\T_MOD_EQUAL], [\T_MUL_EQUAL], [\T_OR_EQUAL], [\T_PAAMAYIM_NEKUDOTAYIM], [\T_PLUS_EQUAL], [\T_POW],
[\T_POW_EQUAL], [\T_SL], [\T_SL_EQUAL], [\T_SR], [\T_SR_EQUAL], [\T_XOR_EQUAL],
[\T_COALESCE], [\T_SPACESHIP], [FCT::T_PIPE],
],
array_map(static fn (int $id): array => [$id], Token::getObjectOperatorKinds()),
);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Operator/LogicalOperatorsFixer.php | src/Fixer/Operator/LogicalOperatorsFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Haralan Dobrev <hkdobrev@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class LogicalOperatorsFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Use `&&` and `||` logical operators instead of `and` and `or`.',
[
new CodeSample(
<<<'PHP'
<?php
if ($a == "foo" and ($b == "bar" or $c == "baz")) {
}
PHP,
),
],
null,
'Risky, because you must double-check if using and/or with lower precedence was intentional.',
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([\T_LOGICAL_AND, \T_LOGICAL_OR]);
}
public function isRisky(): bool
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if ($token->isGivenKind(\T_LOGICAL_AND)) {
$tokens[$index] = new Token([\T_BOOLEAN_AND, '&&']);
} elseif ($token->isGivenKind(\T_LOGICAL_OR)) {
$tokens[$index] = new Token([\T_BOOLEAN_OR, '||']);
}
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Operator/UnaryOperatorSpacesFixer.php | src/Fixer/Operator/UnaryOperatorSpacesFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* only_dec_inc?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* only_dec_inc: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Gregor Harlan <gharlan@web.de>
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class UnaryOperatorSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Unary operators should be placed adjacent to their operands.',
[
new CodeSample("<?php\n\$sample ++;\n-- \$sample;\n\$sample = ! ! \$a;\n\$sample = ~ \$c;\nfunction & foo(){}\n"),
new CodeSample(
<<<'PHP'
<?php
function foo($a, ... $b) { return (-- $a) * ($b ++);}
PHP,
['only_dec_inc' => false],
),
new CodeSample(
<<<'PHP'
<?php
function foo($a, ... $b) { return (-- $a) * ($b ++);}
PHP,
['only_dec_inc' => true],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before NotOperatorWithSpaceFixer, NotOperatorWithSuccessorSpaceFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return true;
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('only_dec_inc', 'Limit to increment and decrement operators.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
if (true === $this->configuration['only_dec_inc'] && !$tokens[$index]->isGivenKind([\T_DEC, \T_INC])) {
continue;
}
if ($tokensAnalyzer->isUnarySuccessorOperator($index)) {
if (!$tokens[$tokens->getPrevNonWhitespace($index)]->isComment()) {
$tokens->removeLeadingWhitespace($index);
}
continue;
}
if ($tokensAnalyzer->isUnaryPredecessorOperator($index)) {
$tokens->removeTrailingWhitespace($index);
continue;
}
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Operator/LongToShorthandOperatorFixer.php | src/Fixer/Operator/LongToShorthandOperatorFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\Fixer\AbstractShortOperatorFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @phpstan-import-type _PhpTokenArray from Token
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class LongToShorthandOperatorFixer extends AbstractShortOperatorFixer
{
/**
* @var non-empty-array<string, _PhpTokenArray>
*/
private const OPERATORS = [
'+' => [\T_PLUS_EQUAL, '+='],
'-' => [\T_MINUS_EQUAL, '-='],
'*' => [\T_MUL_EQUAL, '*='],
'/' => [\T_DIV_EQUAL, '/='],
'&' => [\T_AND_EQUAL, '&='],
'.' => [\T_CONCAT_EQUAL, '.='],
'%' => [\T_MOD_EQUAL, '%='],
'|' => [\T_OR_EQUAL, '|='],
'^' => [\T_XOR_EQUAL, '^='],
];
/**
* @var non-empty-list<string>
*/
private array $operatorTypes;
private TokensAnalyzer $tokensAnalyzer;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Shorthand notation for operators should be used if possible.',
[
new CodeSample("<?php\n\$i = \$i + 10;\n"),
],
null,
'Risky when applying for string offsets (e.g. `<?php $text = "foo"; $text[0] = $text[0] & "\x7F";`).',
);
}
/**
* {@inheritdoc}
*
* Must run before BinaryOperatorSpacesFixer, NoExtraBlankLinesFixer, NoSinglelineWhitespaceBeforeSemicolonsFixer, StandardizeIncrementFixer.
*/
public function getPriority(): int
{
return 17;
}
public function isRisky(): bool
{
return true;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([...array_keys(self::OPERATORS), FCT::T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, FCT::T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$this->operatorTypes = array_keys(self::OPERATORS);
$this->tokensAnalyzer = new TokensAnalyzer($tokens);
parent::applyFix($file, $tokens);
}
protected function isOperatorTokenCandidate(Tokens $tokens, int $index): bool
{
if (!$tokens[$index]->equalsAny($this->operatorTypes)) {
return false;
}
while (null !== $index) {
$index = $tokens->getNextMeaningfulToken($index);
$otherToken = $tokens[$index];
if ($otherToken->equalsAny([';', [\T_CLOSE_TAG]])) {
return true;
}
// fast precedence check
if ($otherToken->equals('?') || $otherToken->isGivenKind(\T_INSTANCEOF)) {
return false;
}
$blockType = Tokens::detectBlockType($otherToken);
if (null !== $blockType) {
if (false === $blockType['isStart']) {
return true;
}
$index = $tokens->findBlockEnd($blockType['type'], $index);
continue;
}
// precedence check
if ($this->tokensAnalyzer->isBinaryOperator($index)) {
return false;
}
}
return false; // unreachable, but keeps SCA happy
}
protected function getReplacementToken(Token $token): Token
{
\assert(isset(self::OPERATORS[$token->getContent()])); // for PHPStan
return new Token(self::OPERATORS[$token->getContent()]);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Operator/StandardizeIncrementFixer.php | src/Fixer/Operator/StandardizeIncrementFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\Fixer\AbstractIncrementOperatorFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author ntzm
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class StandardizeIncrementFixer extends AbstractIncrementOperatorFixer
{
private const EXPRESSION_END_TOKENS = [
';',
')',
']',
',',
':',
[CT::T_DYNAMIC_PROP_BRACE_CLOSE],
[CT::T_DYNAMIC_VAR_BRACE_CLOSE],
[\T_CLOSE_TAG],
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Increment and decrement operators should be used if possible.',
[
new CodeSample("<?php\n\$i += 1;\n"),
new CodeSample("<?php\n\$i -= 1;\n"),
],
);
}
/**
* {@inheritdoc}
*
* Must run before IncrementStyleFixer.
* Must run after LongToShorthandOperatorFixer.
*/
public function getPriority(): int
{
return 16;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([\T_PLUS_EQUAL, \T_MINUS_EQUAL]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; $index > 0; --$index) {
$expressionEnd = $tokens[$index];
if (!$expressionEnd->equalsAny(self::EXPRESSION_END_TOKENS)) {
continue;
}
$numberIndex = $tokens->getPrevMeaningfulToken($index);
$number = $tokens[$numberIndex];
if (!$number->isGivenKind(\T_LNUMBER) || '1' !== $number->getContent()) {
continue;
}
$operatorIndex = $tokens->getPrevMeaningfulToken($numberIndex);
$operator = $tokens[$operatorIndex];
if (!$operator->isGivenKind([\T_PLUS_EQUAL, \T_MINUS_EQUAL])) {
continue;
}
$startIndex = $this->findStart($tokens, $operatorIndex);
$this->clearRangeLeaveComments(
$tokens,
$tokens->getPrevMeaningfulToken($operatorIndex) + 1,
$numberIndex,
);
$tokens->insertAt(
$startIndex,
new Token($operator->isGivenKind(\T_PLUS_EQUAL) ? [\T_INC, '++'] : [\T_DEC, '--']),
);
}
}
/**
* Clear tokens in the given range unless they are comments.
*/
private function clearRangeLeaveComments(Tokens $tokens, int $indexStart, int $indexEnd): void
{
for ($i = $indexStart; $i <= $indexEnd; ++$i) {
$token = $tokens[$i];
if ($token->isComment()) {
continue;
}
if ($token->isWhitespace("\n\r")) {
continue;
}
$tokens->clearAt($i);
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Operator/NotOperatorWithSpaceFixer.php | src/Fixer/Operator/NotOperatorWithSpaceFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Javier Spagnoletti <phansys@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NotOperatorWithSpaceFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Logical NOT operators (`!`) should have leading and trailing whitespaces.',
[
new CodeSample(
<<<'PHP'
<?php
if (!$bar) {
echo "Help!";
}
PHP,
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after ModernizeStrposFixer, UnaryOperatorSpacesFixer.
*/
public function getPriority(): int
{
return -10;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound('!');
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if ($token->equals('!')) {
if (!$tokens[$index + 1]->isWhitespace()) {
$tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' ']));
}
if (!$tokens[$index - 1]->isWhitespace()) {
$tokens->insertAt($index, new Token([\T_WHITESPACE, ' ']));
}
}
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Operator/StandardizeNotEqualsFixer.php | src/Fixer/Operator/StandardizeNotEqualsFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class StandardizeNotEqualsFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Replace all `<>` with `!=`.',
[new CodeSample("<?php\n\$a = \$b <> \$c;\n")],
);
}
/**
* {@inheritdoc}
*
* Must run before BinaryOperatorSpacesFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_IS_NOT_EQUAL);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if ($token->isGivenKind(\T_IS_NOT_EQUAL)) {
$tokens[$index] = new Token([\T_IS_NOT_EQUAL, '!=']);
}
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Internal/ConfigurableFixerTemplateFixer.php | src/Fixer/Internal/ConfigurableFixerTemplateFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Internal;
use PhpCsFixer\AbstractDoctrineAnnotationFixer;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer;
use PhpCsFixer\Console\Command\HelpCommand;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Doctrine\Annotation\Tokens as DoctrineAnnotationTokens;
use PhpCsFixer\Fixer\AttributeNotation\OrderedAttributesFixer;
use PhpCsFixer\Fixer\Casing\ConstantCaseFixer;
use PhpCsFixer\Fixer\ClassNotation\FinalInternalClassFixer;
use PhpCsFixer\Fixer\Comment\HeaderCommentFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ControlStructure\NoBreakCommentFixer;
use PhpCsFixer\Fixer\ControlStructure\TrailingCommaInMultilineFixer;
use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\Fixer\Import\OrderedImportsFixer;
use PhpCsFixer\Fixer\InternalFixerInterface;
use PhpCsFixer\Fixer\NamespaceNotation\BlankLinesBeforeNamespaceFixer;
use PhpCsFixer\Fixer\Phpdoc\GeneralPhpdocAnnotationRemoveFixer;
use PhpCsFixer\Fixer\Phpdoc\GeneralPhpdocTagRenameFixer;
use PhpCsFixer\Fixer\Phpdoc\PhpdocOrderByValueFixer;
use PhpCsFixer\Fixer\Phpdoc\PhpdocReturnSelfReferenceFixer;
use PhpCsFixer\Fixer\Phpdoc\PhpdocTagTypeFixer;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\StdinFileInfo;
use PhpCsFixer\Tests\AbstractDoctrineAnnotationFixerTestCase;
use PhpCsFixer\Tests\AbstractFixerTest;
use PhpCsFixer\Tests\AbstractFunctionReferenceFixerTest;
use PhpCsFixer\Tests\AbstractProxyFixerTest;
use PhpCsFixer\Tests\Fixer\Whitespace\AbstractNullableTypeDeclarationFixerTestCase;
use PhpCsFixer\Tests\Test\AbstractFixerTestCase;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Utils;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*
* @warning Does not support PHPUnit attributes
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ConfigurableFixerTemplateFixer extends AbstractFixer implements InternalFixerInterface
{
private const MODIFIERS = [\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_FINAL, \T_ABSTRACT, \T_COMMENT, FCT::T_ATTRIBUTE, FCT::T_READONLY];
public function getName(): string
{
return 'PhpCsFixerInternal/'.parent::getName();
}
public function getDefinition(): FixerDefinitionInterface
{
$fileInfo = $this->getExampleFixerFile();
$file = $fileInfo->openFile('r');
$content = $file->fread($file->getSize());
if (false === $content) {
throw new \RuntimeException('Cannot read example file.');
}
$tokens = Tokens::fromCode($content);
$generalPhpdocAnnotationRemoveFixer = new GeneralPhpdocAnnotationRemoveFixer();
$generalPhpdocAnnotationRemoveFixer->configure([
'annotations' => [
'implements',
'phpstan-type',
],
]);
$generalPhpdocAnnotationRemoveFixer->applyFix($fileInfo, $tokens);
return new FixerDefinition(
'Configurable Fixers must declare Template type.',
[
new CodeSample(
$tokens->generateCode(),
),
],
null,
'This rule auto-adjust @implements and @phpstan-type, which heavily change information for SCA.',
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_CLASS);
}
public function isRisky(): bool
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$this->applyFixForSrc($file, $tokens);
$this->applyFixForTest($file, $tokens);
}
private function applyFixForTest(\SplFileInfo $file, Tokens $tokens): void
{
if (!$this->isTestForFixerFile($file)) {
return;
}
$classIndex = $tokens->getNextTokenOfKind(0, [[\T_CLASS]]);
$docBlockIndex = $this->getDocBlockIndex($tokens, $classIndex);
if (!$tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT)) {
$docBlockIndex = $tokens->getNextMeaningfulToken($docBlockIndex);
$tokens->insertAt($docBlockIndex, [
new Token([\T_DOC_COMMENT, "/**\n */"]),
new Token([\T_WHITESPACE, "\n"]),
]);
}
$doc = new DocBlock($tokens[$docBlockIndex]->getContent());
if (!$doc->isMultiLine()) {
throw new \RuntimeException('Non-multiline docblock not expected, please convert it manually!');
}
$covers = array_map(
static function ($annotation): string {
$parts = explode(' ', $annotation->getContent());
return trim(array_pop($parts));
},
$doc->getAnnotationsOfType(['covers']),
);
$covers = array_filter(
$covers,
static fn (string $className): bool => !str_contains($className, '\Abstract') && str_ends_with($className, 'Fixer'),
);
if (1 !== \count($covers)) {
throw new \RuntimeException('Non-single covers annotation, please handle manually!');
}
$fixerName = array_pop($covers);
$allowedBaseClasses = [
AbstractDoctrineAnnotationFixerTestCase::class,
AbstractNullableTypeDeclarationFixerTestCase::class,
AbstractFixerTestCase::class,
];
$currentClassName = str_replace('\PhpCsFixer', '\PhpCsFixer\Tests', $fixerName).'Test';
$baseClassName = false;
while (true) {
$baseClassName = get_parent_class($currentClassName);
if (false === $baseClassName || \in_array($baseClassName, $allowedBaseClasses, true)) {
break;
}
$currentClassName = $baseClassName;
}
if (false === $baseClassName) {
throw new \RuntimeException('Cannot find valid parent class!');
}
$baseClassName = self::getShortClassName($baseClassName);
$expectedAnnotation = \sprintf('extends %s<%s>', $baseClassName, $fixerName);
$expectedAnnotationPresent = false;
$expectedTypeImport = \sprintf('phpstan-import-type _AutogeneratedInputConfiguration from %s', $fixerName);
$expectedTypeImportPresent = false;
foreach ($doc->getAnnotationsOfType(['extends']) as $annotation) {
$annotationContent = $annotation->getContent();
Preg::match('#^.*?(?P<annotation>@extends\s+?(?P<class>\w+)\<[^>]+?\>\S*)\s*?$#s', $annotationContent, $matches);
if (
($matches['class'] ?? '') === $baseClassName
) {
if (($matches['annotation'] ?? '') !== '@'.$expectedAnnotation) {
$annotationStart = $annotation->getStart();
$annotation->remove();
$doc->getLine($annotationStart)->setContent(' * @'.$expectedAnnotation."\n");
}
$expectedAnnotationPresent = true;
break;
}
}
$implements = class_implements($fixerName);
if (isset($implements[ConfigurableFixerInterface::class])) {
foreach ($doc->getAnnotationsOfType(['phpstan-import-type']) as $annotation) {
$annotationContent = $annotation->getContent();
Preg::match('#^.*?(@'.preg_quote($expectedTypeImport, '\\').')\s*?$#s', $annotationContent, $matches);
if ([] !== $matches) {
$expectedTypeImportPresent = true;
}
}
} else {
$expectedTypeImportPresent = true;
}
if (!$expectedAnnotationPresent || !$expectedTypeImportPresent) {
$lines = $doc->getLines();
$lastLine = end($lines);
\assert(false !== $lastLine);
$lastLine->setContent(
''
.(!$expectedAnnotationPresent ? ' * @'.$expectedAnnotation."\n" : '')
.(!$expectedTypeImportPresent ? ' * @'.$expectedTypeImport."\n" : '')
.$lastLine->getContent(),
);
}
$tokens[$docBlockIndex] = new Token([\T_DOC_COMMENT, $doc->getContent()]);
}
private function applyFixForSrc(\SplFileInfo $file, Tokens $tokens): void
{
if ($file instanceof StdinFileInfo) {
$file = $this->getExampleFixerFile();
}
$fixer = $this->getFixerForSrcFile($file);
if (null === $fixer || !$fixer instanceof ConfigurableFixerInterface) {
return;
}
$optionTypeInput = [];
$optionTypeComputed = [];
$configurationDefinition = $fixer->getConfigurationDefinition();
foreach ($configurationDefinition->getOptions() as $option) {
$optionName = $option->getName();
$allowed = HelpCommand::getDisplayableAllowedValues($option);
$allowedAfterNormalization = null;
// manual handling of normalization
if (null !== $option->getNormalizer()) {
if ($fixer instanceof PhpdocOrderByValueFixer && 'annotations' === $optionName) {
$allowedAfterNormalization = 'array{'
.implode(
', ',
array_map(
static fn ($value): string => \sprintf("'%s'?: '%s'", $value, strtolower($value)),
$allowed[0]->getAllowedValues(),
),
)
.'}';
} elseif ($fixer instanceof HeaderCommentFixer && \in_array($optionName, ['header', 'validator'], true)) {
// nothing to do
} elseif ($fixer instanceof BlankLinesBeforeNamespaceFixer && \in_array($optionName, ['min_line_breaks', 'max_line_breaks'], true)) {
// nothing to do
} elseif ($fixer instanceof PhpdocReturnSelfReferenceFixer && 'replacements' === $optionName) {
// nothing to do
} elseif ($fixer instanceof GeneralPhpdocTagRenameFixer && 'replacements' === $optionName) {
// nothing to do
} elseif ($fixer instanceof NoBreakCommentFixer && 'comment_text' === $optionName) {
// nothing to do
} elseif ($fixer instanceof TrailingCommaInMultilineFixer && 'elements' === $optionName) {
// nothing to do
} elseif ($fixer instanceof OrderedAttributesFixer && 'sort_algorithm' === $optionName) {
// nothing to do
} elseif ($fixer instanceof OrderedAttributesFixer && 'order' === $optionName) {
$allowedAfterNormalization = 'array<string, int>';
} elseif ($fixer instanceof FinalInternalClassFixer && \in_array($optionName, ['annotation_include', 'annotation_exclude', 'include', 'exclude'], true)) {
$allowedAfterNormalization = 'array<string, string>';
} elseif ($fixer instanceof PhpdocTagTypeFixer && 'tags' === $optionName) {
// nothing to do
} elseif ($fixer instanceof OrderedImportsFixer && 'sort_algorithm' === $optionName) {
// nothing to do
} else {
throw new \LogicException(\sprintf('How to handle normalized types of "%s.%s"? Explicit instructions needed!', $fixer->getName(), $optionName));
}
}
if (\is_array($allowed)) {
// $allowed are allowed values
$allowed = array_map(
static fn ($value): string => $value instanceof AllowedValueSubset
? \sprintf('list<%s>', implode('|', array_map(static fn ($val) => "'".$val."'", $value->getAllowedValues())))
: Utils::toString($value),
$allowed,
);
} else {
// $allowed will be allowed types
$allowed = array_map(
static fn ($value): string => Utils::convertArrayTypeToList($value),
$option->getAllowedTypes(),
);
}
sort($allowed);
$allowed = implode('|', $allowed);
if ('array' === $allowed) {
$default = $option->getDefault();
$getTypes = static fn ($values): array => array_unique(array_map(
static fn ($val) => \gettype($val),
$values,
));
$defaultKeyTypes = $getTypes(array_keys($default));
$defaultValueTypes = $getTypes(array_values($default));
$allowed = \sprintf(
'array<%s, %s>',
[] !== $defaultKeyTypes ? implode('|', $defaultKeyTypes) : 'array-key',
[] !== $defaultValueTypes ? implode('|', $defaultValueTypes) : 'mixed',
);
}
$optionTypeInput[] = \sprintf('%s%s: %s', $optionName, $option->hasDefault() ? '?' : '', $allowed);
$optionTypeComputed[] = \sprintf('%s: %s', $optionName, $allowedAfterNormalization ?? $allowed);
}
$expectedTemplateTypeInputAnnotation = \sprintf("phpstan-type _AutogeneratedInputConfiguration array{\n * %s,\n * }", implode(",\n * ", $optionTypeInput));
$expectedTemplateTypeComputedAnnotation = \sprintf("phpstan-type _AutogeneratedComputedConfiguration array{\n * %s,\n * }", implode(",\n * ", $optionTypeComputed));
$expectedImplementsWithTypesAnnotation = 'implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>';
$classIndex = $tokens->getNextTokenOfKind(0, [[\T_CLASS]]);
$docBlockIndex = $this->getDocBlockIndex($tokens, $classIndex);
if (!$tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT)) {
$docBlockIndex = $tokens->getNextMeaningfulToken($docBlockIndex);
$tokens->insertAt($docBlockIndex, [
new Token([\T_DOC_COMMENT, "/**\n */"]),
new Token([\T_WHITESPACE, "\n"]),
]);
}
$doc = new DocBlock($tokens[$docBlockIndex]->getContent());
if (!$doc->isMultiLine()) {
throw new \RuntimeException('Non-multiline docblock not expected, please convert it manually!');
}
$templateTypeInputPresent = false;
$templateTypeComputedPresent = false;
$implementsWithTypesPresent = false;
foreach ($doc->getAnnotationsOfType(['phpstan-type']) as $annotation) {
$annotationContent = $annotation->getContent();
$matches = [];
Preg::match('#^.*?(?P<annotation>@phpstan-type\s+?(?P<typeName>.+?)\s+?(?P<typeContent>.+?))\s*?$#s', $annotationContent, $matches);
if (
($matches['typeName'] ?? '') === '_AutogeneratedInputConfiguration'
) {
if (($matches['annotation'] ?? '') !== '@'.$expectedTemplateTypeInputAnnotation) {
$annotationStart = $annotation->getStart();
$annotation->remove();
$doc->getLine($annotationStart)->setContent(' * @'.$expectedTemplateTypeInputAnnotation."\n");
}
$templateTypeInputPresent = true;
continue;
}
if (
($matches['typeName'] ?? '') === '_AutogeneratedComputedConfiguration'
) {
if (($matches['annotation'] ?? '') !== '@'.$expectedTemplateTypeComputedAnnotation) {
$annotationStart = $annotation->getStart();
$annotation->remove();
$doc->getLine($annotationStart)->setContent(' * @'.$expectedTemplateTypeComputedAnnotation."\n");
}
$templateTypeComputedPresent = true;
continue;
}
}
foreach ($doc->getAnnotationsOfType(['implements']) as $annotation) {
$annotationContent = $annotation->getContent();
Preg::match('#^.*?(?P<annotation>@implements\s+?(?P<class>\w+)\<[^>]+?\>\S*)\s*?$#s', $annotationContent, $matches);
if (
($matches['class'] ?? '') === 'ConfigurableFixerInterface'
) {
if (($matches['annotation'] ?? '') !== '@'.$expectedImplementsWithTypesAnnotation) {
$annotationStart = $annotation->getStart();
$annotation->remove();
$doc->getLine($annotationStart)->setContent(' * @'.$expectedImplementsWithTypesAnnotation."\n");
}
$implementsWithTypesPresent = true;
break;
}
}
if (!$templateTypeInputPresent || !$templateTypeComputedPresent || !$implementsWithTypesPresent) {
$lines = $doc->getLines();
$lastLine = end($lines);
\assert(false !== $lastLine);
$lastLine->setContent(
''
.(!$templateTypeInputPresent ? ' * @'.$expectedTemplateTypeInputAnnotation."\n" : '')
.(!$templateTypeComputedPresent ? ' * @'.$expectedTemplateTypeComputedAnnotation."\n" : '')
.(!$implementsWithTypesPresent ? ' * @'.$expectedImplementsWithTypesAnnotation."\n" : '')
.$lastLine->getContent(),
);
}
$tokens[$docBlockIndex] = new Token([\T_DOC_COMMENT, $doc->getContent()]);
}
private function getDocBlockIndex(Tokens $tokens, int $index): int
{
do {
$index = $tokens->getPrevNonWhitespace($index);
if ($tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) {
$index = $tokens->getPrevTokenOfKind($index, [[\T_ATTRIBUTE]]);
}
} while ($tokens[$index]->isGivenKind(self::MODIFIERS));
return $index;
}
private function getExampleFixerFile(): \SplFileInfo
{
$reflection = new \ReflectionClass(ConstantCaseFixer::class);
$fileName = $reflection->getFileName();
if (false === $fileName) {
throw new \RuntimeException('Cannot read example fileName.');
}
return new \SplFileInfo($fileName);
}
private static function getShortClassName(string $longClassName): string
{
return \array_slice(explode('\\', $longClassName), -1)[0];
}
private function isTestForFixerFile(\SplFileInfo $file): bool
{
$basename = $file->getBasename('.php');
return str_ends_with($basename, 'FixerTest')
&& !\in_array($basename, [
self::getShortClassName(AbstractFunctionReferenceFixerTest::class),
self::getShortClassName(AbstractFixerTest::class),
self::getShortClassName(AbstractProxyFixerTest::class),
], true);
}
private function getFixerForSrcFile(\SplFileInfo $file): ?FixerInterface
{
$basename = $file->getBasename('.php');
if (!str_ends_with($basename, 'Fixer')) {
return null;
}
Preg::match('#.+src/(.+)\.php#', $file->getPathname(), $matches);
if (!isset($matches[1])) {
return null;
}
$className = 'PhpCsFixer\\'.str_replace('/', '\\', $matches[1]);
$implements = class_implements($className);
if (false === $implements || !isset($implements[ConfigurableFixerInterface::class])) {
return null;
}
if (AbstractPhpdocToTypeDeclarationFixer::class === $className) {
return new class extends AbstractPhpdocToTypeDeclarationFixer {
protected function isSkippedType(string $type): bool
{
throw new \LogicException('Not implemented.');
}
protected function createTokensFromRawType(string $type): Tokens
{
throw new \LogicException('Not implemented.');
}
public function getDefinition(): FixerDefinitionInterface
{
throw new \LogicException('Not implemented.');
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
throw new \LogicException('Not implemented.');
}
public function isCandidate(Tokens $tokens): bool
{
throw new \LogicException('Not implemented.');
}
};
} elseif (AbstractDoctrineAnnotationFixer::class === $className) {
return new class extends AbstractDoctrineAnnotationFixer {
protected function isSkippedType(string $type): bool
{
throw new \LogicException('Not implemented.');
}
protected function createTokensFromRawType(string $type): Tokens
{
throw new \LogicException('Not implemented.');
}
public function getDefinition(): FixerDefinitionInterface
{
throw new \LogicException('Not implemented.');
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
throw new \LogicException('Not implemented.');
}
public function isCandidate(Tokens $tokens): bool
{
throw new \LogicException('Not implemented.');
}
public function configure(array $configuration): void
{
// void
}
protected function fixAnnotations(DoctrineAnnotationTokens $doctrineAnnotationTokens): void
{
throw new \LogicException('Not implemented.');
}
public function getConfigurationDefinition(): FixerConfigurationResolverInterface
{
return $this->createConfigurationDefinition();
}
};
}
$fixer = new $className();
\assert($fixer instanceof FixerInterface);
return $fixer;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/IndentationTypeFixer.php | src/Fixer/Whitespace/IndentationTypeFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* Fixer for rules defined in PSR2 ¶2.4.
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class IndentationTypeFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
private string $indent;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Code MUST use configured indentation type.',
[
new CodeSample("<?php\n\nif (true) {\n\techo 'Hello!';\n}\n"),
],
);
}
/**
* {@inheritdoc}
*
* Must run before PhpdocIndentFixer.
* Must run after ClassAttributesSeparationFixer.
*/
public function getPriority(): int
{
return 50;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([\T_COMMENT, \T_DOC_COMMENT, \T_WHITESPACE]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$this->indent = $this->whitespacesConfig->getIndent();
foreach ($tokens as $index => $token) {
if ($token->isComment()) {
$tokens[$index] = $this->fixIndentInComment($tokens, $index);
continue;
}
if ($token->isWhitespace()) {
$tokens[$index] = $this->fixIndentToken($tokens, $index);
continue;
}
}
}
private function fixIndentInComment(Tokens $tokens, int $index): Token
{
$content = Preg::replace('/^(?:(?<! ) {1,3})?\t/m', '\1 ', $tokens[$index]->getContent(), -1, $count);
// Also check for more tabs.
while (0 !== $count) {
$content = Preg::replace('/^(\ +)?\t/m', '\1 ', $content, -1, $count);
}
$indent = $this->indent;
// change indent to expected one
$content = Preg::replaceCallback('/^(?: )+/m', fn (array $matches): string => $this->getExpectedIndent($matches[0], $indent), $content);
return new Token([$tokens[$index]->getId(), $content]);
}
private function fixIndentToken(Tokens $tokens, int $index): Token
{
$content = $tokens[$index]->getContent();
$previousTokenHasTrailingLinebreak = false;
// @TODO this can be removed when we have a transformer for "T_OPEN_TAG" to "T_OPEN_TAG + T_WHITESPACE"
if (str_contains($tokens[$index - 1]->getContent(), "\n")) {
$content = "\n".$content;
$previousTokenHasTrailingLinebreak = true;
}
$indent = $this->indent;
$newContent = Preg::replaceCallback(
'/(\R)(\h+)/', // find indent
function (array $matches) use ($indent): string {
// normalize mixed indent
$content = Preg::replace('/(?:(?<! ) {1,3})?\t/', ' ', $matches[2]);
// change indent to expected one
return $matches[1].$this->getExpectedIndent($content, $indent);
},
$content,
);
if ($previousTokenHasTrailingLinebreak) {
$newContent = substr($newContent, 1);
}
return new Token([\T_WHITESPACE, $newContent]);
}
/**
* @return string mixed
*/
private function getExpectedIndent(string $content, string $indent): string
{
if ("\t" === $indent) {
$content = str_replace(' ', $indent, $content);
}
return $content;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/CompactNullableTypeDeclarationFixer.php | src/Fixer/Whitespace/CompactNullableTypeDeclarationFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Jack Cherng <jfcherng@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class CompactNullableTypeDeclarationFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Remove extra spaces in a nullable type declaration.',
[
new CodeSample(
"<?php\nfunction sample(? string \$str): ? string\n{}\n",
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(CT::T_NULLABLE_TYPE);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
if (!$tokens[$index]->isGivenKind(CT::T_NULLABLE_TYPE)) {
continue;
}
// remove whitespaces only if there are only whitespaces
// between '?' and the variable type
if (
$tokens[$index + 1]->isWhitespace()
&& $tokens[$index + 2]->isGivenKind([
CT::T_ARRAY_TYPEHINT,
\T_CALLABLE,
\T_NS_SEPARATOR,
\T_STATIC,
\T_STRING,
])
) {
$tokens->removeTrailingWhitespace($index);
}
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/CompactNullableTypehintFixer.php | src/Fixer/Whitespace/CompactNullableTypehintFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
/**
* @author Jack Cherng <jfcherng@gmail.com>
*
* @deprecated
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class CompactNullableTypehintFixer extends AbstractProxyFixer implements DeprecatedFixerInterface
{
private CompactNullableTypeDeclarationFixer $compactNullableTypeDeclarationFixer;
public function __construct()
{
$this->compactNullableTypeDeclarationFixer = new CompactNullableTypeDeclarationFixer();
parent::__construct();
}
public function getDefinition(): FixerDefinitionInterface
{
$fixerDefinition = $this->compactNullableTypeDeclarationFixer->getDefinition();
return new FixerDefinition(
'Remove extra spaces in a nullable typehint.',
$fixerDefinition->getCodeSamples(),
$fixerDefinition->getDescription(),
$fixerDefinition->getRiskyDescription(),
);
}
public function getSuccessorsNames(): array
{
return [
$this->compactNullableTypeDeclarationFixer->getName(),
];
}
protected function createProxyFixers(): array
{
return [
$this->compactNullableTypeDeclarationFixer,
];
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/LineEndingFixer.php | src/Fixer/Whitespace/LineEndingFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* Fixer for rules defined in PSR2 ¶2.2.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class LineEndingFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function isCandidate(Tokens $tokens): bool
{
return true;
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'All PHP files must use same line ending.',
[
new CodeSample(
"<?php \$b = \" \$a \r\n 123\"; \$a = <<<TEST\r\nAAAAA \r\n |\r\nTEST;\n",
),
],
);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$ending = $this->whitespacesConfig->getLineEnding();
for ($index = 0, $count = \count($tokens); $index < $count; ++$index) {
$token = $tokens[$index];
if ($token->isGivenKind(\T_ENCAPSED_AND_WHITESPACE)) {
if ($tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(\T_END_HEREDOC)) {
$tokens[$index] = new Token([
$token->getId(),
Preg::replace(
'#\R#',
$ending,
$token->getContent(),
),
]);
}
continue;
}
if ($token->isGivenKind([\T_CLOSE_TAG, \T_COMMENT, \T_DOC_COMMENT, \T_OPEN_TAG, \T_START_HEREDOC, \T_WHITESPACE])) {
$tokens[$index] = new Token([
$token->getId(),
Preg::replace(
'#\R#',
$ending,
$token->getContent(),
),
]);
}
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php | src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* statements?: list<'break'|'case'|'continue'|'declare'|'default'|'do'|'exit'|'for'|'foreach'|'goto'|'if'|'include'|'include_once'|'phpdoc'|'require'|'require_once'|'return'|'switch'|'throw'|'try'|'while'|'yield'|'yield_from'>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* statements: list<'break'|'case'|'continue'|'declare'|'default'|'do'|'exit'|'for'|'foreach'|'goto'|'if'|'include'|'include_once'|'phpdoc'|'require'|'require_once'|'return'|'switch'|'throw'|'try'|'while'|'yield'|'yield_from'>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
* @author Andreas Möller <am@localheinz.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class BlankLineBeforeStatementFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @var array<string, int>
*/
private const TOKEN_MAP = [
'break' => \T_BREAK,
'case' => \T_CASE,
'continue' => \T_CONTINUE,
'declare' => \T_DECLARE,
'default' => \T_DEFAULT,
'do' => \T_DO,
'exit' => \T_EXIT,
'for' => \T_FOR,
'foreach' => \T_FOREACH,
'goto' => \T_GOTO,
'if' => \T_IF,
'include' => \T_INCLUDE,
'include_once' => \T_INCLUDE_ONCE,
'phpdoc' => \T_DOC_COMMENT,
'require' => \T_REQUIRE,
'require_once' => \T_REQUIRE_ONCE,
'return' => \T_RETURN,
'switch' => \T_SWITCH,
'throw' => \T_THROW,
'try' => \T_TRY,
'while' => \T_WHILE,
'yield' => \T_YIELD,
'yield_from' => \T_YIELD_FROM,
];
/**
* @var list<int>
*/
private array $fixTokenMap = [];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'An empty line feed must precede any configured statement.',
[
new CodeSample(
<<<'PHP'
<?php
function A() {
echo 1;
return 1;
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
switch ($foo) {
case 42:
$bar->process();
break;
case 44:
break;
}
PHP,
[
'statements' => ['break'],
],
),
new CodeSample(
<<<'PHP'
<?php
foreach ($foo as $bar) {
if ($bar->isTired()) {
$bar->sleep();
continue;
}
}
PHP,
[
'statements' => ['continue'],
],
),
new CodeSample(
<<<'PHP'
<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
PHP,
[
'statements' => ['do'],
],
),
new CodeSample(
<<<'PHP'
<?php
if ($foo === false) {
exit(0);
} else {
$bar = 9000;
exit(1);
}
PHP,
[
'statements' => ['exit'],
],
),
new CodeSample(
<<<'PHP'
<?php
a:
if ($foo === false) {
goto a;
} else {
$bar = 9000;
goto b;
}
PHP,
[
'statements' => ['goto'],
],
),
new CodeSample(
<<<'PHP'
<?php
$a = 9000;
if (true) {
$foo = $bar;
}
PHP,
[
'statements' => ['if'],
],
),
new CodeSample(
<<<'PHP'
<?php
if (true) {
$foo = $bar;
return;
}
PHP,
[
'statements' => ['return'],
],
),
new CodeSample(
<<<'PHP'
<?php
$a = 9000;
switch ($a) {
case 42:
break;
}
PHP,
[
'statements' => ['switch'],
],
),
new CodeSample(
<<<'PHP'
<?php
if (null === $a) {
$foo->bar();
throw new \UnexpectedValueException("A cannot be null.");
}
PHP,
[
'statements' => ['throw'],
],
),
new CodeSample(
<<<'PHP'
<?php
$a = 9000;
try {
$foo->bar();
} catch (\Exception $exception) {
$a = -1;
}
PHP,
[
'statements' => ['try'],
],
),
new CodeSample(
<<<'PHP'
<?php
function getValues() {
yield 1;
yield 2;
// comment
yield 3;
}
PHP,
[
'statements' => ['yield'],
],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after NoExtraBlankLinesFixer, NoUselessElseFixer, NoUselessReturnFixer, ReturnAssignmentFixer, YieldFromArrayToYieldsFixer.
*/
public function getPriority(): int
{
return -21;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound($this->fixTokenMap);
}
protected function configurePostNormalisation(): void
{
$fixTokenMap = [];
foreach ($this->configuration['statements'] as $key) {
$fixTokenMap[$key] = self::TOKEN_MAP[$key];
}
$this->fixTokenMap = array_values($fixTokenMap);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$analyzer = new TokensAnalyzer($tokens);
for ($index = $tokens->count() - 1; $index > 0; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind($this->fixTokenMap)) {
continue;
}
if ($token->isGivenKind(\T_WHILE) && $analyzer->isWhilePartOfDoWhile($index)) {
continue;
}
if ($token->isGivenKind(\T_CASE) && $analyzer->isEnumCase($index)) {
continue;
}
$insertBlankLineIndex = $this->getInsertBlankLineIndex($tokens, $index);
$prevNonWhitespace = $tokens->getPrevNonWhitespace($insertBlankLineIndex);
if ($this->shouldAddBlankLine($tokens, $prevNonWhitespace)) {
$this->insertBlankLine($tokens, $insertBlankLineIndex);
}
$index = $prevNonWhitespace;
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('statements', 'List of statements which must be preceded by an empty line.'))
->setAllowedTypes(['string[]'])
->setAllowedValues([new AllowedValueSubset(array_keys(self::TOKEN_MAP))])
->setDefault([
'break',
'continue',
'declare',
'return',
'throw',
'try',
])
->getOption(),
]);
}
private function getInsertBlankLineIndex(Tokens $tokens, int $index): int
{
while ($index > 0) {
if ($tokens[$index - 1]->isWhitespace() && substr_count($tokens[$index - 1]->getContent(), "\n") > 1) {
break;
}
$prevIndex = $tokens->getPrevNonWhitespace($index);
if (!$tokens[$prevIndex]->isComment()) {
break;
}
if (!$tokens[$prevIndex - 1]->isWhitespace()) {
break;
}
if (1 !== substr_count($tokens[$prevIndex - 1]->getContent(), "\n")) {
break;
}
$index = $prevIndex;
}
return $index;
}
private function shouldAddBlankLine(Tokens $tokens, int $prevNonWhitespace): bool
{
$prevNonWhitespaceToken = $tokens[$prevNonWhitespace];
if ($prevNonWhitespaceToken->isComment()) {
for ($j = $prevNonWhitespace - 1; $j >= 0; --$j) {
if (str_contains($tokens[$j]->getContent(), "\n")) {
return false;
}
if ($tokens[$j]->isWhitespace() || $tokens[$j]->isComment()) {
continue;
}
return $tokens[$j]->equalsAny([';', '}']);
}
}
return $prevNonWhitespaceToken->equalsAny([';', '}']);
}
private function insertBlankLine(Tokens $tokens, int $index): void
{
$prevIndex = $index - 1;
$prevToken = $tokens[$prevIndex];
$lineEnding = $this->whitespacesConfig->getLineEnding();
if ($prevToken->isWhitespace()) {
$newlinesCount = substr_count($prevToken->getContent(), "\n");
if (0 === $newlinesCount) {
$tokens[$prevIndex] = new Token([\T_WHITESPACE, rtrim($prevToken->getContent(), " \t").$lineEnding.$lineEnding]);
} elseif (1 === $newlinesCount) {
$tokens[$prevIndex] = new Token([\T_WHITESPACE, $lineEnding.$prevToken->getContent()]);
}
} else {
$tokens->insertAt($index, new Token([\T_WHITESPACE, $lineEnding.$lineEnding]));
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/NoSpacesInsideParenthesisFixer.php | src/Fixer/Whitespace/NoSpacesInsideParenthesisFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Tokens;
/**
* Fixer for rules defined in PSR2 ¶4.3, ¶4.6, ¶5.
*
* @author Marc Aubé
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @deprecated in favour of SpacesInsideParenthesisFixer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoSpacesInsideParenthesisFixer extends AbstractProxyFixer implements DeprecatedFixerInterface
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There MUST NOT be a space after the opening parenthesis. There MUST NOT be a space before the closing parenthesis.',
[
new CodeSample(
<<<'PHP'
<?php
if ( $a ) {
foo( );
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
function foo( $bar, $baz )
{
}
PHP,
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before FunctionToConstantFixer, GetClassToClassKeywordFixer, StringLengthToEmptyFixer.
* Must run after CombineConsecutiveIssetsFixer, CombineNestedDirnameFixer, IncrementStyleFixer, LambdaNotUsedImportFixer, ModernizeStrposFixer, NoUselessSprintfFixer, PowToExponentiationFixer.
*/
public function getPriority(): int
{
return 3;
}
public function getSuccessorsNames(): array
{
return array_keys($this->proxyFixers);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound('(');
}
protected function createProxyFixers(): array
{
return [new SpacesInsideParenthesesFixer()];
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/SpacesInsideParenthesesFixer.php | src/Fixer/Whitespace/SpacesInsideParenthesesFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* Fixer for rules defined in PSR2 ¶4.3, ¶4.6, ¶5.
*
* @phpstan-type _AutogeneratedInputConfiguration array{
* space?: 'none'|'single',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* space: 'none'|'single',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Marc Aubé
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class SpacesInsideParenthesesFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Parentheses must be declared using the configured whitespace.',
[
new CodeSample(
<<<'PHP'
<?php
if ( $a ) {
foo( );
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
function foo( $bar, $baz )
{
}
PHP,
['space' => 'none'],
),
new CodeSample(
<<<'PHP'
<?php
if ($a) {
foo( );
}
PHP,
['space' => 'single'],
),
new CodeSample(
<<<'PHP'
<?php
function foo($bar, $baz)
{
}
PHP,
['space' => 'single'],
),
],
'By default there are not any additional spaces inside parentheses, however with `space=single` configuration option whitespace inside parentheses will be unified to single space.',
);
}
/**
* {@inheritdoc}
*
* Must run before FunctionToConstantFixer, GetClassToClassKeywordFixer, StringLengthToEmptyFixer.
* Must run after CombineConsecutiveIssetsFixer, CombineNestedDirnameFixer, IncrementStyleFixer, LambdaNotUsedImportFixer, ModernizeStrposFixer, NoUselessSprintfFixer, PowToExponentiationFixer.
*/
public function getPriority(): int
{
return 3;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound(['(', CT::T_BRACE_CLASS_INSTANTIATION_OPEN]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
if ('none' === $this->configuration['space']) {
foreach ($tokens as $index => $token) {
if (!$token->equalsAny(['(', [CT::T_BRACE_CLASS_INSTANTIATION_OPEN]])) {
continue;
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
// ignore parenthesis for T_ARRAY
if (null !== $prevIndex && $tokens[$prevIndex]->isGivenKind(\T_ARRAY)) {
continue;
}
$blockType = Tokens::detectBlockType($token);
$endIndex = $tokens->findBlockEnd($blockType['type'], $index);
// remove space after opening `(`
if (!$tokens[$tokens->getNextNonWhitespace($index)]->isComment()) {
$this->removeSpaceAroundToken($tokens, $index + 1);
}
// remove space before closing `)` if it is not `list($a, $b, )` case
if (!$tokens[$tokens->getPrevMeaningfulToken($endIndex)]->equals(',')) {
$this->removeSpaceAroundToken($tokens, $endIndex - 1);
}
}
}
if ('single' === $this->configuration['space']) {
foreach ($tokens as $index => $token) {
if (!$token->equalsAny(['(', [CT::T_BRACE_CLASS_INSTANTIATION_OPEN]])) {
continue;
}
$blockType = Tokens::detectBlockType($token);
$endParenthesisIndex = $tokens->findBlockEnd($blockType['type'], $index);
// if not other content than spaces in block remove spaces
$blockContent = $this->getBlockContent($index, $endParenthesisIndex, $tokens);
if (1 === \count($blockContent) && \in_array(' ', $blockContent, true)) {
$this->removeSpaceAroundToken($tokens, $index + 1);
continue;
}
// don't process if the next token is `)`
$nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($index);
if (')' === $tokens[$nextMeaningfulTokenIndex]->getContent()) {
continue;
}
$afterParenthesisIndex = $tokens->getNextNonWhitespace($endParenthesisIndex);
$afterParenthesisToken = $tokens[$afterParenthesisIndex];
if ($afterParenthesisToken->isGivenKind(CT::T_USE_LAMBDA)) {
$useStartParenthesisIndex = $tokens->getNextTokenOfKind($afterParenthesisIndex, ['(']);
$useEndParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $useStartParenthesisIndex);
// add single-line edge whitespaces inside use parentheses
$this->fixParenthesisInnerEdge($tokens, $useStartParenthesisIndex, $useEndParenthesisIndex);
}
// add single-line edge whitespaces inside parameters list parentheses
$this->fixParenthesisInnerEdge($tokens, $index, $endParenthesisIndex);
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('space', 'Whether to have `single` or `none` space inside parentheses.'))
->setAllowedValues(['none', 'single'])
->setDefault('none')
->getOption(),
]);
}
/**
* Remove spaces from token at a given index.
*/
private function removeSpaceAroundToken(Tokens $tokens, int $index): void
{
$token = $tokens[$index];
if ($token->isWhitespace() && !str_contains($token->getContent(), "\n")) {
$tokens->clearAt($index);
}
}
private function fixParenthesisInnerEdge(Tokens $tokens, int $start, int $end): void
{
// fix white space before ')'
if ($tokens[$end - 1]->isWhitespace()) {
$content = $tokens[$end - 1]->getContent();
if (' ' !== $content && !str_contains($content, "\n") && !$tokens[$tokens->getPrevNonWhitespace($end - 1)]->isComment()) {
$tokens[$end - 1] = new Token([\T_WHITESPACE, ' ']);
}
} else {
$tokens->insertAt($end, new Token([\T_WHITESPACE, ' ']));
}
// fix white space after '('
if ($tokens[$start + 1]->isWhitespace()) {
$content = $tokens[$start + 1]->getContent();
if (' ' !== $content && !str_contains($content, "\n") && !$tokens[$tokens->getNextNonWhitespace($start + 1)]->isComment()) {
$tokens[$start + 1] = new Token([\T_WHITESPACE, ' ']);
}
} else {
$tokens->insertAt($start + 1, new Token([\T_WHITESPACE, ' ']));
}
}
/**
* @return list<string>
*/
private function getBlockContent(int $startIndex, int $endIndex, Tokens $tokens): array
{
// + 1 for (
$contents = [];
for ($i = ($startIndex + 1); $i < $endIndex; ++$i) {
$contents[] = $tokens[$i]->getContent();
}
return $contents;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/NoWhitespaceInBlankLineFixer.php | src/Fixer/Whitespace/NoWhitespaceInBlankLineFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoWhitespaceInBlankLineFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Remove trailing whitespace at the end of blank lines.',
[new CodeSample("<?php\n \n\$a = 1;\n")],
);
}
/**
* {@inheritdoc}
*
* Must run after AssignNullCoalescingToCoalesceEqualFixer, CombineConsecutiveIssetsFixer, CombineConsecutiveUnsetsFixer, FunctionToConstantFixer, NoEmptyCommentFixer, NoEmptyStatementFixer, NoUselessElseFixer, NoUselessReturnFixer, YieldFromArrayToYieldsFixer.
*/
public function getPriority(): int
{
return -99;
}
public function isCandidate(Tokens $tokens): bool
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
// skip first as it cannot be a white space token
for ($i = 1, $count = \count($tokens); $i < $count; ++$i) {
if ($tokens[$i]->isWhitespace()) {
$this->fixWhitespaceToken($tokens, $i);
}
}
}
private function fixWhitespaceToken(Tokens $tokens, int $index): void
{
$content = $tokens[$index]->getContent();
$lines = Preg::split("/(\r\n|\n)/", $content);
$lineCount = \count($lines);
if (
// fix T_WHITESPACES with at least 3 lines (eg `\n \n`)
$lineCount > 2
// and T_WHITESPACES with at least 2 lines at the end of file or after open tag with linebreak
|| ($lineCount > 0 && (!isset($tokens[$index + 1]) || $tokens[$index - 1]->isGivenKind(\T_OPEN_TAG)))
) {
$lMax = isset($tokens[$index + 1]) ? $lineCount - 1 : $lineCount;
$lStart = 1;
if ($tokens[$index - 1]->isGivenKind(\T_OPEN_TAG) && "\n" === substr($tokens[$index - 1]->getContent(), -1)) {
$lStart = 0;
}
for ($l = $lStart; $l < $lMax; ++$l) {
$lines[$l] = Preg::replace('/^\h+$/', '', $lines[$l]);
}
$content = implode($this->whitespacesConfig->getLineEnding(), $lines);
$tokens->ensureWhitespaceAtIndex($index, 0, $content);
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/TypeDeclarationSpacesFixer.php | src/Fixer/Whitespace/TypeDeclarationSpacesFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Future;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* elements?: list<'constant'|'function'|'property'>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* elements: list<'constant'|'function'|'property'>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
* @author John Paul E. Balandan, CPA <paulbalandan@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class TypeDeclarationSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private const PROPERTY_MODIFIERS = [\T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC, \T_VAR, \T_FINAL, FCT::T_READONLY, FCT::T_PUBLIC_SET, FCT::T_PROTECTED_SET, FCT::T_PRIVATE_SET];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Ensure single space between a variable and its type declaration in function arguments and properties.',
[
new CodeSample(
<<<'PHP'
<?php
class Bar
{
private string $a;
private bool $b;
public function __invoke(array $c) {}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
class Foo
{
public int $bar;
public function baz(string $a)
{
return fn(bool $c): string => (string) $c;
}
}
PHP,
['elements' => ['function']],
),
new CodeSample(
<<<'PHP'
<?php
class Foo
{
public int $bar;
public function baz(string $a) {}
}
PHP,
['elements' => ['property']],
),
new VersionSpecificCodeSample(
<<<'PHP'
<?php
class Foo
{
public const string BAR = "";
}
PHP,
new VersionSpecification(8_03_00),
['elements' => ['constant']],
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([...Token::getClassyTokenKinds(), \T_FN, \T_FUNCTION]);
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('elements', 'Structural elements where the spacing after the type declaration should be fixed.'))
->setAllowedTypes(['string[]'])
->setAllowedValues([new AllowedValueSubset(['function', 'property', 'constant'])])
->setDefault(
Future::getV4OrV3(['function', 'property', 'constant'], ['function', 'property']),
)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$functionsAnalyzer = new FunctionsAnalyzer();
foreach (array_reverse($this->getElements($tokens), true) as $index => $type) {
if ('property' === $type && \in_array('property', $this->configuration['elements'], true)) {
$this->ensureSingleSpaceAtPropertyTypehint($tokens, $index);
continue;
}
if ('method' === $type && \in_array('function', $this->configuration['elements'], true)) {
$this->ensureSingleSpaceAtFunctionArgumentTypehint($functionsAnalyzer, $tokens, $index);
continue;
}
if ('const' === $type && \in_array('constant', $this->configuration['elements'], true)) {
$this->ensureSingleSpaceAtConstantTypehint($tokens, $index);
// implicit continue;
}
}
}
/**
* @return array<int, string>
*
* @phpstan-return array<int, 'method'|'property'|'const'>
*/
private function getElements(Tokens $tokens): array
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
$elements = array_map(
static fn (array $element): string => $element['type'],
array_filter(
$tokensAnalyzer->getClassyElements(),
static fn (array $element): bool => \in_array($element['type'], ['method', 'property', 'const'], true),
),
);
foreach ($tokens as $index => $token) {
if (
$token->isGivenKind(\T_FN)
|| ($token->isGivenKind(\T_FUNCTION) && !isset($elements[$index]))
) {
$elements[$index] = 'method';
}
}
return $elements;
}
private function ensureSingleSpaceAtFunctionArgumentTypehint(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index): void
{
foreach (array_reverse($functionsAnalyzer->getFunctionArguments($tokens, $index)) as $argumentInfo) {
$argumentType = $argumentInfo->getTypeAnalysis();
if (null === $argumentType) {
continue;
}
$tokens->ensureWhitespaceAtIndex($argumentType->getEndIndex() + 1, 0, ' ');
}
}
private function ensureSingleSpaceAtPropertyTypehint(Tokens $tokens, int $index): void
{
$propertyIndex = $index;
do {
$index = $tokens->getPrevMeaningfulToken($index);
} while (!$tokens[$index]->isGivenKind(self::PROPERTY_MODIFIERS));
$propertyType = $this->collectTypeAnalysis($tokens, $index, $propertyIndex);
if (null === $propertyType) {
return;
}
$tokens->ensureWhitespaceAtIndex($propertyType->getEndIndex() + 1, 0, ' ');
}
private function ensureSingleSpaceAtConstantTypehint(Tokens $tokens, int $index): void
{
$constIndex = $index;
$equalsIndex = $tokens->getNextTokenOfKind($constIndex, ['=']);
if (null === $equalsIndex) {
return;
}
$nameIndex = $tokens->getPrevMeaningfulToken($equalsIndex);
if (!$tokens[$nameIndex]->isGivenKind(\T_STRING)) {
return;
}
$typeEndIndex = $tokens->getPrevMeaningfulToken($nameIndex);
if (null === $typeEndIndex || $tokens[$typeEndIndex]->isGivenKind(\T_CONST)) {
return;
}
$tokens->ensureWhitespaceAtIndex($typeEndIndex + 1, 0, ' ');
}
private function collectTypeAnalysis(Tokens $tokens, int $startIndex, int $endIndex): ?TypeAnalysis
{
$type = '';
$typeStartIndex = $tokens->getNextMeaningfulToken($startIndex);
$typeEndIndex = $typeStartIndex;
for ($i = $typeStartIndex; $i < $endIndex; ++$i) {
if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) {
continue;
}
$type .= $tokens[$i]->getContent();
$typeEndIndex = $i;
}
return '' !== $type ? new TypeAnalysis($type, $typeStartIndex, $typeEndIndex) : null;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/NoTrailingWhitespaceFixer.php | src/Fixer/Whitespace/NoTrailingWhitespaceFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* Fixer for rules defined in PSR2 ¶2.3.
*
* Don't add trailing spaces at the end of non-blank lines.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoTrailingWhitespaceFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There must be no trailing whitespace at the end of non-blank lines.',
[new CodeSample("<?php\n\$a = 1; \n")],
);
}
/**
* {@inheritdoc}
*
* Must run after CombineConsecutiveIssetsFixer, CombineConsecutiveUnsetsFixer, EmptyLoopBodyFixer, EmptyLoopConditionFixer, FunctionToConstantFixer, ModernizeStrposFixer, NoEmptyCommentFixer, NoEmptyPhpdocFixer, NoEmptyStatementFixer, NoUnneededControlParenthesesFixer, NoUselessElseFixer, StringLengthToEmptyFixer, TernaryToElvisOperatorFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = \count($tokens) - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if (
$token->isGivenKind(\T_OPEN_TAG)
&& $tokens->offsetExists($index + 1)
&& $tokens[$index + 1]->isWhitespace()
&& Preg::match('/(.*)\h$/', $token->getContent(), $openTagMatches)
&& Preg::match('/^(\R)(.*)$/s', $tokens[$index + 1]->getContent(), $whitespaceMatches)
) {
$tokens[$index] = new Token([\T_OPEN_TAG, $openTagMatches[1].$whitespaceMatches[1]]);
$tokens->ensureWhitespaceAtIndex($index + 1, 0, $whitespaceMatches[2]);
continue;
}
if (!$token->isWhitespace()) {
continue;
}
$lines = Preg::split('/(\R+)/', $token->getContent(), -1, \PREG_SPLIT_DELIM_CAPTURE);
$linesSize = \count($lines);
// fix only multiline whitespaces or singleline whitespaces at the end of file
if ($linesSize > 1 || !isset($tokens[$index + 1])) {
if (!$tokens[$index - 1]->isGivenKind(\T_OPEN_TAG) || !Preg::match('/(.*)\R$/', $tokens[$index - 1]->getContent())) {
$lines[0] = rtrim($lines[0], " \t");
}
for ($i = 1; $i < $linesSize; ++$i) {
$trimmedLine = rtrim($lines[$i], " \t");
if ('' !== $trimmedLine) {
$lines[$i] = $trimmedLine;
}
}
$content = implode('', $lines);
if ('' !== $content) {
$tokens[$index] = new Token([$token->getId(), $content]);
} else {
$tokens->clearAt($index);
}
}
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/NoExtraBlankLinesFixer.php | src/Fixer/Whitespace/NoExtraBlankLinesFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Future;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\SwitchAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* tokens?: list<'attribute'|'break'|'case'|'comma'|'continue'|'curly_brace_block'|'default'|'extra'|'parenthesis_brace_block'|'return'|'square_brace_block'|'switch'|'throw'|'use'|'use_trait'>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* tokens: list<'attribute'|'break'|'case'|'comma'|'continue'|'curly_brace_block'|'default'|'extra'|'parenthesis_brace_block'|'return'|'square_brace_block'|'switch'|'throw'|'use'|'use_trait'>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoExtraBlankLinesFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @var non-empty-list<string>
*/
private const AVAILABLE_TOKENS = [
'attribute',
'break',
'case',
'comma',
'continue',
'curly_brace_block',
'default',
'extra',
'parenthesis_brace_block',
'return',
'square_brace_block',
'switch',
'throw',
'use',
'use_trait',
];
/**
* @var array<int, callable(int): void> key is token id
*/
private array $tokenKindCallbackMap;
/**
* @var array<string, callable(int): void> key is token's content
*/
private array $tokenEqualsMap;
private Tokens $tokens;
private TokensAnalyzer $tokensAnalyzer;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Removes extra blank lines and/or blank lines following configuration.',
[
new CodeSample(
<<<'PHP'
<?php
$foo = array("foo");
$bar = "bar";
PHP,
),
new CodeSample(
<<<'PHP'
<?php
switch ($foo) {
case 41:
echo "foo";
break;
case 42:
break;
}
PHP,
['tokens' => ['break']],
),
new CodeSample(
<<<'PHP'
<?php
for ($i = 0; $i < 9000; ++$i) {
if (true) {
continue;
}
}
PHP,
['tokens' => ['continue']],
),
new CodeSample(
<<<'PHP'
<?php
for ($i = 0; $i < 9000; ++$i) {
echo $i;
}
PHP,
['tokens' => ['curly_brace_block']],
),
new CodeSample(
<<<'PHP'
<?php
$foo = array("foo");
$bar = "bar";
PHP,
['tokens' => ['extra']],
),
new CodeSample(
<<<'PHP'
<?php
$foo = array(
"foo"
);
PHP,
['tokens' => ['parenthesis_brace_block']],
),
new CodeSample(
<<<'PHP'
<?php
function foo($bar)
{
return $bar;
}
PHP,
['tokens' => ['return']],
),
new CodeSample(
<<<'PHP'
<?php
$foo = [
"foo"
];
PHP,
['tokens' => ['square_brace_block']],
),
new CodeSample(
<<<'PHP'
<?php
function foo($bar)
{
throw new \Exception("Hello!");
}
PHP,
['tokens' => ['throw']],
),
new CodeSample(
<<<'PHP'
<?php
namespace Foo;
use Bar\Baz;
use Baz\Bar;
class Bar
{
}
PHP,
['tokens' => ['use']],
),
new CodeSample(
<<<'PHP'
<?php
switch($a) {
case 1:
default:
echo 3;
}
PHP,
['tokens' => ['switch', 'case', 'default']],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before BlankLineBeforeStatementFixer.
* Must run after ClassAttributesSeparationFixer, CombineConsecutiveUnsetsFixer, EmptyLoopBodyFixer, EmptyLoopConditionFixer, FunctionToConstantFixer, LongToShorthandOperatorFixer, ModernizeStrposFixer, NoEmptyCommentFixer, NoEmptyPhpdocFixer, NoEmptyStatementFixer, NoUnusedImportsFixer, NoUselessElseFixer, NoUselessPrintfFixer, NoUselessReturnFixer, NoUselessSprintfFixer, PhpdocReadonlyClassCommentToKeywordFixer, StringLengthToEmptyFixer, YieldFromArrayToYieldsFixer.
*/
public function getPriority(): int
{
return -20;
}
public function isCandidate(Tokens $tokens): bool
{
return true;
}
/**
* @param _AutogeneratedInputConfiguration $configuration
*/
protected function configurePreNormalisation(array $configuration): void
{
if (isset($configuration['tokens']) && \in_array('use_trait', $configuration['tokens'], true)) {
Future::triggerDeprecation(new \RuntimeException('Option "tokens: use_trait" used in `no_extra_blank_lines` rule is deprecated, use the rule `class_attributes_separation` with `elements: trait_import` instead.'));
}
}
protected function configurePostNormalisation(): void
{
$tokensConfiguration = $this->configuration['tokens'];
$this->tokenEqualsMap = [];
if (\in_array('comma', $tokensConfiguration, true)) {
$this->tokenEqualsMap[','] = [$this, 'fixAfterToken'];
}
if (\in_array('curly_brace_block', $tokensConfiguration, true)) {
$this->tokenEqualsMap['{'] = [$this, 'fixStructureOpenCloseIfMultiLine']; // i.e. not: CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN
}
if (\in_array('parenthesis_brace_block', $tokensConfiguration, true)) {
$this->tokenEqualsMap['('] = [$this, 'fixStructureOpenCloseIfMultiLine']; // i.e. not: CT::T_BRACE_CLASS_INSTANTIATION_OPEN
}
// Each item requires explicit array-like callable, otherwise PHPStan will complain about unused private methods.
$configMap = [
'attribute' => [CT::T_ATTRIBUTE_CLOSE, [$this, 'fixAfterToken']],
'break' => [\T_BREAK, [$this, 'fixAfterToken']],
'case' => [\T_CASE, [$this, 'fixAfterCaseToken']],
'continue' => [\T_CONTINUE, [$this, 'fixAfterToken']],
'default' => [\T_DEFAULT, [$this, 'fixAfterToken']],
'extra' => [\T_WHITESPACE, [$this, 'removeMultipleBlankLines']],
'return' => [\T_RETURN, [$this, 'fixAfterToken']],
'square_brace_block' => [CT::T_ARRAY_SQUARE_BRACE_OPEN, [$this, 'fixStructureOpenCloseIfMultiLine']],
'switch' => [\T_SWITCH, [$this, 'fixAfterToken']],
'throw' => [\T_THROW, [$this, 'fixAfterThrowToken']],
'use' => [\T_USE, [$this, 'removeBetweenUse']],
'use_trait' => [CT::T_USE_TRAIT, [$this, 'removeBetweenUse']],
];
$this->tokenKindCallbackMap = [];
foreach ($tokensConfiguration as $config) {
if (isset($configMap[$config])) {
$this->tokenKindCallbackMap[$configMap[$config][0]] = $configMap[$config][1];
}
}
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$this->tokens = $tokens;
$this->tokensAnalyzer = new TokensAnalyzer($this->tokens);
for ($index = $tokens->getSize() - 1; $index > 0; --$index) {
$this->fixByToken($tokens[$index], $index);
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('tokens', 'List of tokens to fix.'))
->setAllowedTypes(['string[]'])
->setAllowedValues([new AllowedValueSubset(self::AVAILABLE_TOKENS)])
->setDefault(['extra'])
->getOption(),
]);
}
/**
* @uses fixAfterToken()
* @uses fixAfterCaseToken()
* @uses fixAfterThrowToken()
* @uses fixStructureOpenCloseIfMultiLine()
* @uses removeBetweenUse()
* @uses removeMultipleBlankLines()
*/
private function fixByToken(Token $token, int $index): void
{
foreach ($this->tokenKindCallbackMap as $kind => $callback) {
if (!$token->isGivenKind($kind)) {
continue;
}
\call_user_func_array($this->tokenKindCallbackMap[$token->getId()], [$index]);
return;
}
foreach ($this->tokenEqualsMap as $equals => $callback) {
if (!$token->equals($equals)) {
continue;
}
\call_user_func_array($this->tokenEqualsMap[$token->getContent()], [$index]);
return;
}
}
private function removeBetweenUse(int $index): void
{
$next = $this->tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]);
if (null === $next || $this->tokens[$next]->isGivenKind(\T_CLOSE_TAG)) {
return;
}
$nextUseCandidate = $this->tokens->getNextMeaningfulToken($next);
if (null === $nextUseCandidate || !$this->tokens[$nextUseCandidate]->isGivenKind($this->tokens[$index]->getId()) || !$this->containsLinebreak($index, $nextUseCandidate)) {
return;
}
$this->removeEmptyLinesAfterLineWithTokenAt($next);
}
private function removeMultipleBlankLines(int $index): void
{
$expected = $this->tokens[$index - 1]->isGivenKind(\T_OPEN_TAG) && Preg::match('/\R$/', $this->tokens[$index - 1]->getContent()) ? 1 : 2;
$parts = Preg::split('/(.*\R)/', $this->tokens[$index]->getContent(), -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY);
$count = \count($parts);
if ($count > $expected) {
$this->tokens[$index] = new Token([\T_WHITESPACE, implode('', \array_slice($parts, 0, $expected)).rtrim($parts[$count - 1], "\r\n")]);
}
}
private function fixAfterToken(int $index): void
{
for ($i = $index - 1; $i > 0; --$i) {
if ($this->tokens[$i]->isGivenKind(\T_FUNCTION) && $this->tokensAnalyzer->isLambda($i)) {
return;
}
if ($this->tokens[$i]->isGivenKind(\T_CLASS) && $this->tokensAnalyzer->isAnonymousClass($i)) {
return;
}
if ($this->tokens[$i]->isGivenKind([CT::T_ARRAY_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN])) {
return;
}
if ($this->tokens[$i]->isWhitespace() && str_contains($this->tokens[$i]->getContent(), "\n")) {
break;
}
}
$this->removeEmptyLinesAfterLineWithTokenAt($index);
}
private function fixAfterCaseToken(int $index): void
{
$enumSwitchIndex = $this->tokens->getPrevTokenOfKind($index, [[\T_SWITCH], [FCT::T_ENUM]]);
if (!$this->tokens[$enumSwitchIndex]->isGivenKind(\T_SWITCH)) {
return;
}
$this->removeEmptyLinesAfterLineWithTokenAt($index);
}
private function fixAfterThrowToken(int $index): void
{
$prevIndex = $this->tokens->getPrevMeaningfulToken($index);
if (!$this->tokens[$prevIndex]->equalsAny([';', '{', '}', ':', [\T_OPEN_TAG]])) {
return;
}
if ($this->tokens[$prevIndex]->equals(':') && !SwitchAnalyzer::belongsToSwitch($this->tokens, $prevIndex)) {
return;
}
$this->fixAfterToken($index);
}
/**
* Remove white line(s) after the index of a block type,
* but only if the block is not on one line.
*
* @param int $index body start
*/
private function fixStructureOpenCloseIfMultiLine(int $index): void
{
$blockTypeInfo = Tokens::detectBlockType($this->tokens[$index]);
$bodyEnd = $this->tokens->findBlockEnd($blockTypeInfo['type'], $index);
for ($i = $bodyEnd - 1; $i >= $index; --$i) {
if (str_contains($this->tokens[$i]->getContent(), "\n")) {
$this->removeEmptyLinesAfterLineWithTokenAt($i);
$this->removeEmptyLinesAfterLineWithTokenAt($index);
break;
}
}
}
private function removeEmptyLinesAfterLineWithTokenAt(int $index): void
{
// find the line break
$parenthesesDepth = 0;
$tokenCount = \count($this->tokens);
for ($end = $index; $end < $tokenCount; ++$end) {
if ($this->tokens[$end]->equals('(')) {
++$parenthesesDepth;
continue;
}
if ($this->tokens[$end]->equals(')')) {
--$parenthesesDepth;
if ($parenthesesDepth < 0) {
return;
}
continue;
}
if (
$this->tokens[$end]->equals('}')
|| str_contains($this->tokens[$end]->getContent(), "\n")
) {
break;
}
}
if ($end === $tokenCount) {
return; // not found, early return
}
$ending = $this->whitespacesConfig->getLineEnding();
for ($i = $end; $i < $tokenCount && $this->tokens[$i]->isWhitespace(); ++$i) {
$content = $this->tokens[$i]->getContent();
if (substr_count($content, "\n") < 1) {
continue;
}
$newContent = Preg::replace('/^.*\R(\h*)$/s', $ending.'$1', $content);
$this->tokens[$i] = new Token([\T_WHITESPACE, $newContent]);
}
}
private function containsLinebreak(int $startIndex, int $endIndex): bool
{
for ($i = $endIndex; $i > $startIndex; --$i) {
if (Preg::match('/\R/', $this->tokens[$i]->getContent())) {
return true;
}
}
return false;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/MethodChainingIndentationFixer.php | src/Fixer/Whitespace/MethodChainingIndentationFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Vladimir Boliev <voff.web@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class MethodChainingIndentationFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Method chaining MUST be properly indented. Method chaining with different levels of indentation is not supported.',
[new CodeSample("<?php\n\$user->setEmail('voff.web@gmail.com')\n ->setPassword('233434');\n")],
);
}
/**
* {@inheritdoc}
*
* Must run after NoSpaceAroundDoubleColonFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound(Token::getObjectOperatorKinds());
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$lineEnding = $this->whitespacesConfig->getLineEnding();
for ($index = 1, $count = \count($tokens); $index < $count; ++$index) {
if (!$tokens[$index]->isObjectOperator()) {
continue;
}
$endParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(', ';', ',', [\T_CLOSE_TAG]]);
$previousEndParenthesisIndex = $tokens->getPrevTokenOfKind($index, [')']);
if (
null === $endParenthesisIndex
|| !$tokens[$endParenthesisIndex]->equals('(') && null === $previousEndParenthesisIndex
) {
continue;
}
if ($this->canBeMovedToNextLine($index, $tokens)) {
$newline = new Token([\T_WHITESPACE, $lineEnding]);
if ($tokens[$index - 1]->isWhitespace()) {
$tokens[$index - 1] = $newline;
} else {
$tokens->insertAt($index, $newline);
++$index;
++$endParenthesisIndex;
}
}
$currentIndent = $this->getIndentAt($tokens, $index - 1);
if (null === $currentIndent) {
continue;
}
$expectedIndent = $this->getExpectedIndentAt($tokens, $index);
if ($currentIndent !== $expectedIndent) {
$tokens[$index - 1] = new Token([\T_WHITESPACE, $lineEnding.$expectedIndent]);
}
if (!$tokens[$endParenthesisIndex]->equals('(')) {
continue;
}
$endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $endParenthesisIndex);
for ($searchIndex = $index + 1; $searchIndex < $endParenthesisIndex; ++$searchIndex) {
$searchToken = $tokens[$searchIndex];
if (!$searchToken->isWhitespace()) {
continue;
}
$content = $searchToken->getContent();
if (!Preg::match('/\R/', $content)) {
continue;
}
$content = Preg::replace(
'/(\R)'.$currentIndent.'(\h*)$/D',
'$1'.$expectedIndent.'$2',
$content,
);
$tokens[$searchIndex] = new Token([$searchToken->getId(), $content]);
}
}
}
/**
* @param int $index index of the first token on the line to indent
*/
private function getExpectedIndentAt(Tokens $tokens, int $index): string
{
$index = $tokens->getPrevMeaningfulToken($index);
$indent = $this->whitespacesConfig->getIndent();
for ($i = $index; $i >= 0; --$i) {
if ($tokens[$i]->equals(')')) {
$i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $i);
}
$currentIndent = $this->getIndentAt($tokens, $i);
if (null === $currentIndent) {
continue;
}
if ($this->currentLineRequiresExtraIndentLevel($tokens, $i, $index)) {
return $currentIndent.$indent;
}
return $currentIndent;
}
return $indent;
}
/**
* @param int $index position of the object operator token ("->" or "?->")
*/
private function canBeMovedToNextLine(int $index, Tokens $tokens): bool
{
$prevMeaningful = $tokens->getPrevMeaningfulToken($index);
$hasCommentBefore = false;
for ($i = $index - 1; $i > $prevMeaningful; --$i) {
if ($tokens[$i]->isComment()) {
$hasCommentBefore = true;
continue;
}
if ($tokens[$i]->isWhitespace() && Preg::match('/\R/', $tokens[$i]->getContent())) {
return $hasCommentBefore;
}
}
return false;
}
/**
* @param int $index index of the indentation token
*/
private function getIndentAt(Tokens $tokens, int $index): ?string
{
if (Preg::match('/\R{1}(\h*)$/', $this->getIndentContentAt($tokens, $index), $matches)) {
return $matches[1];
}
return null;
}
private function getIndentContentAt(Tokens $tokens, int $index): string
{
if (!$tokens[$index]->isGivenKind([\T_WHITESPACE, \T_INLINE_HTML])) {
return '';
}
$content = $tokens[$index]->getContent();
if ($tokens[$index]->isWhitespace() && $tokens[$index - 1]->isGivenKind(\T_OPEN_TAG)) {
$content = $tokens[$index - 1]->getContent().$content;
}
if (Preg::match('/\R/', $content)) {
return $content;
}
return '';
}
/**
* @param int $start index of first meaningful token on previous line
* @param int $end index of last token on previous line
*/
private function currentLineRequiresExtraIndentLevel(Tokens $tokens, int $start, int $end): bool
{
$firstMeaningful = $tokens->getNextMeaningfulToken($start);
if ($tokens[$firstMeaningful]->isObjectOperator()) {
$thirdMeaningful = $tokens->getNextMeaningfulToken($tokens->getNextMeaningfulToken($firstMeaningful));
return
$tokens[$thirdMeaningful]->equals('(')
&& $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $thirdMeaningful) > $end;
}
return
!$tokens[$end]->equals(')')
|| $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $end) >= $start;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/HeredocIndentationFixer.php | src/Fixer/Whitespace/HeredocIndentationFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* indentation?: 'same_as_start'|'start_plus_one',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* indentation: 'same_as_start'|'start_plus_one',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Gregor Harlan
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class HeredocIndentationFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Heredoc/nowdoc content must be properly indented.',
[
new CodeSample(
<<<'SAMPLE'
<?php
$heredoc = <<<EOD
abc
def
EOD;
$nowdoc = <<<'EOD'
abc
def
EOD;
SAMPLE,
),
new CodeSample(
<<<'SAMPLE'
<?php
$nowdoc = <<<'EOD'
abc
def
EOD;
SAMPLE,
['indentation' => 'same_as_start'],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after BracesFixer, MultilineStringToHeredocFixer, StatementIndentationFixer.
*/
public function getPriority(): int
{
return -26;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_START_HEREDOC);
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('indentation', 'Whether the indentation should be the same as in the start token line or one level more.'))
->setAllowedValues(['start_plus_one', 'same_as_start'])
->setDefault('start_plus_one')
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = \count($tokens) - 1; 0 <= $index; --$index) {
if (!$tokens[$index]->isGivenKind(\T_END_HEREDOC)) {
continue;
}
$end = $index;
$index = $tokens->getPrevTokenOfKind($index, [[\T_START_HEREDOC]]);
$this->fixIndentation($tokens, $index, $end);
}
}
private function fixIndentation(Tokens $tokens, int $start, int $end): void
{
$indent = WhitespacesAnalyzer::detectIndent($tokens, $start);
if ('start_plus_one' === $this->configuration['indentation']) {
$indent .= $this->whitespacesConfig->getIndent();
}
Preg::match('/^\h*/', $tokens[$end]->getContent(), $matches);
$currentIndent = $matches[0];
$currentIndentLength = \strlen($currentIndent);
$content = $indent.substr($tokens[$end]->getContent(), $currentIndentLength);
$tokens[$end] = new Token([\T_END_HEREDOC, $content]);
if ($end === $start + 1) {
return;
}
$index = $end - 1;
for ($last = true; $index > $start; --$index, $last = false) {
if (!$tokens[$index]->isGivenKind([\T_ENCAPSED_AND_WHITESPACE, \T_WHITESPACE])) {
continue;
}
$content = $tokens[$index]->getContent();
if ('' !== $currentIndent) {
$content = Preg::replace('/(?<=\v)(?!'.$currentIndent.')\h+/', '', $content);
}
$regexEnd = $last && '' === $currentIndent ? '(?!\v|$)' : '(?!\v)';
$content = Preg::replace('/(?<=\v)'.$currentIndent.$regexEnd.'/', $indent, $content);
$tokens[$index] = new Token([$tokens[$index]->getId(), $content]);
}
++$index;
if (!$tokens[$index]->isGivenKind(\T_ENCAPSED_AND_WHITESPACE)) {
$tokens->insertAt($index, new Token([\T_ENCAPSED_AND_WHITESPACE, $indent]));
return;
}
$content = $tokens[$index]->getContent();
if (!\in_array($content[0], ["\r", "\n"], true) && ('' === $currentIndent || str_starts_with($content, $currentIndent))) {
$content = $indent.substr($content, $currentIndentLength);
} elseif ('' !== $currentIndent) {
$content = Preg::replace('/^(?!'.$currentIndent.')\h+/', '', $content);
}
$tokens[$index] = new Token([\T_ENCAPSED_AND_WHITESPACE, $content]);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/StatementIndentationFixer.php | src/Fixer/Whitespace/StatementIndentationFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\IndentationTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* stick_comment_to_next_continuous_control_statement?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* stick_comment_to_next_continuous_control_statement: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class StatementIndentationFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
use IndentationTrait;
private const BLOCK_SIGNATURE_FIRST_TOKENS = [
\T_USE,
\T_IF,
\T_ELSE,
\T_ELSEIF,
\T_FOR,
\T_FOREACH,
\T_WHILE,
\T_DO,
\T_SWITCH,
\T_CASE,
\T_DEFAULT,
\T_TRY,
\T_CLASS,
\T_INTERFACE,
\T_TRAIT,
\T_EXTENDS,
\T_IMPLEMENTS,
\T_CONST,
FCT::T_MATCH,
];
private const CONTROL_STRUCTURE_POSSIBIBLY_WITHOUT_BRACES_TOKENS = [
\T_IF,
\T_ELSE,
\T_ELSEIF,
\T_FOR,
\T_FOREACH,
\T_WHILE,
\T_DO,
];
private const BLOCK_FIRST_TOKENS = ['{', [CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN], [CT::T_USE_TRAIT], [CT::T_GROUP_IMPORT_BRACE_OPEN], [CT::T_PROPERTY_HOOK_BRACE_OPEN], [FCT::T_ATTRIBUTE]];
private const PROPERTY_KEYWORDS = [\T_VAR, \T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_STATIC, FCT::T_READONLY];
private AlternativeSyntaxAnalyzer $alternativeSyntaxAnalyzer;
private bool $bracesFixerCompatibility;
public function __construct(bool $bracesFixerCompatibility = false)
{
parent::__construct();
$this->bracesFixerCompatibility = $bracesFixerCompatibility;
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Each statement must be indented.',
[
new CodeSample(
<<<'PHP'
<?php
if ($baz == true) {
echo "foo";
}
else {
echo "bar";
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
// foo
if ($foo) {
echo "foo";
// this is treated as comment of `if` block, as `stick_comment_to_next_continuous_control_statement` is disabled
} else {
$aaa = 1;
}
PHP,
['stick_comment_to_next_continuous_control_statement' => false],
),
new CodeSample(
<<<'PHP'
<?php
// foo
if ($foo) {
echo "foo";
// this is treated as comment of `elseif(1)` block, as `stick_comment_to_next_continuous_control_statement` is enabled
} elseif(1) {
echo "bar";
} elseif(2) {
// this is treated as comment of `elseif(2)` block, as the only content of that block
} elseif(3) {
$aaa = 1;
// this is treated as comment of `elseif(3)` block, as it is a comment in the final block
}
PHP,
['stick_comment_to_next_continuous_control_statement' => true],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before HeredocIndentationFixer.
* Must run after BracesPositionFixer, ClassAttributesSeparationFixer, CurlyBracesPositionFixer, FullyQualifiedStrictTypesFixer, GlobalNamespaceImportFixer, MethodArgumentSpaceFixer, NoUselessElseFixer, YieldFromArrayToYieldsFixer.
*/
public function getPriority(): int
{
return -3;
}
public function isCandidate(Tokens $tokens): bool
{
return true;
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('stick_comment_to_next_continuous_control_statement', 'Last comment of code block counts as comment for next block.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$this->alternativeSyntaxAnalyzer = new AlternativeSyntaxAnalyzer();
$endIndex = \count($tokens) - 1;
if ($tokens[$endIndex]->isWhitespace()) {
--$endIndex;
}
$lastIndent = $this->getLineIndentationWithBracesCompatibility(
$tokens,
0,
$this->extractIndent($this->computeNewLineContent($tokens, 0)),
);
/**
* @var list<array{
* type: 'block'|'block_signature'|'statement',
* skip: bool,
* end_index: int,
* end_index_inclusive: bool,
* initial_indent: string,
* new_indent?: string,
* is_indented_block: bool,
* }> $scopes
*/
$scopes = [
[
'type' => 'block',
'skip' => false,
'end_index' => $endIndex,
'end_index_inclusive' => true,
'initial_indent' => $lastIndent,
'is_indented_block' => false,
],
];
$previousLineInitialIndent = '';
$previousLineNewIndent = '';
$noBracesBlockStarts = [];
$alternativeBlockStarts = [];
$caseBlockStarts = [];
foreach ($tokens as $index => $token) {
$currentScope = \count($scopes) - 1;
if (isset($noBracesBlockStarts[$index])) {
$scopes[] = [
'type' => 'block',
'skip' => false,
'end_index' => $this->findStatementEndIndex($tokens, $index, \count($tokens) - 1) + 1,
'end_index_inclusive' => true,
'initial_indent' => $this->getLineIndentationWithBracesCompatibility($tokens, $index, $lastIndent),
'is_indented_block' => true,
];
++$currentScope;
}
if (
$token->equalsAny(self::BLOCK_FIRST_TOKENS)
|| ($token->equals('(') && !$tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(\T_ARRAY))
|| isset($alternativeBlockStarts[$index])
|| isset($caseBlockStarts[$index])
) {
$endIndexInclusive = true;
if ($token->isGivenKind([\T_EXTENDS, \T_IMPLEMENTS])) {
$endIndex = $tokens->getNextTokenOfKind($index, ['{']);
} elseif ($token->isGivenKind(CT::T_USE_TRAIT)) {
$endIndex = $tokens->getNextTokenOfKind($index, [';']);
} elseif ($token->equals(':')) {
if (isset($caseBlockStarts[$index])) {
[$endIndex, $endIndexInclusive] = $this->findCaseBlockEnd($tokens, $index);
} elseif ($this->alternativeSyntaxAnalyzer->belongsToAlternativeSyntax($tokens, $index)) {
$endIndex = $this->alternativeSyntaxAnalyzer->findAlternativeSyntaxBlockEnd($tokens, $alternativeBlockStarts[$index]);
}
} elseif ($token->isGivenKind(CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN)) {
$endIndex = $tokens->getNextTokenOfKind($index, [[CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE]]);
} elseif ($token->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) {
$endIndex = $tokens->getNextTokenOfKind($index, [[CT::T_GROUP_IMPORT_BRACE_CLOSE]]);
} elseif ($token->equals('{')) {
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
} elseif ($token->equals('(')) {
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
} elseif ($token->isGivenKind(CT::T_PROPERTY_HOOK_BRACE_OPEN)) {
$endIndex = $tokens->getNextTokenOfKind($index, [[CT::T_PROPERTY_HOOK_BRACE_CLOSE]]);
} else {
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index);
}
if ('block_signature' === $scopes[$currentScope]['type']) {
$initialIndent = $scopes[$currentScope]['initial_indent'];
} else {
$initialIndent = $this->getLineIndentationWithBracesCompatibility($tokens, $index, $lastIndent);
}
$skip = false;
if ($this->bracesFixerCompatibility) {
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if (null !== $prevIndex) {
$prevIndex = $tokens->getPrevMeaningfulToken($prevIndex);
}
if (null !== $prevIndex && $tokens[$prevIndex]->isGivenKind([\T_FUNCTION, \T_FN])) {
$skip = true;
}
}
$scopes[] = [
'type' => 'block',
'skip' => $skip,
'end_index' => $endIndex,
'end_index_inclusive' => $endIndexInclusive,
'initial_indent' => $initialIndent,
'is_indented_block' => true,
];
++$currentScope;
while ($index >= $scopes[$currentScope]['end_index']) {
array_pop($scopes);
--$currentScope;
}
continue;
}
if (
$token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)
|| ($token->equals('(') && $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(\T_ARRAY))
) {
$blockType = $token->equals('(') ? Tokens::BLOCK_TYPE_PARENTHESIS_BRACE : Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE;
$scopes[] = [
'type' => 'statement',
'skip' => true,
'end_index' => $tokens->findBlockEnd($blockType, $index),
'end_index_inclusive' => true,
'initial_indent' => $previousLineInitialIndent,
'new_indent' => $previousLineNewIndent,
'is_indented_block' => false,
];
continue;
}
$isPropertyStart = $this->isPropertyStart($tokens, $index);
if ($isPropertyStart || $token->isGivenKind(self::BLOCK_SIGNATURE_FIRST_TOKENS)) {
$lastWhitespaceIndex = null;
$closingParenthesisIndex = null;
for ($endIndex = $index + 1, $max = \count($tokens); $endIndex < $max; ++$endIndex) {
$endToken = $tokens[$endIndex];
if ($endToken->equals('(')) {
$closingParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $endIndex);
$endIndex = $closingParenthesisIndex;
continue;
}
if ($endToken->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) {
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $endIndex);
continue;
}
if ($endToken->equalsAny(['{', ';', [\T_DOUBLE_ARROW], [\T_IMPLEMENTS]])) {
break;
}
if ($endToken->equals(':')) {
if ($token->isGivenKind([\T_CASE, \T_DEFAULT])) {
$caseBlockStarts[$endIndex] = $index;
} else {
$alternativeBlockStarts[$endIndex] = $index;
}
break;
}
if (!$token->isGivenKind(self::CONTROL_STRUCTURE_POSSIBIBLY_WITHOUT_BRACES_TOKENS)) {
continue;
}
if ($endToken->isWhitespace()) {
$lastWhitespaceIndex = $endIndex;
continue;
}
if (!$endToken->isComment()) {
$noBraceBlockStartIndex = $lastWhitespaceIndex ?? $endIndex;
$noBracesBlockStarts[$noBraceBlockStartIndex] = true;
$endIndex = $closingParenthesisIndex ?? $index;
break;
}
}
$scopes[] = [
'type' => 'block_signature',
'skip' => false,
'end_index' => $endIndex,
'end_index_inclusive' => true,
'initial_indent' => $this->getLineIndentationWithBracesCompatibility($tokens, $index, $lastIndent),
'is_indented_block' => $isPropertyStart || $token->isGivenKind([\T_EXTENDS, \T_IMPLEMENTS, \T_CONST]),
];
continue;
}
if ($token->isGivenKind(\T_FUNCTION)) {
$endIndex = $index + 1;
for ($max = \count($tokens); $endIndex < $max; ++$endIndex) {
if ($tokens[$endIndex]->equals('(')) {
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $endIndex);
continue;
}
if ($tokens[$endIndex]->equalsAny(['{', ';'])) {
break;
}
}
$scopes[] = [
'type' => 'block_signature',
'skip' => false,
'end_index' => $endIndex,
'end_index_inclusive' => true,
'initial_indent' => $this->getLineIndentationWithBracesCompatibility($tokens, $index, $lastIndent),
'is_indented_block' => false,
];
continue;
}
if (
$token->isWhitespace()
|| ($index > 0 && $tokens[$index - 1]->isGivenKind(\T_OPEN_TAG))
) {
$previousOpenTagContent = $tokens[$index - 1]->isGivenKind(\T_OPEN_TAG)
? Preg::replace('/\S/', '', $tokens[$index - 1]->getContent())
: '';
$content = $previousOpenTagContent.($token->isWhitespace() ? $token->getContent() : '');
if (!Preg::match('/\R/', $content)) {
continue;
}
$nextToken = $tokens[$index + 1] ?? null;
if (
$this->bracesFixerCompatibility
&& null !== $nextToken
&& $nextToken->isComment()
&& !$this->isCommentWithFixableIndentation($tokens, $index + 1)
) {
continue;
}
if ('block' === $scopes[$currentScope]['type'] || 'block_signature' === $scopes[$currentScope]['type']) {
$indent = false;
if ($scopes[$currentScope]['is_indented_block']) {
$firstNonWhitespaceTokenIndex = null;
$nextNewlineIndex = null;
for ($searchIndex = $index + 1, $max = \count($tokens); $searchIndex < $max; ++$searchIndex) {
$searchToken = $tokens[$searchIndex];
if (!$searchToken->isWhitespace()) {
if (null === $firstNonWhitespaceTokenIndex) {
$firstNonWhitespaceTokenIndex = $searchIndex;
}
continue;
}
if (Preg::match('/\R/', $searchToken->getContent())) {
$nextNewlineIndex = $searchIndex;
break;
}
}
$endIndex = $scopes[$currentScope]['end_index'];
if (!$scopes[$currentScope]['end_index_inclusive']) {
++$endIndex;
}
if (
(null !== $firstNonWhitespaceTokenIndex && $firstNonWhitespaceTokenIndex < $endIndex)
|| (null !== $nextNewlineIndex && $nextNewlineIndex < $endIndex)
) {
if (
// do we touch whitespace directly before comment...
$tokens[$firstNonWhitespaceTokenIndex]->isGivenKind(\T_COMMENT)
// ...and afterwards, there is only comment or `}`
&& $tokens[$tokens->getNextMeaningfulToken($firstNonWhitespaceTokenIndex)]->equals('}')
) {
if (
// ... and the comment was only content in docblock
$tokens[$tokens->getPrevMeaningfulToken($firstNonWhitespaceTokenIndex)]->equals('{')
) {
$indent = true;
} else {
// or it was dedicated comment for next control loop
// ^^ we need to check if there is a control group afterwards, and in that case don't make extra indent level
$nextIndex = $tokens->getNextMeaningfulToken($firstNonWhitespaceTokenIndex);
$nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex);
if (null !== $nextNextIndex && $tokens[$nextNextIndex]->isGivenKind([\T_ELSE, \T_ELSEIF])) {
$indent = true !== $this->configuration['stick_comment_to_next_continuous_control_statement'];
} else {
$indent = true;
}
}
} else {
$indent = true;
}
}
}
$previousLineInitialIndent = $this->extractIndent($content);
if ($scopes[$currentScope]['skip']) {
$whitespaces = $previousLineInitialIndent;
} else {
$whitespaces = $scopes[$currentScope]['initial_indent'].($indent ? $this->whitespacesConfig->getIndent() : '');
}
$content = Preg::replace(
'/(\R+)\h*$/',
'$1'.$whitespaces,
$content,
);
$previousLineNewIndent = $this->extractIndent($content);
} else {
$content = Preg::replace(
'/(\R)'.$scopes[$currentScope]['initial_indent'].'(\h*)$/D',
'$1'.$scopes[$currentScope]['new_indent'].'$2',
$content,
);
}
$lastIndent = $this->extractIndent($content);
if ('' !== $previousOpenTagContent) {
$content = Preg::replace("/^{$previousOpenTagContent}/", '', $content);
}
if ('' !== $content) {
$tokens->ensureWhitespaceAtIndex($index, 0, $content);
} elseif ($token->isWhitespace()) {
$tokens->clearAt($index);
}
if (null !== $nextToken && $nextToken->isComment()) {
$tokens[$index + 1] = new Token([
$nextToken->getId(),
Preg::replace(
'/(\R)'.preg_quote($previousLineInitialIndent, '/').'(\h*\S+.*)/',
'$1'.$previousLineNewIndent.'$2',
$nextToken->getContent(),
),
]);
}
if ($token->isWhitespace()) {
continue;
}
}
if ($this->isNewLineToken($tokens, $index)) {
$lastIndent = $this->extractIndent($this->computeNewLineContent($tokens, $index));
}
while ($index >= $scopes[$currentScope]['end_index']) {
array_pop($scopes);
if ([] === $scopes) {
return;
}
--$currentScope;
}
if ($token->isComment() || $token->equalsAny([';', ',', '}', [\T_OPEN_TAG], [\T_CLOSE_TAG], [CT::T_ATTRIBUTE_CLOSE]])) {
continue;
}
if ('statement' !== $scopes[$currentScope]['type'] && 'block_signature' !== $scopes[$currentScope]['type']) {
$endIndex = $this->findStatementEndIndex($tokens, $index, $scopes[$currentScope]['end_index']);
if ($endIndex === $index) {
continue;
}
$scopes[] = [
'type' => 'statement',
'skip' => false,
'end_index' => $endIndex,
'end_index_inclusive' => false,
'initial_indent' => $previousLineInitialIndent,
'new_indent' => $previousLineNewIndent,
'is_indented_block' => true,
];
}
}
}
private function findStatementEndIndex(Tokens $tokens, int $index, int $parentScopeEndIndex): int
{
$endIndex = null;
$ifLevel = 0;
$doWhileLevel = 0;
for ($searchEndIndex = $index; $searchEndIndex <= $parentScopeEndIndex; ++$searchEndIndex) {
$searchEndToken = $tokens[$searchEndIndex];
if (
$searchEndToken->isGivenKind(\T_IF)
&& !$tokens[$tokens->getPrevMeaningfulToken($searchEndIndex)]->isGivenKind(\T_ELSE)
) {
++$ifLevel;
continue;
}
if ($searchEndToken->isGivenKind(\T_DO)) {
++$doWhileLevel;
continue;
}
if ($searchEndToken->equalsAny(['(', '{', [CT::T_ARRAY_SQUARE_BRACE_OPEN]])) {
if ($searchEndToken->equals('(')) {
$blockType = Tokens::BLOCK_TYPE_PARENTHESIS_BRACE;
} elseif ($searchEndToken->equals('{')) {
$blockType = Tokens::BLOCK_TYPE_CURLY_BRACE;
} else {
$blockType = Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE;
}
$searchEndIndex = $tokens->findBlockEnd($blockType, $searchEndIndex);
$searchEndToken = $tokens[$searchEndIndex];
}
if (!$searchEndToken->equalsAny([';', ',', '}', [\T_CLOSE_TAG]])) {
continue;
}
$controlStructureContinuationIndex = $tokens->getNextMeaningfulToken($searchEndIndex);
if (
$ifLevel > 0
&& null !== $controlStructureContinuationIndex
&& $tokens[$controlStructureContinuationIndex]->isGivenKind([\T_ELSE, \T_ELSEIF])
) {
if (
$tokens[$controlStructureContinuationIndex]->isGivenKind(\T_ELSE)
&& !$tokens[$tokens->getNextMeaningfulToken($controlStructureContinuationIndex)]->isGivenKind(\T_IF)
) {
--$ifLevel;
}
$searchEndIndex = $controlStructureContinuationIndex;
continue;
}
if (
$doWhileLevel > 0
&& null !== $controlStructureContinuationIndex
&& $tokens[$controlStructureContinuationIndex]->isGivenKind(\T_WHILE)
) {
--$doWhileLevel;
$searchEndIndex = $controlStructureContinuationIndex;
continue;
}
$endIndex = $tokens->getPrevNonWhitespace($searchEndIndex);
break;
}
return $endIndex ?? $tokens->getPrevMeaningfulToken($parentScopeEndIndex);
}
/**
* @return array{int, bool}
*/
private function findCaseBlockEnd(Tokens $tokens, int $index): array
{
for ($max = \count($tokens); $index < $max; ++$index) {
if ($tokens[$index]->isGivenKind(\T_SWITCH)) {
$braceIndex = $tokens->getNextMeaningfulToken(
$tokens->findBlockEnd(
Tokens::BLOCK_TYPE_PARENTHESIS_BRACE,
$tokens->getNextMeaningfulToken($index),
),
);
if ($tokens[$braceIndex]->equals(':')) {
$index = $this->alternativeSyntaxAnalyzer->findAlternativeSyntaxBlockEnd($tokens, $index);
} else {
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $braceIndex);
}
continue;
}
if ($tokens[$index]->equals('{')) {
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
continue;
}
if ($tokens[$index]->isGivenKind([\T_CASE, \T_DEFAULT])) {
return [$index, true];
}
if ($tokens[$index]->equalsAny(['}', [\T_ENDSWITCH]])) {
return [$tokens->getPrevNonWhitespace($index), false];
}
}
throw new \LogicException('End of case block not found.');
}
private function getLineIndentationWithBracesCompatibility(Tokens $tokens, int $index, string $regularIndent): string
{
if (
$this->bracesFixerCompatibility
&& $tokens[$index]->isGivenKind(\T_OPEN_TAG)
&& Preg::match('/\R/', $tokens[$index]->getContent())
&& isset($tokens[$index + 1])
&& $tokens[$index + 1]->isWhitespace()
&& Preg::match('/\h+$/D', $tokens[$index + 1]->getContent())
) {
return Preg::replace('/.*?(\h+)$/sD', '$1', $tokens[$index + 1]->getContent());
}
return $regularIndent;
}
/**
* Returns whether the token at given index is the last token in a property
* declaration before the type or the name of that property.
*/
private function isPropertyStart(Tokens $tokens, int $index): bool
{
$nextIndex = $tokens->getNextMeaningfulToken($index);
if (
null === $nextIndex
|| $tokens[$nextIndex]->isGivenKind(self::PROPERTY_KEYWORDS)
|| $tokens[$nextIndex]->isGivenKind([\T_CONST, \T_FUNCTION])
) {
return false;
}
while ($tokens[$index]->isGivenKind(self::PROPERTY_KEYWORDS)) {
if ($tokens[$index]->isGivenKind([\T_VAR, \T_PUBLIC, \T_PROTECTED, \T_PRIVATE])) {
return true;
}
$index = $tokens->getPrevMeaningfulToken($index);
}
return false;
}
/**
* Returns whether the token at given index is a comment whose indentation
* can be fixed.
*
* Indentation of a comment is not changed when the comment is part of a
* multi-line message whose lines are all single-line comments and at least
* one line has meaningful content.
*/
private function isCommentWithFixableIndentation(Tokens $tokens, int $index): bool
{
if (!$tokens[$index]->isComment()) {
return false;
}
if (str_starts_with($tokens[$index]->getContent(), '/*')) {
return true;
}
$indent = preg_quote($this->whitespacesConfig->getIndent(), '~');
if (Preg::match("~^(//|#)({$indent}.*)?$~", $tokens[$index]->getContent())) {
return false;
}
$firstCommentIndex = $index;
while (true) {
$firstCommentCandidateIndex = $this->getSiblingContinuousSingleLineComment($tokens, $firstCommentIndex, false);
if (null === $firstCommentCandidateIndex) {
break;
}
$firstCommentIndex = $firstCommentCandidateIndex;
}
$lastCommentIndex = $index;
while (true) {
$lastCommentCandidateIndex = $this->getSiblingContinuousSingleLineComment($tokens, $lastCommentIndex, true);
if (null === $lastCommentCandidateIndex) {
break;
}
$lastCommentIndex = $lastCommentCandidateIndex;
}
if ($firstCommentIndex === $lastCommentIndex) {
return true;
}
for ($i = $firstCommentIndex + 1; $i < $lastCommentIndex; ++$i) {
if (!$tokens[$i]->isWhitespace() && !$tokens[$i]->isComment()) {
return false;
}
}
return true;
}
private function getSiblingContinuousSingleLineComment(Tokens $tokens, int $index, bool $after): ?int
{
$siblingIndex = $index;
do {
if ($after) {
$siblingIndex = $tokens->getNextTokenOfKind($siblingIndex, [[\T_COMMENT]]);
} else {
$siblingIndex = $tokens->getPrevTokenOfKind($siblingIndex, [[\T_COMMENT]]);
}
if (null === $siblingIndex) {
return null;
}
} while (str_starts_with($tokens[$siblingIndex]->getContent(), '/*'));
$newLines = 0;
for ($i = min($siblingIndex, $index) + 1, $max = max($siblingIndex, $index); $i < $max; ++$i) {
if ($tokens[$i]->isWhitespace() && Preg::match('/\R/', $tokens[$i]->getContent())) {
if (1 === $newLines || Preg::match('/\R.*\R/', $tokens[$i]->getContent())) {
return null;
}
++$newLines;
}
}
return $siblingIndex;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/ArrayIndentationFixer.php | src/Fixer/Whitespace/ArrayIndentationFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\IndentationTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ArrayIndentationFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
use IndentationTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Each element of an array must be indented exactly once.',
[
new CodeSample("<?php\n\$foo = [\n 'bar' => [\n 'baz' => true,\n ],\n];\n"),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([\T_ARRAY, \T_LIST, CT::T_ARRAY_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN]);
}
/**
* {@inheritdoc}
*
* Must run before AlignMultilineCommentFixer, BinaryOperatorSpacesFixer.
* Must run after MethodArgumentSpaceFixer.
*/
public function getPriority(): int
{
return 29;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$lastIndent = '';
$scopes = [];
$previousLineInitialIndent = '';
$previousLineNewIndent = '';
foreach ($tokens as $index => $token) {
$currentScope = [] !== $scopes ? \count($scopes) - 1 : null;
if ($token->isComment()) {
continue;
}
if (
$token->isGivenKind([CT::T_ARRAY_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN])
|| ($token->equals('(') && $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind([\T_ARRAY, \T_LIST]))
) {
$blockType = Tokens::detectBlockType($token);
$endIndex = $tokens->findBlockEnd($blockType['type'], $index);
$scopes[] = [
'type' => 'array',
'end_index' => $endIndex,
'initial_indent' => $lastIndent,
];
continue;
}
if ($this->isNewLineToken($tokens, $index)) {
$lastIndent = $this->extractIndent($this->computeNewLineContent($tokens, $index));
}
if (null === $currentScope) {
continue;
}
if ($token->isWhitespace()) {
if (!Preg::match('/\R/', $token->getContent())) {
continue;
}
if ('array' === $scopes[$currentScope]['type']) {
$indent = false;
for ($searchEndIndex = $index + 1; $searchEndIndex < $scopes[$currentScope]['end_index']; ++$searchEndIndex) {
$searchEndToken = $tokens[$searchEndIndex];
if (
(!$searchEndToken->isWhitespace() && !$searchEndToken->isComment())
|| ($searchEndToken->isWhitespace() && Preg::match('/\R/', $searchEndToken->getContent()))
) {
$indent = true;
break;
}
}
$content = Preg::replace(
'/(\R+)\h*$/',
'$1'.$scopes[$currentScope]['initial_indent'].($indent ? $this->whitespacesConfig->getIndent() : ''),
$token->getContent(),
);
$previousLineInitialIndent = $this->extractIndent($token->getContent());
$previousLineNewIndent = $this->extractIndent($content);
} else {
$content = Preg::replace(
'/(\R)'.preg_quote($scopes[$currentScope]['initial_indent'], '/').'(\h*)$/',
'$1'.$scopes[$currentScope]['new_indent'].'$2',
$token->getContent(),
);
}
$tokens[$index] = new Token([\T_WHITESPACE, $content]);
$lastIndent = $this->extractIndent($content);
continue;
}
if ($index === $scopes[$currentScope]['end_index']) {
while ([] !== $scopes && $index === $scopes[$currentScope]['end_index']) {
array_pop($scopes);
--$currentScope;
}
continue;
}
if ($token->equals(',')) {
continue;
}
if ('expression' !== $scopes[$currentScope]['type']) {
$endIndex = $this->findExpressionEndIndex($tokens, $index, $scopes[$currentScope]['end_index']);
if ($endIndex === $index) {
continue;
}
$scopes[] = [
'type' => 'expression',
'end_index' => $endIndex,
'initial_indent' => $previousLineInitialIndent,
'new_indent' => $previousLineNewIndent,
];
}
}
}
private function findExpressionEndIndex(Tokens $tokens, int $index, int $parentScopeEndIndex): int
{
$endIndex = null;
for ($searchEndIndex = $index + 1; $searchEndIndex < $parentScopeEndIndex; ++$searchEndIndex) {
$searchEndToken = $tokens[$searchEndIndex];
if ($searchEndToken->equalsAny(['(', '{'])
|| $searchEndToken->isGivenKind([CT::T_ARRAY_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN])
) {
$type = Tokens::detectBlockType($searchEndToken);
$searchEndIndex = $tokens->findBlockEnd(
$type['type'],
$searchEndIndex,
);
continue;
}
if ($searchEndToken->equals(',')) {
$endIndex = $tokens->getPrevMeaningfulToken($searchEndIndex);
break;
}
}
return $endIndex ?? $tokens->getPrevMeaningfulToken($parentScopeEndIndex);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/BlankLineBetweenImportGroupsFixer.php | src/Fixer/Whitespace/BlankLineBetweenImportGroupsFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @author Sander Verkuil <s.verkuil@pm.me>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class BlankLineBetweenImportGroupsFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
private const IMPORT_TYPE_CLASS = 'class';
private const IMPORT_TYPE_CONST = 'const';
private const IMPORT_TYPE_FUNCTION = 'function';
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Putting blank lines between `use` statement groups.',
[
new CodeSample(
<<<'PHP'
<?php
use function AAC;
use const AAB;
use AAA;
PHP,
),
new CodeSample(
<<<'PHP'
<?php
use const AAAA;
use const BBB;
use Bar;
use AAC;
use Acme;
use function CCC\AA;
use function DDD;
PHP,
),
new CodeSample(
<<<'PHP'
<?php
use const BBB;
use const AAAA;
use Acme;
use AAC;
use Bar;
use function DDD;
use function CCC\AA;
PHP,
),
new CodeSample(
<<<'PHP'
<?php
use const AAAA;
use const BBB;
use Acme;
use function DDD;
use AAC;
use function CCC\AA;
use Bar;
PHP,
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after OrderedImportsFixer.
*/
public function getPriority(): int
{
return -40;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_USE);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
$namespacesImports = $tokensAnalyzer->getImportUseIndexes(true);
foreach (array_reverse($namespacesImports) as $uses) {
$this->walkOverUses($tokens, $uses);
}
}
/**
* @param list<int> $uses
*/
private function walkOverUses(Tokens $tokens, array $uses): void
{
$usesCount = \count($uses);
if ($usesCount < 2) {
return; // nothing to fix
}
$previousType = null;
for ($i = $usesCount - 1; $i >= 0; --$i) {
$index = $uses[$i];
$startIndex = $tokens->getNextMeaningfulToken($index + 1);
$endIndex = $tokens->getNextTokenOfKind($startIndex, [';', [\T_CLOSE_TAG]]);
if ($tokens[$startIndex]->isGivenKind(CT::T_CONST_IMPORT)) {
$type = self::IMPORT_TYPE_CONST;
} elseif ($tokens[$startIndex]->isGivenKind(CT::T_FUNCTION_IMPORT)) {
$type = self::IMPORT_TYPE_FUNCTION;
} else {
$type = self::IMPORT_TYPE_CLASS;
}
if (null !== $previousType && $type !== $previousType) {
$this->ensureLine($tokens, $endIndex + 1);
}
$previousType = $type;
}
}
private function ensureLine(Tokens $tokens, int $index): void
{
static $lineEnding;
if (null === $lineEnding) {
$lineEnding = $this->whitespacesConfig->getLineEnding();
$lineEnding .= $lineEnding;
}
$index = $this->getInsertIndex($tokens, $index);
$indent = WhitespacesAnalyzer::detectIndent($tokens, $index);
$tokens->ensureWhitespaceAtIndex($index, 1, $lineEnding.$indent);
}
private function getInsertIndex(Tokens $tokens, int $index): int
{
$tokensCount = \count($tokens);
for (; $index < $tokensCount - 1; ++$index) {
if (!$tokens[$index]->isWhitespace() && !$tokens[$index]->isComment()) {
return $index - 1;
}
$content = $tokens[$index]->getContent();
if (str_contains($content, "\n")) {
return $index;
}
}
return $index;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/SingleBlankLineAtEofFixer.php | src/Fixer/Whitespace/SingleBlankLineAtEofFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Tokens;
/**
* A file must always end with a line endings character.
*
* Fixer for rules defined in PSR2 ¶2.2.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class SingleBlankLineAtEofFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'A PHP file without end tag must always end with a single empty line feed.',
[
new CodeSample("<?php\n\$a = 1;"),
new CodeSample("<?php\n\$a = 1;\n\n"),
],
);
}
public function getPriority(): int
{
// must run last to be sure the file is properly formatted before it runs
return -100;
}
public function isCandidate(Tokens $tokens): bool
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$count = $tokens->count();
if ($count > 0 && !$tokens[$count - 1]->isGivenKind([\T_INLINE_HTML, \T_CLOSE_TAG, \T_OPEN_TAG])) {
$tokens->ensureWhitespaceAtIndex($count - 1, 1, $this->whitespacesConfig->getLineEnding());
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/NoSpacesAroundOffsetFixer.php | src/Fixer/Whitespace/NoSpacesAroundOffsetFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* positions?: list<'inside'|'outside'>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* positions: list<'inside'|'outside'>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Javier Spagnoletti <phansys@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoSpacesAroundOffsetFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There MUST NOT be spaces around offset braces.',
[
new CodeSample("<?php\n\$sample = \$b [ 'a' ] [ 'b' ];\n"),
new CodeSample("<?php\n\$sample = \$b [ 'a' ] [ 'b' ];\n", ['positions' => ['inside']]),
new CodeSample("<?php\n\$sample = \$b [ 'a' ] [ 'b' ];\n", ['positions' => ['outside']]),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound(['[', CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if (!$token->equalsAny(['[', [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN]])) {
continue;
}
if (\in_array('inside', $this->configuration['positions'], true)) {
if ($token->equals('[')) {
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index);
} else {
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE, $index);
}
// remove space after opening `[` or `{`
if ($tokens[$index + 1]->isWhitespace(" \t")) {
$tokens->clearAt($index + 1);
}
// remove space before closing `]` or `}`
if ($tokens[$endIndex - 1]->isWhitespace(" \t")) {
$tokens->clearAt($endIndex - 1);
}
}
if (\in_array('outside', $this->configuration['positions'], true)) {
$prevNonWhitespaceIndex = $tokens->getPrevNonWhitespace($index);
if ($tokens[$prevNonWhitespaceIndex]->isComment()) {
continue;
}
$tokens->removeLeadingWhitespace($index);
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
$values = ['inside', 'outside'];
return new FixerConfigurationResolver([
(new FixerOptionBuilder('positions', 'Whether spacing should be fixed inside and/or outside the offset braces.'))
->setAllowedTypes(['string[]'])
->setAllowedValues([new AllowedValueSubset($values)])
->setDefault($values)
->getOption(),
]);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Whitespace/TypesSpacesFixer.php | src/Fixer/Whitespace/TypesSpacesFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Whitespace;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* space?: 'none'|'single',
* space_multiple_catch?: 'none'|'single'|null,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* space: 'none'|'single',
* space_multiple_catch: 'none'|'single'|null,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class TypesSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'A single space or none should be around union type and intersection type operators.',
[
new CodeSample(
"<?php\ntry\n{\n new Foo();\n} catch (ErrorA | ErrorB \$e) {\necho'error';}\n",
),
new CodeSample(
"<?php\ntry\n{\n new Foo();\n} catch (ErrorA|ErrorB \$e) {\necho'error';}\n",
['space' => 'single'],
),
new VersionSpecificCodeSample(
"<?php\nfunction foo(int | string \$x)\n{\n}\n",
new VersionSpecification(8_00_00),
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after NullableTypeDeclarationFixer, OrderedTypesFixer.
*/
public function getPriority(): int
{
return -1;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION]);
}
protected function configurePostNormalisation(): void
{
if (!isset($this->configuration['space_multiple_catch'])) {
$this->configuration = [
'space' => $this->configuration['space'],
'space_multiple_catch' => $this->configuration['space'],
];
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('space', 'Spacing to apply around union type and intersection type operators.'))
->setAllowedValues(['none', 'single'])
->setDefault('none')
->getOption(),
(new FixerOptionBuilder('space_multiple_catch', 'Spacing to apply around type operator when catching exceptions of multiple types, use `null` to follow the value configured for `space`.'))
->setAllowedValues(['none', 'single', null])
->setDefault(null)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$tokenCount = $tokens->count() - 1;
for ($index = 0; $index < $tokenCount; ++$index) {
if ($tokens[$index]->isGivenKind([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION])) {
$tokenCount += $this->fixSpacing($tokens, $index, 'single' === $this->configuration['space']);
continue;
}
if ($tokens[$index]->isGivenKind(\T_CATCH)) {
while (true) {
$index = $tokens->getNextTokenOfKind($index, [')', [CT::T_TYPE_ALTERNATION]]);
if ($tokens[$index]->equals(')')) {
break;
}
$tokenCount += $this->fixSpacing($tokens, $index, 'single' === $this->configuration['space_multiple_catch']);
}
// implicit continue
}
}
}
private function fixSpacing(Tokens $tokens, int $index, bool $singleSpace): int
{
if (!$singleSpace) {
$this->ensureNoSpace($tokens, $index + 1);
$this->ensureNoSpace($tokens, $index - 1);
return 0;
}
$addedTokenCount = 0;
$addedTokenCount += $this->ensureSingleSpace($tokens, $index + 1, 0);
$addedTokenCount += $this->ensureSingleSpace($tokens, $index - 1, 1);
return $addedTokenCount;
}
private function ensureSingleSpace(Tokens $tokens, int $index, int $offset): int
{
if (!$tokens[$index]->isWhitespace()) {
$tokens->insertSlices([$index + $offset => new Token([\T_WHITESPACE, ' '])]);
return 1;
}
if (' ' !== $tokens[$index]->getContent() && !Preg::match('/\R/', $tokens[$index]->getContent())) {
$tokens[$index] = new Token([\T_WHITESPACE, ' ']);
}
return 0;
}
private function ensureNoSpace(Tokens $tokens, int $index): void
{
if ($tokens[$index]->isWhitespace() && !Preg::match('/\R/', $tokens[$index]->getContent())) {
$tokens->clearAt($index);
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ListNotation/ListSyntaxFixer.php | src/Fixer/ListNotation/ListSyntaxFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ListNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* syntax?: 'long'|'short',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* syntax: 'long'|'short',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ListSyntaxFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private ?int $candidateTokenKind = null;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'List (`array` destructuring) assignment should be declared using the configured syntax.',
[
new CodeSample(
"<?php\nlist(\$sample) = \$array;\n",
),
new CodeSample(
"<?php\n[\$sample] = \$array;\n",
['syntax' => 'long'],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before BinaryOperatorSpacesFixer, TernaryOperatorSpacesFixer.
*/
public function getPriority(): int
{
return 2;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound($this->candidateTokenKind);
}
protected function configurePostNormalisation(): void
{
$this->candidateTokenKind = 'long' === $this->configuration['syntax'] ? CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN : \T_LIST;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
if ($tokens[$index]->isGivenKind($this->candidateTokenKind)) {
if (\T_LIST === $this->candidateTokenKind) {
$this->fixToShortSyntax($tokens, $index);
} else {
$this->fixToLongSyntax($tokens, $index);
}
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('syntax', 'Whether to use the `long` or `short` syntax for array destructuring.'))
->setAllowedValues(['long', 'short'])
->setDefault('short')
->getOption(),
]);
}
private function fixToLongSyntax(Tokens $tokens, int $index): void
{
$closeIndex = $tokens->getNextTokenOfKind($index, [
[CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE],
'[', // [CT::T_ARRAY_SQUARE_BRACE_OPEN],
]);
if (!$tokens[$closeIndex]->isGivenKind(CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE)) {
return;
}
$tokens[$index] = new Token('(');
$tokens[$closeIndex] = new Token(')');
$tokens->insertAt($index, new Token([\T_LIST, 'list']));
}
private function fixToShortSyntax(Tokens $tokens, int $index): void
{
$openIndex = $tokens->getNextTokenOfKind($index, ['(']);
$closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex);
$tokens[$openIndex] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, '[']);
$tokens[$closeIndex] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, ']']);
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.php | src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* private_methods?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* private_methods: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Filippo Tessarotto <zoeslam@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoUnneededFinalMethodFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Removes `final` from methods where possible.',
[
new CodeSample(
<<<'PHP'
<?php
final class Foo
{
final public function foo1() {}
final protected function bar() {}
final private function baz() {}
}
class Bar
{
final private function bar1() {}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
final class Foo
{
final private function baz() {}
}
class Bar
{
final private function bar1() {}
}
PHP,
['private_methods' => false],
),
],
null,
'Risky when child class overrides a `private` method.',
);
}
public function isCandidate(Tokens $tokens): bool
{
if (!$tokens->isAllTokenKindsFound([\T_FINAL, \T_FUNCTION])) {
return false;
}
return $tokens->isAnyTokenKindsFound([\T_CLASS, FCT::T_ENUM]);
}
public function isRisky(): bool
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($this->getMethods($tokens) as $element) {
$index = $element['method_final_index'];
if ($element['method_of_enum'] || $element['class_is_final']) {
$this->clearFinal($tokens, $index);
continue;
}
if (!$element['method_is_private'] || false === $this->configuration['private_methods'] || $element['method_is_constructor']) {
continue;
}
$this->clearFinal($tokens, $index);
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('private_methods', 'Private methods of non-`final` classes must not be declared `final`.'))
->setAllowedTypes(['bool'])
->setDefault(true)
->getOption(),
]);
}
/**
* @return \Generator<array{
* classIndex: int,
* token: Token,
* type: string,
* class_is_final?: bool,
* method_final_index: null|int,
* method_is_constructor?: bool,
* method_is_private: bool,
* method_of_enum: bool
* }>
*/
private function getMethods(Tokens $tokens): \Generator
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
$modifierKinds = [\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_FINAL, \T_ABSTRACT, \T_STATIC];
$enums = [];
$classesAreFinal = [];
foreach ($tokensAnalyzer->getClassyElements() as $index => $element) {
if ('method' !== $element['type']) {
continue; // not a method
}
$classIndex = $element['classIndex'];
if (!\array_key_exists($classIndex, $enums)) {
$enums[$classIndex] = $tokens[$classIndex]->isGivenKind(FCT::T_ENUM);
}
$element['method_final_index'] = null;
$element['method_is_private'] = false;
$previous = $index;
do {
$previous = $tokens->getPrevMeaningfulToken($previous);
if ($tokens[$previous]->isGivenKind(\T_PRIVATE)) {
$element['method_is_private'] = true;
} elseif ($tokens[$previous]->isGivenKind(\T_FINAL)) {
$element['method_final_index'] = $previous;
}
} while ($tokens[$previous]->isGivenKind($modifierKinds));
if ($enums[$classIndex]) {
$element['method_of_enum'] = true;
yield $element;
continue;
}
if (!\array_key_exists($classIndex, $classesAreFinal)) {
$modifiers = $tokensAnalyzer->getClassyModifiers($classIndex);
$classesAreFinal[$classIndex] = isset($modifiers['final']);
}
$element['method_of_enum'] = false;
$element['class_is_final'] = $classesAreFinal[$classIndex];
$element['method_is_constructor'] = '__construct' === strtolower($tokens[$tokens->getNextMeaningfulToken($index)]->getContent());
yield $element;
}
}
private function clearFinal(Tokens $tokens, ?int $index): void
{
if (null === $index) {
return;
}
$tokens->clearAt($index);
++$index;
if ($tokens[$index]->isWhitespace()) {
$tokens->clearAt($index);
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/FinalClassFixer.php | src/Fixer/ClassNotation/FinalClassFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
/**
* @author Filippo Tessarotto <zoeslam@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class FinalClassFixer extends AbstractProxyFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'All classes must be final, except abstract ones and Doctrine entities.',
[
new CodeSample(
<<<'PHP'
<?php
class MyApp {}
PHP,
),
],
'No exception and no configuration are intentional. Beside Doctrine entities and of course abstract classes, there is no single reason not to declare all classes final. '
.'If you want to subclass a class, mark the parent class as abstract and create two child classes, one empty if necessary: you\'ll gain much more fine grained type-hinting. '
.'If you need to mock a standalone class, create an interface, or maybe it\'s a value-object that shouldn\'t be mocked at all. '
.'If you need to extend a standalone class, create an interface and use the Composite pattern. '
.'If these rules are too strict for you, you can use `FinalInternalClassFixer` instead.',
'Risky when subclassing non-abstract classes.',
);
}
/**
* {@inheritdoc}
*
* Must run before ProtectedToPrivateFixer, SelfStaticAccessorFixer.
*/
public function getPriority(): int
{
return parent::getPriority();
}
protected function createProxyFixers(): array
{
$fixer = new FinalInternalClassFixer();
$fixer->configure([
'include' => [],
'consider_absent_docblock_as_internal_class' => true,
]);
return [$fixer];
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/ClassDefinitionFixer.php | src/Fixer/ClassNotation/ClassDefinitionFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* Fixer for part of the rules defined in PSR2 ¶4.1 Extends and Implements and PSR12 ¶8. Anonymous Classes.
*
* @phpstan-type _ClassReferenceInfo array{start: int, count: int, multiLine: bool}
* @phpstan-type _AutogeneratedInputConfiguration array{
* inline_constructor_arguments?: bool,
* multi_line_extends_each_single_line?: bool,
* single_item_single_line?: bool,
* single_line?: bool,
* space_before_parenthesis?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* inline_constructor_arguments: bool,
* multi_line_extends_each_single_line: bool,
* single_item_single_line: bool,
* single_line: bool,
* space_before_parenthesis: bool,
* }
* @phpstan-type _ClassyDefinitionInfo array{
* start: int,
* classy: int,
* open: int,
* extends: false|_ClassReferenceInfo,
* implements: false|_ClassReferenceInfo,
* anonymousClass: bool,
* final: false|int,
* abstract: false|int,
* readonly: false|int,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ClassDefinitionFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Whitespace around the keywords of a class, trait, enum or interfaces definition should be one space.',
[
new CodeSample(
<<<'PHP'
<?php
class Foo extends Bar implements Baz, BarBaz
{
}
final class Foo extends Bar implements Baz, BarBaz
{
}
trait Foo
{
}
$foo = new class extends Bar implements Baz, BarBaz {};
PHP,
),
new CodeSample(
<<<'PHP'
<?php
class Foo
extends Bar
implements Baz, BarBaz
{}
PHP,
['single_line' => true],
),
new CodeSample(
<<<'PHP'
<?php
class Foo
extends Bar
implements Baz
{}
PHP,
['single_item_single_line' => true],
),
new CodeSample(
<<<'PHP'
<?php
interface Bar extends
Bar, BarBaz, FooBarBaz
{}
PHP,
['multi_line_extends_each_single_line' => true],
),
new CodeSample(
<<<'PHP'
<?php
$foo = new class(){};
PHP,
['space_before_parenthesis' => true],
),
new CodeSample(
"<?php\n\$foo = new class(\n \$bar,\n \$baz\n) {};\n",
['inline_constructor_arguments' => true],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before BracesFixer, SingleLineEmptyBodyFixer.
* Must run after NewWithBracesFixer, NewWithParenthesesFixer, StringableForToStringFixer.
*/
public function getPriority(): int
{
return 36;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds());
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
// -4, one for count to index, 3 because min. of tokens for a classy location.
for ($index = $tokens->getSize() - 4; $index > 0; --$index) {
if ($tokens[$index]->isClassy()) {
$this->fixClassyDefinition($tokens, $index);
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('multi_line_extends_each_single_line', 'Whether definitions should be multiline.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
(new FixerOptionBuilder('single_item_single_line', 'Whether definitions should be single line when including a single item.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
(new FixerOptionBuilder('single_line', 'Whether definitions should be single line.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
(new FixerOptionBuilder('space_before_parenthesis', 'Whether there should be a single space after the parenthesis of anonymous class (PSR12) or not.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
(new FixerOptionBuilder('inline_constructor_arguments', 'Whether constructor argument list in anonymous classes should be single line.'))
->setAllowedTypes(['bool'])
->setDefault(true)
->getOption(),
]);
}
/**
* @param int $classyIndex Class definition token start index
*/
private function fixClassyDefinition(Tokens $tokens, int $classyIndex): void
{
$classDefInfo = $this->getClassyDefinitionInfo($tokens, $classyIndex);
// PSR2 4.1 Lists of implements MAY be split across multiple lines, where each subsequent line is indented once.
// When doing so, the first item in the list MUST be on the next line, and there MUST be only one interface per line.
if (false !== $classDefInfo['implements']) {
$classDefInfo['implements'] = $this->fixClassyDefinitionImplements(
$tokens,
$classDefInfo['open'],
$classDefInfo['implements'],
);
}
if (false !== $classDefInfo['extends']) {
$classDefInfo['extends'] = $this->fixClassyDefinitionExtends(
$tokens,
false === $classDefInfo['implements'] ? $classDefInfo['open'] : $classDefInfo['implements']['start'],
$classDefInfo['extends'],
);
}
// PSR2: class definition open curly brace must go on a new line.
// PSR12: anonymous class curly brace on same line if not multi line implements.
$classDefInfo['open'] = $this->fixClassyDefinitionOpenSpacing($tokens, $classDefInfo);
if (false !== $classDefInfo['implements']) {
$end = $classDefInfo['implements']['start'];
} elseif (false !== $classDefInfo['extends']) {
$end = $classDefInfo['extends']['start'];
} else {
$end = $tokens->getPrevNonWhitespace($classDefInfo['open']);
}
if ($classDefInfo['anonymousClass'] && false === $this->configuration['inline_constructor_arguments']) {
if (!$tokens[$end]->equals(')')) { // anonymous class with `extends` and/or `implements`
$start = $tokens->getPrevMeaningfulToken($end);
$this->makeClassyDefinitionSingleLine($tokens, $start, $end);
$end = $start;
}
if ($tokens[$end]->equals(')')) { // skip constructor arguments of anonymous class
$end = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $end);
}
}
// 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);
}
/**
* @param _ClassReferenceInfo $classExtendsInfo
*
* @return _ClassReferenceInfo
*/
private function fixClassyDefinitionExtends(Tokens $tokens, int $classOpenIndex, array $classExtendsInfo): array
{
$endIndex = $tokens->getPrevNonWhitespace($classOpenIndex);
if (true === $this->configuration['single_line'] || false === $classExtendsInfo['multiLine']) {
$this->makeClassyDefinitionSingleLine($tokens, $classExtendsInfo['start'], $endIndex);
$classExtendsInfo['multiLine'] = false;
} elseif (true === $this->configuration['single_item_single_line'] && 1 === $classExtendsInfo['count']) {
$this->makeClassyDefinitionSingleLine($tokens, $classExtendsInfo['start'], $endIndex);
$classExtendsInfo['multiLine'] = false;
} elseif (true === $this->configuration['multi_line_extends_each_single_line'] && $classExtendsInfo['multiLine']) {
$this->makeClassyInheritancePartMultiLine($tokens, $classExtendsInfo['start'], $endIndex);
$classExtendsInfo['multiLine'] = true;
}
return $classExtendsInfo;
}
/**
* @param _ClassReferenceInfo $classImplementsInfo
*
* @return _ClassReferenceInfo
*/
private function fixClassyDefinitionImplements(Tokens $tokens, int $classOpenIndex, array $classImplementsInfo): array
{
$endIndex = $tokens->getPrevNonWhitespace($classOpenIndex);
if (true === $this->configuration['single_line'] || false === $classImplementsInfo['multiLine']) {
$this->makeClassyDefinitionSingleLine($tokens, $classImplementsInfo['start'], $endIndex);
$classImplementsInfo['multiLine'] = false;
} elseif (true === $this->configuration['single_item_single_line'] && 1 === $classImplementsInfo['count']) {
$this->makeClassyDefinitionSingleLine($tokens, $classImplementsInfo['start'], $endIndex);
$classImplementsInfo['multiLine'] = false;
} else {
$this->makeClassyInheritancePartMultiLine($tokens, $classImplementsInfo['start'], $endIndex);
$classImplementsInfo['multiLine'] = true;
}
return $classImplementsInfo;
}
/**
* @param _ClassyDefinitionInfo $classDefInfo
*/
private function fixClassyDefinitionOpenSpacing(Tokens $tokens, array $classDefInfo): int
{
if ($classDefInfo['anonymousClass']) {
if (false !== $classDefInfo['implements']) {
$spacing = $classDefInfo['implements']['multiLine'] ? $this->whitespacesConfig->getLineEnding() : ' ';
} elseif (false !== $classDefInfo['extends']) {
$spacing = $classDefInfo['extends']['multiLine'] ? $this->whitespacesConfig->getLineEnding() : ' ';
} else {
$spacing = ' ';
}
} else {
$spacing = $this->whitespacesConfig->getLineEnding();
}
$openIndex = $tokens->getNextTokenOfKind($classDefInfo['classy'], ['{']);
if (' ' !== $spacing && str_contains($tokens[$openIndex - 1]->getContent(), "\n")) {
return $openIndex;
}
if ($tokens[$openIndex - 1]->isWhitespace()) {
if (' ' !== $spacing || !$tokens[$tokens->getPrevNonWhitespace($openIndex - 1)]->isComment()) {
$tokens[$openIndex - 1] = new Token([\T_WHITESPACE, $spacing]);
}
return $openIndex;
}
$tokens->insertAt($openIndex, new Token([\T_WHITESPACE, $spacing]));
return $openIndex + 1;
}
/**
* @return _ClassyDefinitionInfo
*/
private function getClassyDefinitionInfo(Tokens $tokens, int $classyIndex): array
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
$openIndex = $tokens->getNextTokenOfKind($classyIndex, ['{']);
$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);
$def['extends'] = [] !== $extends ? $this->getClassyInheritanceInfo($tokens, array_key_first($extends)) : false;
if (!$tokens[$classyIndex]->isGivenKind(\T_INTERFACE)) {
$implements = $tokens->findGivenKind(\T_IMPLEMENTS, $classyIndex, $openIndex);
$def['implements'] = [] !== $implements ? $this->getClassyInheritanceInfo($tokens, array_key_first($implements)) : false;
$def['anonymousClass'] = $tokensAnalyzer->isAnonymousClass($classyIndex);
}
}
if ($def['anonymousClass']) {
$startIndex = $tokens->getPrevTokenOfKind($classyIndex, [[\T_NEW]]); // go to "new" for anonymous class
} else {
$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;
}
}
}
$def['start'] = $startIndex;
return $def;
}
/**
* @return _ClassReferenceInfo
*/
private function getClassyInheritanceInfo(Tokens $tokens, int $startIndex): array
{
$implementsInfo = ['start' => $startIndex, 'count' => 1, 'multiLine' => false];
++$startIndex;
$endIndex = $tokens->getNextTokenOfKind($startIndex, ['{', [\T_IMPLEMENTS], [\T_EXTENDS]]);
$endIndex = $tokens[$endIndex]->equals('{') ? $tokens->getPrevNonWhitespace($endIndex) : $endIndex;
for ($i = $startIndex; $i < $endIndex; ++$i) {
if ($tokens[$i]->equals(',')) {
++$implementsInfo['count'];
continue;
}
if (!$implementsInfo['multiLine'] && str_contains($tokens[$i]->getContent(), "\n")) {
$implementsInfo['multiLine'] = true;
}
}
return $implementsInfo;
}
private function makeClassyDefinitionSingleLine(Tokens $tokens, int $startIndex, int $endIndex): void
{
for ($i = $endIndex; $i >= $startIndex; --$i) {
if ($tokens[$i]->isWhitespace()) {
if (str_contains($tokens[$i]->getContent(), "\n")) {
if ($tokens[$i - 1]->isGivenKind(CT::T_ATTRIBUTE_CLOSE) || $tokens[$i + 1]->isGivenKind(FCT::T_ATTRIBUTE)) {
continue;
}
if (($tokens[$i - 1]->isComment() && str_ends_with($tokens[$i - 1]->getContent(), ']'))
|| ($tokens[$i + 1]->isComment() && str_starts_with($tokens[$i + 1]->getContent(), '#['))
) {
continue;
}
if ($tokens[$i - 1]->isGivenKind(\T_DOC_COMMENT) || $tokens[$i + 1]->isGivenKind(\T_DOC_COMMENT)) {
continue;
}
}
if ($tokens[$i - 1]->isComment()) {
$content = $tokens[$i - 1]->getContent();
if (!str_starts_with($content, '//') && !str_starts_with($content, '#')) {
$tokens[$i] = new Token([\T_WHITESPACE, ' ']);
}
continue;
}
if ($tokens[$i + 1]->isComment()) {
$content = $tokens[$i + 1]->getContent();
if (!str_starts_with($content, '//')) {
$tokens[$i] = new Token([\T_WHITESPACE, ' ']);
}
continue;
}
if ($tokens[$i - 1]->isGivenKind(\T_CLASS) && $tokens[$i + 1]->equals('(')) {
if (true === $this->configuration['space_before_parenthesis']) {
$tokens[$i] = new Token([\T_WHITESPACE, ' ']);
} else {
$tokens->clearAt($i);
}
continue;
}
if (!$tokens[$i - 1]->equals(',') && $tokens[$i + 1]->equalsAny([',', ')']) || $tokens[$i - 1]->equals('(')) {
$tokens->clearAt($i);
continue;
}
$tokens[$i] = new Token([\T_WHITESPACE, ' ']);
continue;
}
if ($tokens[$i]->equals(',') && !$tokens[$i + 1]->isWhitespace()) {
$tokens->insertAt($i + 1, new Token([\T_WHITESPACE, ' ']));
continue;
}
if (true === $this->configuration['space_before_parenthesis'] && $tokens[$i]->isGivenKind(\T_CLASS) && !$tokens[$i + 1]->isWhitespace()) {
$tokens->insertAt($i + 1, new Token([\T_WHITESPACE, ' ']));
continue;
}
if (!$tokens[$i]->isComment()) {
continue;
}
if (!$tokens[$i + 1]->isWhitespace() && !$tokens[$i + 1]->isComment() && !str_contains($tokens[$i]->getContent(), "\n")) {
$tokens->insertAt($i + 1, new Token([\T_WHITESPACE, ' ']));
}
if (!$tokens[$i - 1]->isWhitespace() && !$tokens[$i - 1]->isComment()) {
$tokens->insertAt($i, new Token([\T_WHITESPACE, ' ']));
}
}
}
private function makeClassyInheritancePartMultiLine(Tokens $tokens, int $startIndex, int $endIndex): void
{
for ($i = $endIndex; $i > $startIndex; --$i) {
$previousInterfaceImplementingIndex = $tokens->getPrevTokenOfKind($i, [',', [\T_IMPLEMENTS], [\T_EXTENDS]]);
$breakAtIndex = $tokens->getNextMeaningfulToken($previousInterfaceImplementingIndex);
// make the part of a ',' or 'implements' single line
$this->makeClassyDefinitionSingleLine(
$tokens,
$breakAtIndex,
$i,
);
// make sure the part is on its own line
$isOnOwnLine = false;
for ($j = $breakAtIndex; $j > $previousInterfaceImplementingIndex; --$j) {
if (str_contains($tokens[$j]->getContent(), "\n")) {
$isOnOwnLine = true;
break;
}
}
if (!$isOnOwnLine) {
if ($tokens[$breakAtIndex - 1]->isWhitespace()) {
$tokens[$breakAtIndex - 1] = new Token([
\T_WHITESPACE,
$this->whitespacesConfig->getLineEnding().$this->whitespacesConfig->getIndent(),
]);
} else {
$tokens->insertAt($breakAtIndex, new Token([\T_WHITESPACE, $this->whitespacesConfig->getLineEnding().$this->whitespacesConfig->getIndent()]));
}
}
$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];
$readonlyToken = clone $tokens[$readonlyIndex];
$accessToken = clone $tokens[$accessModifierIndex];
$tokens[$readonlyIndex] = $accessToken;
$tokens[$accessModifierIndex] = $readonlyToken;
break;
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/StringableForToStringFixer.php | src/Fixer/ClassNotation/StringableForToStringFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Santiago San Martin <sanmartindev@gmail.com>
* @author Kuba Werłos <werlos@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class StringableForToStringFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'A class that implements the `__toString()` method must explicitly implement the `Stringable` interface.',
[
new CodeSample(
<<<'PHP'
<?php
class Foo
{
public function __toString()
{
return "Foo";
}
}
PHP,
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before ClassDefinitionFixer, GlobalNamespaceImportFixer, OrderedInterfacesFixer.
*/
public function getPriority(): int
{
return 37;
}
public function isCandidate(Tokens $tokens): bool
{
return \PHP_VERSION_ID >= 8_00_00 && $tokens->isAllTokenKindsFound([\T_CLASS, \T_STRING]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens);
$stringableInterfaces = ['stringable'];
for ($index = 1; $index < $tokens->count(); ++$index) {
if ($tokens[$index]->isGivenKind(\T_NAMESPACE)) {
$stringableInterfaces = [];
continue;
}
if ($tokens[$index]->isGivenKind(\T_USE)) {
$name = self::getNameFromUse($index, $useDeclarations);
if (null !== $name) {
$stringableInterfaces[] = $name;
}
continue;
}
if (!$tokens[$index]->isGivenKind(\T_CLASS)) {
continue;
}
$classStartIndex = $tokens->getNextTokenOfKind($index, ['{']);
\assert(\is_int($classStartIndex));
$classEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classStartIndex);
if (!self::doesHaveToStringMethod($tokens, $classStartIndex, $classEndIndex)) {
continue;
}
if (self::doesImplementStringable($tokens, $index, $classStartIndex, $stringableInterfaces)) {
continue;
}
self::addStringableInterface($tokens, $index);
}
}
/**
* @param list<NamespaceUseAnalysis> $useDeclarations
*/
private static function getNameFromUse(int $index, array $useDeclarations): ?string
{
$uses = array_filter(
$useDeclarations,
static fn (NamespaceUseAnalysis $namespaceUseAnalysis): bool => $namespaceUseAnalysis->getStartIndex() === $index,
);
if (0 === \count($uses)) {
return null;
}
\assert(1 === \count($uses));
$useDeclaration = reset($uses);
$lowercasedFullName = strtolower($useDeclaration->getFullName());
if ('stringable' !== $lowercasedFullName && '\stringable' !== $lowercasedFullName) {
return null;
}
return strtolower($useDeclaration->getShortName());
}
private static function doesHaveToStringMethod(Tokens $tokens, int $classStartIndex, int $classEndIndex): bool
{
$index = $classStartIndex;
while ($index < $classEndIndex) {
++$index;
if ($tokens[$index]->equals('{')) {
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
continue;
}
if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) {
continue;
}
$functionNameIndex = $tokens->getNextMeaningfulToken($index);
\assert(\is_int($functionNameIndex));
if ($tokens[$functionNameIndex]->equals([\T_STRING, '__toString'], false)) {
return true;
}
}
return false;
}
/**
* @param list<string> $stringableInterfaces
*/
private static function doesImplementStringable(
Tokens $tokens,
int $classKeywordIndex,
int $classOpenBraceIndex,
array $stringableInterfaces
): bool {
$implementedInterfaces = self::getInterfaces($tokens, $classKeywordIndex, $classOpenBraceIndex);
if ([] === $implementedInterfaces) {
return false;
}
if (\in_array('\stringable', $implementedInterfaces, true)) {
return true;
}
foreach ($stringableInterfaces as $stringableInterface) {
if (\in_array($stringableInterface, $implementedInterfaces, true)) {
return true;
}
}
return false;
}
/**
* @return list<string>
*/
private static function getInterfaces(Tokens $tokens, int $classKeywordIndex, int $classOpenBraceIndex): array
{
$implementsIndex = $tokens->getNextTokenOfKind($classKeywordIndex, ['{', [\T_IMPLEMENTS]]);
\assert(\is_int($implementsIndex));
$interfaces = [];
$interface = '';
for (
$index = $tokens->getNextMeaningfulToken($implementsIndex);
$index < $classOpenBraceIndex;
$index = $tokens->getNextMeaningfulToken($index)
) {
\assert(\is_int($index));
if ($tokens[$index]->equals(',')) {
$interfaces[] = strtolower($interface);
$interface = '';
continue;
}
$interface .= $tokens[$index]->getContent();
}
if ('' !== $interface) {
$interfaces[] = strtolower($interface);
}
return $interfaces;
}
private static function addStringableInterface(Tokens $tokens, int $classIndex): void
{
$implementsIndex = $tokens->getNextTokenOfKind($classIndex, ['{', [\T_IMPLEMENTS]]);
\assert(\is_int($implementsIndex));
if ($tokens[$implementsIndex]->equals('{')) {
$prevIndex = $tokens->getPrevMeaningfulToken($implementsIndex);
\assert(\is_int($prevIndex));
$tokens->insertSlices([
$prevIndex + 1 => [
new Token([\T_WHITESPACE, ' ']),
new Token([\T_IMPLEMENTS, 'implements']),
new Token([\T_WHITESPACE, ' ']),
new Token([\T_NS_SEPARATOR, '\\']),
new Token([\T_STRING, \Stringable::class]),
],
]);
return;
}
$afterImplementsIndex = $tokens->getNextMeaningfulToken($implementsIndex);
\assert(\is_int($afterImplementsIndex));
$tokens->insertSlices([
$afterImplementsIndex => [
new Token([\T_NS_SEPARATOR, '\\']),
new Token([\T_STRING, \Stringable::class]),
new Token(','),
new Token([\T_WHITESPACE, ' ']),
],
]);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/FinalPublicMethodForAbstractClassFixer.php | src/Fixer/ClassNotation/FinalPublicMethodForAbstractClassFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Filippo Tessarotto <zoeslam@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class FinalPublicMethodForAbstractClassFixer extends AbstractFixer
{
/**
* @var array<string, true>
*/
private array $magicMethods = [
'__construct' => true,
'__destruct' => true,
'__call' => true,
'__callstatic' => true,
'__get' => true,
'__set' => true,
'__isset' => true,
'__unset' => true,
'__sleep' => true,
'__wakeup' => true,
'__tostring' => true,
'__invoke' => true,
'__set_state' => true,
'__clone' => true,
'__debuginfo' => true,
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'All `public` methods of `abstract` classes should be `final`.',
[
new CodeSample(
<<<'PHP'
<?php
abstract class AbstractMachine
{
public function start()
{}
}
PHP,
),
],
'Enforce API encapsulation in an inheritance architecture. '
.'If you want to override a method, use the Template method pattern.',
'Risky when overriding `public` methods of `abstract` classes.',
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAllTokenKindsFound([\T_ABSTRACT, \T_PUBLIC, \T_FUNCTION]);
}
public function isRisky(): bool
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$abstracts = array_keys($tokens->findGivenKind(\T_ABSTRACT));
foreach (array_reverse($abstracts) as $abstractIndex) {
$classIndex = $tokens->getNextTokenOfKind($abstractIndex, [[\T_CLASS], [\T_FUNCTION]]);
if (!$tokens[$classIndex]->isGivenKind(\T_CLASS)) {
continue;
}
$classOpen = $tokens->getNextTokenOfKind($classIndex, ['{']);
$classClose = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpen);
$this->fixClass($tokens, $classOpen, $classClose);
}
}
private function fixClass(Tokens $tokens, int $classOpenIndex, int $classCloseIndex): void
{
for ($index = $classCloseIndex - 1; $index > $classOpenIndex; --$index) {
// skip method contents
if ($tokens[$index]->equals('}')) {
$index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
continue;
}
// skip non public methods
if (!$tokens[$index]->isGivenKind(\T_PUBLIC)) {
continue;
}
$nextIndex = $tokens->getNextMeaningfulToken($index);
$nextToken = $tokens[$nextIndex];
if ($nextToken->isGivenKind(\T_STATIC)) {
$nextIndex = $tokens->getNextMeaningfulToken($nextIndex);
$nextToken = $tokens[$nextIndex];
}
// skip uses, attributes, constants etc
if (!$nextToken->isGivenKind(\T_FUNCTION)) {
continue;
}
$nextIndex = $tokens->getNextMeaningfulToken($nextIndex);
$nextToken = $tokens[$nextIndex];
// skip magic methods
if (isset($this->magicMethods[strtolower($nextToken->getContent())])) {
continue;
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
$prevToken = $tokens[$prevIndex];
if ($prevToken->isGivenKind(\T_STATIC)) {
$index = $prevIndex;
$prevIndex = $tokens->getPrevMeaningfulToken($index);
$prevToken = $tokens[$prevIndex];
}
// skip abstract or already final methods
if ($prevToken->isGivenKind([\T_ABSTRACT, \T_FINAL])) {
$index = $prevIndex;
continue;
}
$tokens->insertAt(
$index,
[
new Token([\T_FINAL, 'final']),
new Token([\T_WHITESPACE, ' ']),
],
);
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/VisibilityRequiredFixer.php | src/Fixer/ClassNotation/VisibilityRequiredFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
/**
* @deprecated
*
* @phpstan-type _AutogeneratedInputConfiguration array{
* elements?: list<'const'|'method'|'property'>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* elements: list<'const'|'method'|'property'>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class VisibilityRequiredFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, DeprecatedFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private ModifierKeywordsFixer $proxyFixer;
public function __construct()
{
$this->proxyFixer = new ModifierKeywordsFixer();
parent::__construct();
}
public function getDefinition(): FixerDefinitionInterface
{
$fixerDefinition = $this->proxyFixer->getDefinition();
return new FixerDefinition(
$fixerDefinition->getSummary(),
$fixerDefinition->getCodeSamples(),
$fixerDefinition->getDescription(),
$fixerDefinition->getRiskyDescription(),
);
}
public function getSuccessorsNames(): array
{
return array_keys($this->proxyFixers);
}
protected function createProxyFixers(): array
{
return [
$this->proxyFixer,
];
}
/**
* @param _AutogeneratedInputConfiguration $configuration
*/
protected function configurePreNormalisation(array $configuration): void
{
$this->proxyFixer->configure($configuration);
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return $this->proxyFixer->createConfigurationDefinition();
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/ProtectedToPrivateFixer.php | src/Fixer/ClassNotation/ProtectedToPrivateFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @author Filippo Tessarotto <zoeslam@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ProtectedToPrivateFixer extends AbstractFixer
{
private const MODIFIER_KINDS = [\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, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET];
private TokensAnalyzer $tokensAnalyzer;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Converts `protected` variables and methods to `private` where possible.',
[
new CodeSample(
<<<'PHP'
<?php
final class Sample
{
protected $a;
protected function test()
{
}
}
PHP,
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before OrderedClassElementsFixer, StaticPrivateMethodFixer.
* Must run after FinalClassFixer, FinalInternalClassFixer.
*/
public function getPriority(): int
{
return 66;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([\T_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, FCT::T_PROTECTED_SET])
&& (
$tokens->isAllTokenKindsFound([\T_CLASS, \T_FINAL])
|| $tokens->isTokenKindFound(FCT::T_ENUM)
);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$this->tokensAnalyzer = new TokensAnalyzer($tokens);
$classesCandidate = [];
$classElementTypes = ['method' => true, 'property' => true, 'promoted_property' => true, 'const' => true];
foreach ($this->tokensAnalyzer->getClassyElements() as $index => $element) {
$classIndex = $element['classIndex'];
$classesCandidate[$classIndex] ??= $this->isClassCandidate($tokens, $classIndex);
if (false === $classesCandidate[$classIndex]) {
continue;
}
if (!isset($classElementTypes[$element['type']])) {
continue;
}
$previousIndex = $index;
$protectedIndex = null;
$protectedPromotedIndex = null;
$protectedSetIndex = null;
$isFinal = false;
do {
$previousIndex = $tokens->getPrevMeaningfulToken($previousIndex);
if ($tokens[$previousIndex]->isGivenKind(\T_PROTECTED)) {
$protectedIndex = $previousIndex;
} elseif ($tokens[$previousIndex]->isGivenKind(CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED)) {
$protectedPromotedIndex = $previousIndex;
} elseif ($tokens[$previousIndex]->isGivenKind(FCT::T_PROTECTED_SET)) {
$protectedSetIndex = $previousIndex;
} elseif ($tokens[$previousIndex]->isGivenKind(\T_FINAL)) {
$isFinal = true;
}
} while ($tokens[$previousIndex]->isGivenKind(self::MODIFIER_KINDS));
if ($isFinal && 'const' === $element['type']) {
continue; // Final constants cannot be private
}
if (null !== $protectedIndex) {
$tokens[$protectedIndex] = new Token([\T_PRIVATE, 'private']);
}
if (null !== $protectedPromotedIndex) {
$tokens[$protectedPromotedIndex] = new Token([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, 'private']);
}
if (null !== $protectedSetIndex) {
$tokens[$protectedSetIndex] = new Token([\T_PRIVATE_SET, 'private(set)']);
}
}
}
/**
* Consider symbol as candidate for fixing if it's:
* - an Enum (PHP8.1+)
* - a class, which:
* - is not anonymous
* - is final
* - does not use traits
* - does not extend other class.
*/
private function isClassCandidate(Tokens $tokens, int $classIndex): bool
{
if ($tokens[$classIndex]->isGivenKind(FCT::T_ENUM)) {
return true;
}
if (!$tokens[$classIndex]->isGivenKind(\T_CLASS) || $this->tokensAnalyzer->isAnonymousClass($classIndex)) {
return false;
}
$modifiers = $this->tokensAnalyzer->getClassyModifiers($classIndex);
if (!isset($modifiers['final'])) {
return false;
}
$classNameIndex = $tokens->getNextMeaningfulToken($classIndex); // move to class name as anonymous class is never "final"
$classExtendsIndex = $tokens->getNextMeaningfulToken($classNameIndex); // move to possible "extends"
if ($tokens[$classExtendsIndex]->isGivenKind(\T_EXTENDS)) {
return false;
}
if (!$tokens->isTokenKindFound(CT::T_USE_TRAIT)) {
return true; // cheap test
}
$classOpenIndex = $tokens->getNextTokenOfKind($classNameIndex, ['{']);
$classCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpenIndex);
$useIndex = $tokens->getNextTokenOfKind($classOpenIndex, [[CT::T_USE_TRAIT]]);
return null === $useIndex || $useIndex > $classCloseIndex;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/SelfAccessorFixer.php | src/Fixer/ClassNotation/SelfAccessorFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @author Gregor Harlan <gharlan@web.de>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class SelfAccessorFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Inside class or interface element `self` should be preferred to the class name itself.',
[
new CodeSample(
<<<'PHP'
<?php
class Sample
{
const BAZ = 1;
const BAR = Sample::BAZ;
public function getBar()
{
return Sample::BAR;
}
}
PHP,
),
],
null,
'Risky when using dynamic calls like get_called_class() or late static binding.',
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([\T_CLASS, \T_INTERFACE]);
}
/**
* {@inheritdoc}
*
* Must run after PsrAutoloadingFixer.
*/
public function getPriority(): int
{
return -11;
}
public function isRisky(): bool
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
foreach ($tokens->getNamespaceDeclarations() as $namespace) {
for ($index = $namespace->getScopeStartIndex(); $index < $namespace->getScopeEndIndex(); ++$index) {
if (!$tokens[$index]->isGivenKind([\T_CLASS, \T_INTERFACE]) || $tokensAnalyzer->isAnonymousClass($index)) {
continue;
}
$nameIndex = $tokens->getNextTokenOfKind($index, [[\T_STRING]]);
$startIndex = $tokens->getNextTokenOfKind($nameIndex, ['{']);
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startIndex);
$name = $tokens[$nameIndex]->getContent();
$this->replaceNameOccurrences($tokens, $namespace->getFullName(), $name, $startIndex, $endIndex);
$index = $endIndex;
}
}
}
/**
* Replace occurrences of the name of the classy element by "self" (if possible).
*/
private function replaceNameOccurrences(Tokens $tokens, string $namespace, string $name, int $startIndex, int $endIndex): void
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
$insideMethodSignatureUntil = null;
for ($i = $startIndex; $i < $endIndex; ++$i) {
if ($i === $insideMethodSignatureUntil) {
$insideMethodSignatureUntil = null;
}
$token = $tokens[$i];
// skip anonymous classes
if ($token->isGivenKind(\T_CLASS) && $tokensAnalyzer->isAnonymousClass($i)) {
$i = $tokens->getNextTokenOfKind($i, ['{']);
$i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $i);
continue;
}
if ($token->isGivenKind(\T_FN)) {
$i = $tokensAnalyzer->getLastTokenIndexOfArrowFunction($i);
$i = $tokens->getNextMeaningfulToken($i);
continue;
}
if ($token->isGivenKind(\T_FUNCTION)) {
if ($tokensAnalyzer->isLambda($i)) {
$i = $tokens->getNextTokenOfKind($i, ['{']);
$i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $i);
continue;
}
$i = $tokens->getNextTokenOfKind($i, ['(']);
$insideMethodSignatureUntil = $tokens->getNextTokenOfKind($i, ['{', ';']);
continue;
}
if (!$token->equals([\T_STRING, $name], false)) {
continue;
}
$nextToken = $tokens[$tokens->getNextMeaningfulToken($i)];
if ($nextToken->isGivenKind(\T_NS_SEPARATOR)) {
continue;
}
$classStartIndex = $i;
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($i)];
if ($prevToken->isGivenKind(\T_NS_SEPARATOR)) {
$classStartIndex = $this->getClassStart($tokens, $i, $namespace);
if (null === $classStartIndex) {
continue;
}
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($classStartIndex)];
}
if ($prevToken->isGivenKind(\T_STRING) || $prevToken->isObjectOperator()) {
continue;
}
if (
$prevToken->isGivenKind([\T_INSTANCEOF, \T_NEW])
|| $nextToken->isGivenKind(\T_PAAMAYIM_NEKUDOTAYIM)
|| (
null !== $insideMethodSignatureUntil
&& $i < $insideMethodSignatureUntil
&& $prevToken->equalsAny(['(', ',', [CT::T_NULLABLE_TYPE], [CT::T_TYPE_ALTERNATION], [CT::T_TYPE_COLON]])
)
) {
for ($j = $classStartIndex; $j < $i; ++$j) {
$tokens->clearTokenAndMergeSurroundingWhitespace($j);
}
$tokens[$i] = new Token([\T_STRING, 'self']);
}
}
}
private function getClassStart(Tokens $tokens, int $index, string $namespace): ?int
{
$namespace = ('' !== $namespace ? '\\'.$namespace : '').'\\';
foreach (array_reverse(Preg::split('/(\\\)/', $namespace, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE)) as $piece) {
$index = $tokens->getPrevMeaningfulToken($index);
if ('\\' === $piece) {
if (!$tokens[$index]->isGivenKind(\T_NS_SEPARATOR)) {
return null;
}
} elseif (!$tokens[$index]->equals([\T_STRING, $piece], false)) {
return null;
}
}
return $index;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php | src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use PhpCsFixer\Utils;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
/**
* Make sure there is one blank line above and below class elements.
*
* The exception is when an element is the first or last item in a 'classy'.
*
* @phpstan-type _Class array{
* index: int,
* open: int,
* close: int,
* elements: non-empty-list<_Element>
* }
* @phpstan-type _Element array{token: Token, type: string, index: int, start: int, end: int}
* @phpstan-type _AutogeneratedInputConfiguration array{
* elements?: array<string, string>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* elements: array<string, string>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ClassAttributesSeparationFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @internal
*/
public const SPACING_NONE = 'none';
/**
* @internal
*/
public const SPACING_ONE = 'one';
private const SPACING_ONLY_IF_META = 'only_if_meta';
private const MODIFIER_TYPES = [\T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_ABSTRACT, \T_FINAL, \T_STATIC, \T_STRING, \T_NS_SEPARATOR, \T_VAR, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET];
/**
* @var array<string, string>
*/
private array $classElementTypes = [];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Class, trait and interface elements must be separated with one or none blank line.',
[
new CodeSample(
<<<'PHP'
<?php
final class Sample
{
protected function foo()
{
}
protected function bar()
{
}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
class Sample
{private $a; // foo
/** second in a hour */
private $b;
}
PHP,
['elements' => ['property' => self::SPACING_ONE]],
),
new CodeSample(
<<<'PHP'
<?php
class Sample
{
const A = 1;
/** seconds in some hours */
const B = 3600;
}
PHP,
['elements' => ['const' => self::SPACING_ONE]],
),
new CodeSample(
<<<'PHP'
<?php
class Sample
{
/** @var int */
const SECOND = 1;
/** @var int */
const MINUTE = 60;
const HOUR = 3600;
const DAY = 86400;
}
PHP,
['elements' => ['const' => self::SPACING_ONLY_IF_META]],
),
new VersionSpecificCodeSample(
<<<'PHP'
<?php
class Sample
{
public $a;
#[SetUp]
public $b;
/** @var string */
public $c;
/** @internal */
#[Assert\String()]
public $d;
public $e;
}
PHP,
new VersionSpecification(8_00_00),
['elements' => ['property' => self::SPACING_ONLY_IF_META]],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before BracesFixer, IndentationTypeFixer, NoExtraBlankLinesFixer, StatementIndentationFixer.
* Must run after ModifierKeywordsFixer, OrderedClassElementsFixer, PhpUnitDataProviderMethodOrderFixer, SingleClassElementPerStatementFixer.
*/
public function getPriority(): int
{
return 55;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds());
}
protected function configurePostNormalisation(): void
{
$this->classElementTypes = []; // reset previous configuration
foreach ($this->configuration['elements'] as $elementType => $spacing) {
$this->classElementTypes[$elementType] = $spacing;
}
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($this->getElementsByClass($tokens) as $class) {
$elements = $class['elements'];
if (0 === \count($elements)) {
continue;
}
if (isset($this->classElementTypes[$elements[0]['type']])) {
$this->fixSpaceBelowClassElement($tokens, $class);
}
foreach ($elements as $index => $element) {
if (isset($this->classElementTypes[$element['type']])) {
$this->fixSpaceAboveClassElement($tokens, $class, $index);
}
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('elements', 'Dictionary of `const|method|property|trait_import|case` => `none|one|only_if_meta` values.'))
->setAllowedTypes(['array<string, string>'])
->setAllowedValues([static function (array $option): bool {
foreach ($option as $type => $spacing) {
$supportedTypes = ['const', 'method', 'property', 'trait_import', 'case'];
if (!\in_array($type, $supportedTypes, true)) {
throw new InvalidOptionsException(
\sprintf(
'Unexpected element type, expected any of %s, got "%s".',
Utils::naturalLanguageJoin($supportedTypes),
\gettype($type).'#'.$type,
),
);
}
$supportedSpacings = [self::SPACING_NONE, self::SPACING_ONE, self::SPACING_ONLY_IF_META];
if (!\in_array($spacing, $supportedSpacings, true)) {
throw new InvalidOptionsException(
\sprintf(
'Unexpected spacing for element type "%s", expected any of %s, got "%s".',
$spacing,
Utils::naturalLanguageJoin($supportedSpacings),
\is_object($spacing) ? \get_class($spacing) : (null === $spacing ? 'null' : \gettype($spacing).'#'.$spacing),
),
);
}
}
return true;
}])
->setDefault([
'const' => self::SPACING_ONE,
'method' => self::SPACING_ONE,
'property' => self::SPACING_ONE,
'trait_import' => self::SPACING_NONE,
'case' => self::SPACING_NONE,
])
->getOption(),
]);
}
/**
* Fix spacing above an element of a class, interface or trait.
*
* Deals with comments, PHPDocs and spaces above the element with respect to the position of the
* element within the class, interface or trait.
*
* @param _Class $class
*/
private function fixSpaceAboveClassElement(Tokens $tokens, array $class, int $elementIndex): void
{
\assert(isset($class['elements'][$elementIndex]));
$element = $class['elements'][$elementIndex];
$elementAboveEnd = isset($class['elements'][$elementIndex + 1]) ? $class['elements'][$elementIndex + 1]['end'] : 0;
$nonWhiteAbove = $tokens->getPrevNonWhitespace($element['start']);
// element is directly after class open brace
if ($nonWhiteAbove === $class['open']) {
$this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 1);
return;
}
// deal with comments above an element
if ($tokens[$nonWhiteAbove]->isGivenKind(\T_COMMENT)) {
// check if the comment belongs to the previous element
if ($elementAboveEnd === $nonWhiteAbove) {
$this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], $this->determineRequiredLineCount($tokens, $class, $elementIndex));
return;
}
// more than one line break, always bring it back to 2 line breaks between the element start and what is above it
if ($tokens[$nonWhiteAbove + 1]->isWhitespace() && substr_count($tokens[$nonWhiteAbove + 1]->getContent(), "\n") > 1) {
$this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 2);
return;
}
// there are 2 cases:
if (
1 === $element['start'] - $nonWhiteAbove
|| $tokens[$nonWhiteAbove - 1]->isWhitespace() && substr_count($tokens[$nonWhiteAbove - 1]->getContent(), "\n") > 0
|| $tokens[$nonWhiteAbove + 1]->isWhitespace() && substr_count($tokens[$nonWhiteAbove + 1]->getContent(), "\n") > 0
) {
// 1. The comment is meant for the element (although not a PHPDoc),
// make sure there is one line break between the element and the comment...
$this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 1);
// ... and make sure there is blank line above the comment (with the exception when it is directly after a class opening)
$nonWhiteAbove = $this->findCommentBlockStart($tokens, $nonWhiteAbove, $elementAboveEnd);
$nonWhiteAboveComment = $tokens->getPrevNonWhitespace($nonWhiteAbove);
if ($nonWhiteAboveComment === $class['open']) {
if ($tokens[$nonWhiteAboveComment - 1]->isWhitespace() && substr_count($tokens[$nonWhiteAboveComment - 1]->getContent(), "\n") > 0) {
$this->correctLineBreaks($tokens, $nonWhiteAboveComment, $nonWhiteAbove, 1);
}
} else {
$this->correctLineBreaks($tokens, $nonWhiteAboveComment, $nonWhiteAbove, 2);
}
} else {
// 2. The comment belongs to the code above the element,
// make sure there is a blank line above the element (i.e. 2 line breaks)
$this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 2);
}
return;
}
// deal with element with a PHPDoc/attribute above it
if ($tokens[$nonWhiteAbove]->isGivenKind([\T_DOC_COMMENT, CT::T_ATTRIBUTE_CLOSE])) {
// there should be one linebreak between the element and the attribute above it
$this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 1);
// make sure there is blank line above the comment (with the exception when it is directly after a class opening)
$nonWhiteAbove = $this->findCommentBlockStart($tokens, $nonWhiteAbove, $elementAboveEnd);
$nonWhiteAboveComment = $tokens->getPrevNonWhitespace($nonWhiteAbove);
$this->correctLineBreaks($tokens, $nonWhiteAboveComment, $nonWhiteAbove, $nonWhiteAboveComment === $class['open'] ? 1 : 2);
return;
}
$this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], $this->determineRequiredLineCount($tokens, $class, $elementIndex));
}
/**
* @param _Class $class
*/
private function determineRequiredLineCount(Tokens $tokens, array $class, int $elementIndex): int
{
\assert(isset($class['elements'][$elementIndex]));
$type = $class['elements'][$elementIndex]['type'];
$spacing = $this->classElementTypes[$type];
if (self::SPACING_ONE === $spacing) {
return 2;
}
if (self::SPACING_NONE === $spacing) {
if (!isset($class['elements'][$elementIndex + 1])) {
return 1;
}
$aboveElement = $class['elements'][$elementIndex + 1];
if ($aboveElement['type'] !== $type) {
return 2;
}
$aboveElementDocCandidateIndex = $tokens->getPrevNonWhitespace($aboveElement['start']);
return $tokens[$aboveElementDocCandidateIndex]->isGivenKind([\T_DOC_COMMENT, CT::T_ATTRIBUTE_CLOSE]) ? 2 : 1;
}
if (self::SPACING_ONLY_IF_META === $spacing) {
$aboveElementDocCandidateIndex = $tokens->getPrevNonWhitespace($class['elements'][$elementIndex]['start']);
return $tokens[$aboveElementDocCandidateIndex]->isGivenKind([\T_DOC_COMMENT, CT::T_ATTRIBUTE_CLOSE]) ? 2 : 1;
}
throw new \RuntimeException(\sprintf('Unknown spacing "%s".', $spacing));
}
/**
* @param _Class $class
*/
private function fixSpaceBelowClassElement(Tokens $tokens, array $class): void
{
$element = $class['elements'][0];
// if this is last element fix; fix to the class end `}` here if appropriate
if ($class['close'] === $tokens->getNextNonWhitespace($element['end'])) {
$this->correctLineBreaks($tokens, $element['end'], $class['close'], 1);
}
}
private function correctLineBreaks(Tokens $tokens, int $startIndex, int $endIndex, int $reqLineCount): void
{
$lineEnding = $this->whitespacesConfig->getLineEnding();
++$startIndex;
$numbOfWhiteTokens = $endIndex - $startIndex;
if (0 === $numbOfWhiteTokens) {
$tokens->insertAt($startIndex, new Token([\T_WHITESPACE, str_repeat($lineEnding, $reqLineCount)]));
return;
}
$lineBreakCount = $this->getLineBreakCount($tokens, $startIndex, $endIndex);
if ($reqLineCount === $lineBreakCount) {
return;
}
if ($lineBreakCount < $reqLineCount) {
$tokens[$startIndex] = new Token([
\T_WHITESPACE,
str_repeat($lineEnding, $reqLineCount - $lineBreakCount).$tokens[$startIndex]->getContent(),
]);
return;
}
// $lineCount = > $reqLineCount : check the one Token case first since this one will be true most of the time
if (1 === $numbOfWhiteTokens) {
$tokens[$startIndex] = new Token([
\T_WHITESPACE,
Preg::replace('/\r\n|\n/', '', $tokens[$startIndex]->getContent(), $lineBreakCount - $reqLineCount),
]);
return;
}
// $numbOfWhiteTokens = > 1
$toReplaceCount = $lineBreakCount - $reqLineCount;
for ($i = $startIndex; $i < $endIndex && $toReplaceCount > 0; ++$i) {
$tokenLineCount = substr_count($tokens[$i]->getContent(), "\n");
if ($tokenLineCount > 0) {
$tokens[$i] = new Token([
\T_WHITESPACE,
Preg::replace('/\r\n|\n/', '', $tokens[$i]->getContent(), min($toReplaceCount, $tokenLineCount)),
]);
$toReplaceCount -= $tokenLineCount;
}
}
}
private function getLineBreakCount(Tokens $tokens, int $startIndex, int $endIndex): int
{
$lineCount = 0;
for ($i = $startIndex; $i < $endIndex; ++$i) {
$lineCount += substr_count($tokens[$i]->getContent(), "\n");
}
return $lineCount;
}
private function findCommentBlockStart(Tokens $tokens, int $start, int $elementAboveEnd): int
{
for ($i = $start; $i > $elementAboveEnd; --$i) {
if ($tokens[$i]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) {
$start = $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $i);
continue;
}
if ($tokens[$i]->isComment()) {
$start = $i;
continue;
}
if (!$tokens[$i]->isWhitespace() || $this->getLineBreakCount($tokens, $i, $i + 1) > 1) {
break;
}
}
return $start;
}
/**
* @TODO Introduce proper DTO instead of an array
*
* @return \Generator<_Class>
*/
private function getElementsByClass(Tokens $tokens): \Generator
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
$class = null;
foreach (array_reverse($tokensAnalyzer->getClassyElements(), true) as $index => $element) {
$element['index'] = $index;
if (null === $class || $element['classIndex'] !== $class['index']) {
if (null !== $class) {
yield $class;
}
$classIndex = $element['classIndex'];
$classOpen = $tokens->getNextTokenOfKind($classIndex, ['{']);
$classEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpen);
$class = [
'index' => $element['classIndex'],
'open' => $classOpen,
'close' => $classEnd,
'elements' => [],
];
}
unset($element['classIndex']);
$element['start'] = $this->getFirstTokenIndexOfClassElement($tokens, $class['open'], $index);
$element['end'] = $this->getLastTokenIndexOfClassElement($tokens, $class['index'], $index, $element['type'], $tokensAnalyzer);
$class['elements'][] = $element; // reset the key by design
}
if (null !== $class) {
yield $class;
}
}
/**
* including trailing single line comments if belonging to the class element.
*/
private function getFirstTokenIndexOfClassElement(Tokens $tokens, int $classOpen, int $elementIndex): int
{
$firstElementAttributeIndex = $elementIndex;
do {
$nonWhiteAbove = $tokens->getPrevMeaningfulToken($firstElementAttributeIndex);
if (null !== $nonWhiteAbove && $tokens[$nonWhiteAbove]->isGivenKind(self::MODIFIER_TYPES)) {
$firstElementAttributeIndex = $nonWhiteAbove;
} else {
break;
}
} while ($firstElementAttributeIndex > $classOpen);
return $firstElementAttributeIndex;
}
/**
* including trailing single line comments if belonging to the class element.
*/
private function getLastTokenIndexOfClassElement(Tokens $tokens, int $classIndex, int $elementIndex, string $elementType, TokensAnalyzer $tokensAnalyzer): int
{
// find last token of the element
if ('method' === $elementType && !$tokens[$classIndex]->isGivenKind(\T_INTERFACE)) {
$attributes = $tokensAnalyzer->getMethodAttributes($elementIndex);
if (true === $attributes['abstract']) {
$elementEndIndex = $tokens->getNextTokenOfKind($elementIndex, [';']);
} else {
$elementEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $tokens->getNextTokenOfKind($elementIndex, ['{']));
}
} elseif ('trait_import' === $elementType) {
$elementEndIndex = $elementIndex;
do {
$elementEndIndex = $tokens->getNextMeaningfulToken($elementEndIndex);
} while ($tokens[$elementEndIndex]->isGivenKind([\T_STRING, \T_NS_SEPARATOR]) || $tokens[$elementEndIndex]->equals(','));
if (!$tokens[$elementEndIndex]->equals(';')) {
$elementEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $tokens->getNextTokenOfKind($elementIndex, ['{']));
}
} else { // 'const', 'property', enum-'case', or 'method' of an interface
$elementEndIndex = $tokens->getNextTokenOfKind($elementIndex, [';', '{']);
}
$singleLineElement = true;
for ($i = $elementIndex + 1; $i < $elementEndIndex; ++$i) {
if (str_contains($tokens[$i]->getContent(), "\n")) {
$singleLineElement = false;
break;
}
}
if ($singleLineElement) {
while (true) {
$nextToken = $tokens[$elementEndIndex + 1];
if (($nextToken->isComment() || $nextToken->isWhitespace()) && !str_contains($nextToken->getContent(), "\n")) {
++$elementEndIndex;
} else {
break;
}
}
if ($tokens[$elementEndIndex]->isWhitespace()) {
$elementEndIndex = $tokens->getPrevNonWhitespace($elementEndIndex);
}
}
return $elementEndIndex;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/StaticPrivateMethodFixer.php | src/Fixer/ClassNotation/StaticPrivateMethodFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @author Filippo Tessarotto <zoeslam@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class StaticPrivateMethodFixer extends AbstractFixer
{
/**
* @var array<string, true>
*/
private const MAGIC_METHODS = [
'__clone' => true,
'__construct' => true,
'__destruct' => true,
'__wakeup' => true,
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Converts private methods to `static` where possible.',
[
new CodeSample(
<<<'PHP'
<?php
class Foo
{
public function bar()
{
return $this->baz();
}
private function baz()
{
return 1;
}
}
PHP,
),
],
null,
'Risky when the method:'
.' contains dynamic generated calls to the instance,'
.' is dynamically referenced,'
.' is referenced inside a Trait the class uses.',
);
}
/**
* {@inheritdoc}
*
* Must run before StaticLambdaFixer.
* Must run after ProtectedToPrivateFixer.
*/
public function getPriority(): int
{
return 1;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAllTokenKindsFound([\T_CLASS, \T_PRIVATE, \T_FUNCTION]);
}
public function isRisky(): bool
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
do {
$anythingChanged = false;
$end = \count($tokens) - 3; // min. number of tokens to form a class candidate to fix
for ($index = $end; $index > 0; --$index) {
if (!$tokens[$index]->isGivenKind(\T_CLASS)) {
continue;
}
$classOpen = $tokens->getNextTokenOfKind($index, ['{']);
$classClose = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpen);
$anythingChanged |= $this->fixClass($tokens, $tokensAnalyzer, $classOpen, $classClose);
}
} while ($anythingChanged);
}
private function fixClass(Tokens $tokens, TokensAnalyzer $tokensAnalyzer, int $classOpen, int $classClose): bool
{
$fixedMethods = [];
foreach ($this->getClassMethods($tokens, $classOpen, $classClose) as $methodData) {
[$functionKeywordIndex, $methodOpen, $methodClose] = $methodData;
if ($this->skipMethod($tokens, $tokensAnalyzer, $functionKeywordIndex, $methodOpen, $methodClose)) {
continue;
}
$methodNameIndex = $tokens->getNextMeaningfulToken($functionKeywordIndex);
$methodName = $tokens[$methodNameIndex]->getContent();
$fixedMethods[$methodName] = true;
$tokens->insertSlices([$functionKeywordIndex => [new Token([\T_STATIC, 'static']), new Token([\T_WHITESPACE, ' '])]]);
}
if (0 === \count($fixedMethods)) {
return false;
}
$classClose = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpen);
foreach ($this->getClassMethods($tokens, $classOpen, $classClose) as $methodData) {
[, $methodOpen, $methodClose] = $methodData;
$this->fixReferencesInFunction($tokens, $tokensAnalyzer, $methodOpen, $methodClose, $fixedMethods);
}
return true;
}
private function skipMethod(Tokens $tokens, TokensAnalyzer $tokensAnalyzer, int $functionKeywordIndex, int $methodOpen, int $methodClose): bool
{
$methodNameIndex = $tokens->getNextMeaningfulToken($functionKeywordIndex);
$methodName = strtolower($tokens[$methodNameIndex]->getContent());
if (isset(self::MAGIC_METHODS[$methodName])) {
return true;
}
$prevTokenIndex = $tokens->getPrevMeaningfulToken($functionKeywordIndex);
if ($tokens[$prevTokenIndex]->isGivenKind(\T_FINAL)) {
$prevTokenIndex = $tokens->getPrevMeaningfulToken($prevTokenIndex);
}
if (!$tokens[$prevTokenIndex]->isGivenKind(\T_PRIVATE)) {
return true;
}
$prePrevTokenIndex = $tokens->getPrevMeaningfulToken($prevTokenIndex);
if ($tokens[$prePrevTokenIndex]->isGivenKind(\T_STATIC)) {
return true;
}
for ($index = $methodOpen + 1; $index < $methodClose - 1; ++$index) {
if ($tokens[$index]->isGivenKind(\T_CLASS) && $tokensAnalyzer->isAnonymousClass($index)) {
$anonymousClassOpen = $tokens->getNextTokenOfKind($index, ['{']);
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $anonymousClassOpen);
continue;
}
if ($tokens[$index]->isGivenKind(\T_FUNCTION)) {
return true;
}
if ($tokens[$index]->equals([\T_VARIABLE, '$this'])) {
$operatorIndex = $tokens->getNextMeaningfulToken($index);
$methodNameIndex = $tokens->getNextMeaningfulToken($operatorIndex);
$argumentsBraceIndex = $tokens->getNextMeaningfulToken($methodNameIndex);
if (
!$tokens[$operatorIndex]->isGivenKind(\T_OBJECT_OPERATOR)
|| $methodName !== $tokens[$methodNameIndex]->getContent()
|| !$tokens[$argumentsBraceIndex]->equals('(')
) {
return true;
}
}
if ($tokens[$index]->equals([\T_STRING, 'debug_backtrace'])) {
return true;
}
}
return false;
}
/**
* @param array<string, bool> $fixedMethods
*/
private function fixReferencesInFunction(Tokens $tokens, TokensAnalyzer $tokensAnalyzer, int $methodOpen, int $methodClose, array $fixedMethods): void
{
for ($index = $methodOpen + 1; $index < $methodClose - 1; ++$index) {
if ($tokens[$index]->isGivenKind(\T_FUNCTION)) {
$prevIndex = $tokens->getPrevMeaningfulToken($index);
$closureStart = $tokens->getNextTokenOfKind($index, ['{']);
$closureEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $closureStart);
if (!$tokens[$prevIndex]->isGivenKind(\T_STATIC)) {
$this->fixReferencesInFunction($tokens, $tokensAnalyzer, $closureStart, $closureEnd, $fixedMethods);
}
$index = $closureEnd;
continue;
}
if ($tokens[$index]->isGivenKind(\T_CLASS) && $tokensAnalyzer->isAnonymousClass($index)) {
$anonymousClassOpen = $tokens->getNextTokenOfKind($index, ['{']);
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $anonymousClassOpen);
continue;
}
if (!$tokens[$index]->equals([\T_VARIABLE, '$this'])) {
continue;
}
$objectOperatorIndex = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$objectOperatorIndex]->isGivenKind(\T_OBJECT_OPERATOR)) {
continue;
}
$methodNameIndex = $tokens->getNextMeaningfulToken($objectOperatorIndex);
$argumentsBraceIndex = $tokens->getNextMeaningfulToken($methodNameIndex);
if (!$tokens[$argumentsBraceIndex]->equals('(')) {
continue;
}
$currentMethodName = $tokens[$methodNameIndex]->getContent();
if (!isset($fixedMethods[$currentMethodName])) {
continue;
}
$tokens[$index] = new Token([\T_STRING, 'self']);
$tokens[$objectOperatorIndex] = new Token([\T_DOUBLE_COLON, '::']);
}
}
/**
* @return list<array{int, int, int}>
*/
private function getClassMethods(Tokens $tokens, int $classOpen, int $classClose): array
{
$methods = [];
for ($index = $classClose - 1; $index > $classOpen + 1; --$index) {
if ($tokens[$index]->equals('}')) {
$index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
continue;
}
if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) {
continue;
}
$functionKeywordIndex = $index;
$prevTokenIndex = $tokens->getPrevMeaningfulToken($functionKeywordIndex);
$prevPrevTokenIndex = $tokens->getPrevMeaningfulToken($prevTokenIndex);
if ($tokens[$prevTokenIndex]->isGivenKind(\T_ABSTRACT) || $tokens[$prevPrevTokenIndex]->isGivenKind(\T_ABSTRACT)) {
continue;
}
$methodOpen = $tokens->getNextTokenOfKind($functionKeywordIndex, ['{']);
$methodClose = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $methodOpen);
$methods[] = [$functionKeywordIndex, $methodOpen, $methodClose];
}
return $methods;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/OrderedInterfacesFixer.php | src/Fixer/ClassNotation/OrderedInterfacesFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* case_sensitive?: bool,
* direction?: 'ascend'|'descend',
* order?: 'alpha'|'length',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* case_sensitive: bool,
* direction: 'ascend'|'descend',
* order: 'alpha'|'length',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Dave van der Brugge <dmvdbrugge@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class OrderedInterfacesFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/** @internal */
public const OPTION_DIRECTION = 'direction';
/** @internal */
public const OPTION_ORDER = 'order';
/** @internal */
public const DIRECTION_ASCEND = 'ascend';
/** @internal */
public const DIRECTION_DESCEND = 'descend';
/** @internal */
public const ORDER_ALPHA = 'alpha';
/** @internal */
public const ORDER_LENGTH = 'length';
/**
* Array of supported directions in configuration.
*
* @var non-empty-list<string>
*/
private const SUPPORTED_DIRECTION_OPTIONS = [
self::DIRECTION_ASCEND,
self::DIRECTION_DESCEND,
];
/**
* Array of supported orders in configuration.
*
* @var non-empty-list<string>
*/
private const SUPPORTED_ORDER_OPTIONS = [
self::ORDER_ALPHA,
self::ORDER_LENGTH,
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Orders the interfaces in an `implements` or `interface extends` clause.',
[
new CodeSample(
"<?php\n\nfinal class ExampleA implements Gamma, Alpha, Beta {}\n\ninterface ExampleB extends Gamma, Alpha, Beta {}\n",
),
new CodeSample(
"<?php\n\nfinal class ExampleA implements Gamma, Alpha, Beta {}\n\ninterface ExampleB extends Gamma, Alpha, Beta {}\n",
[self::OPTION_DIRECTION => self::DIRECTION_DESCEND],
),
new CodeSample(
"<?php\n\nfinal class ExampleA implements MuchLonger, Short, Longer {}\n\ninterface ExampleB extends MuchLonger, Short, Longer {}\n",
[self::OPTION_ORDER => self::ORDER_LENGTH],
),
new CodeSample(
"<?php\n\nfinal class ExampleA implements MuchLonger, Short, Longer {}\n\ninterface ExampleB extends MuchLonger, Short, Longer {}\n",
[
self::OPTION_ORDER => self::ORDER_LENGTH,
self::OPTION_DIRECTION => self::DIRECTION_DESCEND,
],
),
new CodeSample(
"<?php\n\nfinal class ExampleA implements IgnorecaseB, IgNoReCaSeA, IgnoreCaseC {}\n\ninterface ExampleB extends IgnorecaseB, IgNoReCaSeA, IgnoreCaseC {}\n",
[
self::OPTION_ORDER => self::ORDER_ALPHA,
],
),
new CodeSample(
"<?php\n\nfinal class ExampleA implements Casesensitivea, CaseSensitiveA, CasesensitiveA {}\n\ninterface ExampleB extends Casesensitivea, CaseSensitiveA, CasesensitiveA {}\n",
[
self::OPTION_ORDER => self::ORDER_ALPHA,
'case_sensitive' => true,
],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after FullyQualifiedStrictTypesFixer, StringableForToStringFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_IMPLEMENTS)
|| $tokens->isAllTokenKindsFound([\T_INTERFACE, \T_EXTENDS]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(\T_IMPLEMENTS)) {
if (!$token->isGivenKind(\T_EXTENDS)) {
continue;
}
$nameTokenIndex = $tokens->getPrevMeaningfulToken($index);
$interfaceTokenIndex = $tokens->getPrevMeaningfulToken($nameTokenIndex);
$interfaceToken = $tokens[$interfaceTokenIndex];
if (!$interfaceToken->isGivenKind(\T_INTERFACE)) {
continue;
}
}
$implementsStart = $index + 1;
$implementsEnd = $tokens->getPrevMeaningfulToken($tokens->getNextTokenOfKind($implementsStart, ['{']));
$interfacesTokens = $this->getInterfaces($tokens, $implementsStart, $implementsEnd);
if (1 === \count($interfacesTokens)) {
continue;
}
$interfaces = [];
foreach ($interfacesTokens as $interfaceIndex => $interface) {
$interfaceTokens = Tokens::fromArray($interface);
$normalized = '';
$actualInterfaceIndex = $interfaceTokens->getNextMeaningfulToken(-1);
while ($interfaceTokens->offsetExists($actualInterfaceIndex)) {
$token = $interfaceTokens[$actualInterfaceIndex];
if ($token->isComment() || $token->isWhitespace()) {
break;
}
$normalized .= str_replace('\\', ' ', $token->getContent());
++$actualInterfaceIndex;
}
$interfaces[$interfaceIndex] = [
'tokens' => $interface,
'normalized' => $normalized,
'originalIndex' => $interfaceIndex,
];
}
usort($interfaces, function (array $first, array $second): int {
$score = self::ORDER_LENGTH === $this->configuration[self::OPTION_ORDER]
? \strlen($first['normalized']) - \strlen($second['normalized'])
: (
true === $this->configuration['case_sensitive']
? $first['normalized'] <=> $second['normalized']
: strcasecmp($first['normalized'], $second['normalized'])
);
if (self::DIRECTION_DESCEND === $this->configuration[self::OPTION_DIRECTION]) {
$score *= -1;
}
return $score;
});
$changed = false;
foreach ($interfaces as $interfaceIndex => $interface) {
if ($interface['originalIndex'] !== $interfaceIndex) {
$changed = true;
break;
}
}
if (!$changed) {
continue;
}
$newTokens = array_shift($interfaces)['tokens'];
foreach ($interfaces as $interface) {
array_push($newTokens, new Token(','), ...$interface['tokens']);
}
$tokens->overrideRange($implementsStart, $implementsEnd, $newTokens);
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder(self::OPTION_ORDER, 'How the interfaces should be ordered.'))
->setAllowedValues(self::SUPPORTED_ORDER_OPTIONS)
->setDefault(self::ORDER_ALPHA)
->getOption(),
(new FixerOptionBuilder(self::OPTION_DIRECTION, 'Which direction the interfaces should be ordered.'))
->setAllowedValues(self::SUPPORTED_DIRECTION_OPTIONS)
->setDefault(self::DIRECTION_ASCEND)
->getOption(),
(new FixerOptionBuilder('case_sensitive', 'Whether the sorting should be case sensitive.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
/**
* @return array<int, list<Token>>
*/
private function getInterfaces(Tokens $tokens, int $implementsStart, int $implementsEnd): array
{
$interfaces = [];
$interfaceIndex = 0;
for ($i = $implementsStart; $i <= $implementsEnd; ++$i) {
if ($tokens[$i]->equals(',')) {
++$interfaceIndex;
$interfaces[$interfaceIndex] = [];
continue;
}
$interfaces[$interfaceIndex][] = $tokens[$i];
}
return $interfaces;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/OrderedClassElementsFixer.php | src/Fixer/ClassNotation/OrderedClassElementsFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Utils;
/**
* @phpstan-type _ClassElement array{
* start: int,
* visibility: string,
* abstract: bool,
* static: bool,
* readonly: bool,
* type: string,
* name: string,
* end: int,
* }
* @phpstan-type _AutogeneratedInputConfiguration array{
* case_sensitive?: bool,
* order?: list<string>,
* sort_algorithm?: 'alpha'|'none',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* case_sensitive: bool,
* order: list<string>,
* sort_algorithm: 'alpha'|'none',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Gregor Harlan <gharlan@web.de>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class OrderedClassElementsFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/** @internal */
public const SORT_ALPHA = 'alpha';
/** @internal */
public const SORT_NONE = 'none';
private const SUPPORTED_SORT_ALGORITHMS = [
self::SORT_NONE,
self::SORT_ALPHA,
];
/**
* @var array<string, null|non-empty-list<string>> Array containing all class element base types (keys) and their parent types (values)
*/
private const TYPE_HIERARCHY = [
'use_trait' => null,
'public' => null,
'protected' => null,
'private' => null,
'case' => ['public'],
'constant' => null,
'constant_public' => ['constant', 'public'],
'constant_protected' => ['constant', 'protected'],
'constant_private' => ['constant', 'private'],
'property' => null,
'property_static' => ['property'],
'property_public' => ['property', 'public'],
'property_protected' => ['property', 'protected'],
'property_private' => ['property', 'private'],
'property_public_abstract' => ['property_abstract', 'property_public'],
'property_public_readonly' => ['property_readonly', 'property_public'],
'property_protected_abstract' => ['property_abstract', 'property_protected'],
'property_protected_readonly' => ['property_readonly', 'property_protected'],
'property_private_readonly' => ['property_readonly', 'property_private'],
'property_public_static' => ['property_static', 'property_public'],
'property_protected_static' => ['property_static', 'property_protected'],
'property_private_static' => ['property_static', 'property_private'],
'method' => null,
'method_abstract' => ['method'],
'method_static' => ['method'],
'method_public' => ['method', 'public'],
'method_protected' => ['method', 'protected'],
'method_private' => ['method', 'private'],
'method_public_abstract' => ['method_abstract', 'method_public'],
'method_protected_abstract' => ['method_abstract', 'method_protected'],
'method_private_abstract' => ['method_abstract', 'method_private'],
'method_public_abstract_static' => ['method_abstract', 'method_static', 'method_public'],
'method_protected_abstract_static' => ['method_abstract', 'method_static', 'method_protected'],
'method_private_abstract_static' => ['method_abstract', 'method_static', 'method_private'],
'method_public_static' => ['method_static', 'method_public'],
'method_protected_static' => ['method_static', 'method_protected'],
'method_private_static' => ['method_static', 'method_private'],
];
/**
* @var array<string, null> Array containing special method types
*/
private const SPECIAL_TYPES = [
'construct' => null,
'destruct' => null,
'magic' => null,
'phpunit' => null,
];
/**
* @var array<string, int> Resolved configuration array (type => position)
*/
private array $typePosition;
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds());
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Orders the elements of classes/interfaces/traits/enums.',
[
new CodeSample(
<<<'PHP'
<?php
final class Example
{
use BarTrait;
use BazTrait;
const C1 = 1;
const C2 = 2;
protected static $protStatProp;
public static $pubStatProp1;
public $pubProp1;
protected $protProp;
var $pubProp2;
private static $privStatProp;
private $privProp;
public static $pubStatProp2;
public $pubProp3;
protected function __construct() {}
private static function privStatFunc() {}
public function pubFunc1() {}
public function __toString() {}
protected function protFunc() {}
function pubFunc2() {}
public static function pubStatFunc1() {}
public function pubFunc3() {}
static function pubStatFunc2() {}
private function privFunc() {}
public static function pubStatFunc3() {}
protected static function protStatFunc() {}
public function __destruct() {}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
class Example
{
public function A(){}
private function B(){}
}
PHP,
['order' => ['method_private', 'method_public']],
),
new CodeSample(
<<<'PHP'
<?php
class Example
{
public function D(){}
public function B(){}
public function A(){}
public function C(){}
}
PHP,
['order' => ['method_public'], 'sort_algorithm' => self::SORT_ALPHA],
),
new CodeSample(
<<<'PHP'
<?php
class Example
{
public function Aa(){}
public function AA(){}
public function AwS(){}
public function AWs(){}
}
PHP,
['order' => ['method_public'], 'sort_algorithm' => self::SORT_ALPHA, 'case_sensitive' => true],
),
],
'Accepts a subset of pre-defined element types, special element groups, and custom patterns.
Element types: `[\''.implode('\', \'', array_keys(self::TYPE_HIERARCHY)).'\']`
Special element types: `[\''.implode('\', \'', array_keys(self::SPECIAL_TYPES)).'\']`
Custom values:
- `method:*`: specify a single method name (e.g. `method:__invoke`) to set the order of that specific method.',
);
}
/**
* {@inheritdoc}
*
* Must run before ClassAttributesSeparationFixer, NoBlankLinesAfterClassOpeningFixer, PhpUnitDataProviderMethodOrderFixer, SpaceAfterSemicolonFixer.
* Must run after NoPhp4ConstructorFixer, ProtectedToPrivateFixer.
*/
public function getPriority(): int
{
return 65;
}
protected function configurePostNormalisation(): void
{
$this->typePosition = [];
$position = 0;
foreach ($this->configuration['order'] as $type) {
$this->typePosition[$type] = $position++;
}
foreach (self::TYPE_HIERARCHY as $type => $parents) {
if (isset($this->typePosition[$type])) {
continue;
}
if (null === $parents) {
$this->typePosition[$type] = null;
continue;
}
foreach ($parents as $parent) {
if (isset($this->typePosition[$parent])) {
$this->typePosition[$type] = $this->typePosition[$parent];
continue 2;
}
}
$this->typePosition[$type] = null;
}
$lastPosition = \count($this->configuration['order']);
foreach ($this->typePosition as &$pos) {
if (null === $pos) {
$pos = $lastPosition;
}
$pos *= 10; // last digit is used by phpunit method ordering
}
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($i = 1, $count = $tokens->count(); $i < $count; ++$i) {
if (!$tokens[$i]->isClassy()) {
continue;
}
$i = $tokens->getNextTokenOfKind($i, ['{']);
$elements = $this->getElements($tokens, $i);
if (0 === \count($elements)) {
continue;
}
$endIndex = $elements[array_key_last($elements)]['end'];
$sorted = $this->sortElements($elements);
if ($sorted !== $elements) {
$this->sortTokens($tokens, $i, $endIndex, $sorted);
}
$i = $endIndex;
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
$builtIns = array_keys(array_merge(self::TYPE_HIERARCHY, self::SPECIAL_TYPES));
return new FixerConfigurationResolver([
(new FixerOptionBuilder('order', 'List of strings defining order of elements.'))
->setAllowedTypes(['string[]'])
->setAllowedValues([
static function (array $values) use ($builtIns): bool {
foreach ($values as $value) {
if (\in_array($value, $builtIns, true)) {
return true;
}
if ('method:' === substr($value, 0, 7)) {
return true;
}
}
return false;
},
])
->setDefault([
'use_trait',
'case',
'constant_public',
'constant_protected',
'constant_private',
'property_public',
'property_protected',
'property_private',
'construct',
'destruct',
'magic',
'phpunit',
'method_public',
'method_protected',
'method_private',
])
->getOption(),
(new FixerOptionBuilder('sort_algorithm', 'How multiple occurrences of same type statements should be sorted.'))
->setAllowedValues(self::SUPPORTED_SORT_ALGORITHMS)
->setDefault(self::SORT_NONE)
->getOption(),
(new FixerOptionBuilder('case_sensitive', 'Whether the sorting should be case sensitive.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
/**
* @return list<_ClassElement>
*/
private function getElements(Tokens $tokens, int $startIndex): array
{
++$startIndex;
$elements = [];
while (true) {
$element = [
'start' => $startIndex,
'visibility' => 'public',
'abstract' => false,
'static' => false,
'readonly' => false,
];
for ($i = $startIndex;; ++$i) {
$token = $tokens[$i];
// class end
if ($token->equals('}')) {
return $elements;
}
if ($token->isGivenKind(\T_ABSTRACT)) {
$element['abstract'] = true;
continue;
}
if ($token->isGivenKind(\T_STATIC)) {
$element['static'] = true;
continue;
}
if ($token->isGivenKind(FCT::T_READONLY)) {
$element['readonly'] = true;
}
if ($token->isGivenKind([\T_PROTECTED, \T_PRIVATE])) {
$element['visibility'] = strtolower($token->getContent());
continue;
}
if (!$token->isGivenKind([CT::T_USE_TRAIT, \T_CASE, \T_CONST, \T_VARIABLE, \T_FUNCTION])) {
continue;
}
$type = $this->detectElementType($tokens, $i);
if (\is_array($type)) {
$element['type'] = $type[0];
$element['name'] = $type[1];
} else {
$element['type'] = $type;
}
if ('property' === $element['type']) {
$element['name'] = $tokens[$i]->getContent();
} elseif ('constant' === $element['type']) {
$equalsSignIndex = $tokens->getNextTokenOfKind($i, ['=']);
$element['name'] = $tokens[$tokens->getPrevMeaningfulToken($equalsSignIndex)]->getContent();
} elseif (\in_array($element['type'], ['use_trait', 'case', 'method', 'magic', 'construct', 'destruct'], true)) {
$element['name'] = $tokens[$tokens->getNextMeaningfulToken($i)]->getContent();
}
$element['end'] = $this->findElementEnd($tokens, $i);
break;
}
$elements[] = $element;
$startIndex = $element['end'] + 1;
}
}
/**
* @return list{string, string}|string type or array of type and name
*/
private function detectElementType(Tokens $tokens, int $index)
{
$token = $tokens[$index];
if ($token->isGivenKind(CT::T_USE_TRAIT)) {
return 'use_trait';
}
if ($token->isGivenKind(\T_CASE)) {
return 'case';
}
if ($token->isGivenKind(\T_CONST)) {
return 'constant';
}
if ($token->isGivenKind(\T_VARIABLE)) {
return 'property';
}
$nameToken = $tokens[$tokens->getNextMeaningfulToken($index)];
if ($nameToken->equals([\T_STRING, '__construct'], false)) {
return 'construct';
}
if ($nameToken->equals([\T_STRING, '__destruct'], false)) {
return 'destruct';
}
if (
$nameToken->equalsAny([
[\T_STRING, 'setUpBeforeClass'],
[\T_STRING, 'doSetUpBeforeClass'],
[\T_STRING, 'tearDownAfterClass'],
[\T_STRING, 'doTearDownAfterClass'],
[\T_STRING, 'setUp'],
[\T_STRING, 'doSetUp'],
[\T_STRING, 'assertPreConditions'],
[\T_STRING, 'assertPostConditions'],
[\T_STRING, 'tearDown'],
[\T_STRING, 'doTearDown'],
], false)
) {
return ['phpunit', strtolower($nameToken->getContent())];
}
return str_starts_with($nameToken->getContent(), '__') ? 'magic' : 'method';
}
private function findElementEnd(Tokens $tokens, int $index): int
{
$index = $tokens->getNextTokenOfKind($index, ['(', '{', ';', [CT::T_PROPERTY_HOOK_BRACE_OPEN]]);
if ($tokens[$index]->equals('(')) {
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
$index = $tokens->getNextTokenOfKind($index, ['{', ';']);
}
if ($tokens[$index]->equals('{')) {
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
}
if ($tokens[$index]->isGivenKind(CT::T_PROPERTY_HOOK_BRACE_OPEN)) {
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PROPERTY_HOOK, $index);
}
for (++$index; $tokens[$index]->isWhitespace(" \t") || $tokens[$index]->isComment(); ++$index);
--$index;
return $tokens[$index]->isWhitespace() ? $index - 1 : $index;
}
/**
* @param list<_ClassElement> $elements
*
* @return list<_ClassElement>
*/
private function sortElements(array $elements): array
{
return Utils::stableSort(
$elements,
/**
* @return array{element: _ClassElement, position: int}
*/
fn (array $element): array => ['element' => $element, 'position' => $this->getTypePosition($element)],
/**
* @param array{element: _ClassElement, position: int} $a
* @param array{element: _ClassElement, position: int} $b
*
* @return -1|0|1
*/
fn (array $a, array $b): int => ($a['position'] === $b['position']) ? $this->sortGroupElements($a['element'], $b['element']) : $a['position'] <=> $b['position'],
);
}
/**
* @param _ClassElement $element
*/
private function getTypePosition(array $element): int
{
$type = $element['type'];
if (\in_array($type, ['method', 'magic', 'phpunit'], true) && isset($this->typePosition["method:{$element['name']}"])) {
return $this->typePosition["method:{$element['name']}"];
}
if (\array_key_exists($type, self::SPECIAL_TYPES)) {
if (isset($this->typePosition[$type])) {
$position = $this->typePosition[$type];
if ('phpunit' === $type) {
$position += [
'setupbeforeclass' => 1,
'dosetupbeforeclass' => 2,
'teardownafterclass' => 3,
'doteardownafterclass' => 4,
'setup' => 5,
'dosetup' => 6,
'assertpreconditions' => 7,
'assertpostconditions' => 8,
'teardown' => 9,
'doteardown' => 10,
][$element['name']];
}
return $position;
}
$type = 'method';
}
if (\in_array($type, ['constant', 'property', 'method'], true)) {
$type .= '_'.$element['visibility'];
if ($element['abstract']) {
$type .= '_abstract';
}
if ($element['static']) {
$type .= '_static';
}
if ($element['readonly']) {
$type .= '_readonly';
}
}
return $this->typePosition[$type];
}
/**
* @param _ClassElement $a
* @param _ClassElement $b
*/
private function sortGroupElements(array $a, array $b): int
{
if (self::SORT_ALPHA === $this->configuration['sort_algorithm']) {
return true === $this->configuration['case_sensitive']
? $a['name'] <=> $b['name']
: strcasecmp($a['name'], $b['name']);
}
return $a['start'] <=> $b['start'];
}
/**
* @param list<_ClassElement> $elements
*/
private function sortTokens(Tokens $tokens, int $startIndex, int $endIndex, array $elements): void
{
$replaceTokens = [];
foreach ($elements as $element) {
for ($i = $element['start']; $i <= $element['end']; ++$i) {
$replaceTokens[] = clone $tokens[$i];
}
}
$tokens->overrideRange($startIndex + 1, $endIndex, $replaceTokens);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/NoBlankLinesAfterClassOpeningFixer.php | src/Fixer/ClassNotation/NoBlankLinesAfterClassOpeningFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Ceeram <ceeram@cakephp.org>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoBlankLinesAfterClassOpeningFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds());
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There should be no empty lines after class opening brace.',
[
new CodeSample(
<<<'PHP'
<?php
final class Sample
{
protected function foo()
{
}
}
PHP,
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after OrderedClassElementsFixer, PhpUnitDataProviderMethodOrderFixer.
*/
public function getPriority(): int
{
return 0;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if (!$token->isClassy()) {
continue;
}
$startBraceIndex = $tokens->getNextTokenOfKind($index, ['{']);
if (!$tokens[$startBraceIndex + 1]->isWhitespace()) {
continue;
}
$this->fixWhitespace($tokens, $startBraceIndex + 1);
}
}
/**
* Cleanup a whitespace token.
*/
private function fixWhitespace(Tokens $tokens, int $index): void
{
$content = $tokens[$index]->getContent();
// if there is more than one new line in the whitespace, then we need to fix it
if (substr_count($content, "\n") > 1) {
// the final bit of the whitespace must be the next statement's indentation
$tokens[$index] = new Token([\T_WHITESPACE, $this->whitespacesConfig->getLineEnding().substr($content, (int) strrpos($content, "\n") + 1)]);
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/NoNullPropertyInitializationFixer.php | src/Fixer/ClassNotation/NoNullPropertyInitializationFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author ntzm
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoNullPropertyInitializationFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Properties MUST not be explicitly initialised with `null` except when they have a type declaration (PHP 7.4).',
[
new CodeSample(
<<<'PHP'
<?php
class Foo {
public $bar = null;
public ?string $baz = null;
public ?string $baux;
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
class Foo {
public static $foo = null;
}
PHP,
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([\T_CLASS, \T_TRAIT]) && $tokens->isAnyTokenKindsFound([\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_VAR, \T_STATIC]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$inClass = [];
$classLevel = 0;
for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) {
if ($tokens[$index]->isGivenKind([\T_CLASS, \T_TRAIT])) { // Enums and interfaces do not have properties
++$classLevel;
$inClass[$classLevel] = 1;
$index = $tokens->getNextTokenOfKind($index, ['{']);
continue;
}
if (0 === $classLevel) {
continue;
}
if ($tokens[$index]->equals('{')) {
++$inClass[$classLevel];
continue;
}
if ($tokens[$index]->equals('}')) {
--$inClass[$classLevel];
if (0 === $inClass[$classLevel]) {
unset($inClass[$classLevel]);
--$classLevel;
}
continue;
}
// Ensure we are in a class but not in a method in case there are static variables defined
if (1 !== $inClass[$classLevel]) {
continue;
}
if (!$tokens[$index]->isGivenKind([\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_VAR, \T_STATIC])) {
continue;
}
while (true) {
$varTokenIndex = $index = $tokens->getNextMeaningfulToken($index);
if ($tokens[$index]->isGivenKind(\T_STATIC)) {
$varTokenIndex = $index = $tokens->getNextMeaningfulToken($index);
}
if (!$tokens[$index]->isGivenKind(\T_VARIABLE)) {
break;
}
$index = $tokens->getNextMeaningfulToken($index);
if ($tokens[$index]->equals('=')) {
$index = $tokens->getNextMeaningfulToken($index);
if ($tokens[$index]->isGivenKind(\T_NS_SEPARATOR)) {
$index = $tokens->getNextMeaningfulToken($index);
}
if ($tokens[$index]->equals([\T_STRING, 'null'], false)) {
for ($i = $varTokenIndex + 1; $i <= $index; ++$i) {
if (
!($tokens[$i]->isWhitespace() && str_contains($tokens[$i]->getContent(), "\n"))
&& !$tokens[$i]->isComment()
) {
$tokens->clearAt($i);
}
}
}
++$index;
}
if (!$tokens[$index]->equals(',')) {
break;
}
}
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/NoPhp4ConstructorFixer.php | src/Fixer/ClassNotation/NoPhp4ConstructorFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @phpstan-import-type _PhpTokenPrototypePartial from Token
*
* @author Matteo Beccati <matteo@beccati.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoPhp4ConstructorFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Convert PHP4-style constructors to `__construct`.',
[
new CodeSample(
<<<'PHP'
<?php
class Foo
{
public function Foo($bar)
{
}
}
PHP,
),
],
null,
'Risky when old style constructor being fixed is overridden or overrides parent one.',
);
}
/**
* {@inheritdoc}
*
* Must run before OrderedClassElementsFixer.
*/
public function getPriority(): int
{
return 75;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_CLASS);
}
public function isRisky(): bool
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
$classes = array_keys($tokens->findGivenKind(\T_CLASS));
$numClasses = \count($classes);
for ($i = 0; $i < $numClasses; ++$i) {
$index = $classes[$i];
// is it an anonymous class definition?
if ($tokensAnalyzer->isAnonymousClass($index)) {
continue;
}
// is it inside a namespace?
$nspIndex = $tokens->getPrevTokenOfKind($index, [[\T_NAMESPACE, 'namespace']]);
if (null !== $nspIndex) {
$nspIndex = $tokens->getNextMeaningfulToken($nspIndex);
// make sure it's not the global namespace, as PHP4 constructors are allowed in there
if (!$tokens[$nspIndex]->equals('{')) {
// unless it's the global namespace, the index currently points to the name
$nspIndex = $tokens->getNextTokenOfKind($nspIndex, [';', '{']);
if ($tokens[$nspIndex]->equals(';')) {
// the class is inside a (non-block) namespace, no PHP4-code should be in there
break;
}
// the index points to the { of a block-namespace
$nspEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nspIndex);
if ($index < $nspEnd) {
// the class is inside a block namespace, skip other classes that might be in it
for ($j = $i + 1; $j < $numClasses; ++$j) {
if ($classes[$j] < $nspEnd) {
++$i;
}
}
// and continue checking the classes that might follow
continue;
}
}
}
$classNameIndex = $tokens->getNextMeaningfulToken($index);
$className = $tokens[$classNameIndex]->getContent();
$classStart = $tokens->getNextTokenOfKind($classNameIndex, ['{']);
$classEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classStart);
$this->fixConstructor($tokens, $className, $classStart, $classEnd);
$this->fixParent($tokens, $classStart, $classEnd);
}
}
/**
* Fix constructor within a class, if possible.
*
* @param Tokens $tokens the Tokens instance
* @param string $className the class name
* @param int $classStart the class start index
* @param int $classEnd the class end index
*/
private function fixConstructor(Tokens $tokens, string $className, int $classStart, int $classEnd): void
{
$php4 = $this->findFunction($tokens, $className, $classStart, $classEnd);
if (null === $php4) {
return; // no PHP4-constructor!
}
if (isset($php4['modifiers'][\T_ABSTRACT]) || isset($php4['modifiers'][\T_STATIC])) {
return; // PHP4 constructor can't be abstract or static
}
$php5 = $this->findFunction($tokens, '__construct', $classStart, $classEnd);
if (null === $php5) {
// no PHP5-constructor, we can rename the old one to __construct
$tokens[$php4['nameIndex']] = new Token([\T_STRING, '__construct']);
// in some (rare) cases we might have just created an infinite recursion issue
$this->fixInfiniteRecursion($tokens, $php4['bodyIndex'], $php4['endIndex']);
return;
}
// does the PHP4-constructor only call $this->__construct($args, ...)?
[$sequences, $case] = $this->getWrapperMethodSequence($tokens, '__construct', $php4['startIndex'], $php4['bodyIndex']);
foreach ($sequences as $seq) {
if (null !== $tokens->findSequence($seq, $php4['bodyIndex'] - 1, $php4['endIndex'], $case)) {
// good, delete it!
for ($i = $php4['startIndex']; $i <= $php4['endIndex']; ++$i) {
$tokens->clearAt($i);
}
return;
}
}
// does __construct only call the PHP4-constructor (with the same args)?
[$sequences, $case] = $this->getWrapperMethodSequence($tokens, $className, $php4['startIndex'], $php4['bodyIndex']);
foreach ($sequences as $seq) {
if (null !== $tokens->findSequence($seq, $php5['bodyIndex'] - 1, $php5['endIndex'], $case)) {
// that was a weird choice, but we can safely delete it and...
for ($i = $php5['startIndex']; $i <= $php5['endIndex']; ++$i) {
$tokens->clearAt($i);
}
// rename the PHP4 one to __construct
$tokens[$php4['nameIndex']] = new Token([\T_STRING, '__construct']);
return;
}
}
}
/**
* Fix calls to the parent constructor within a class.
*
* @param Tokens $tokens the Tokens instance
* @param int $classStart the class start index
* @param int $classEnd the class end index
*/
private function fixParent(Tokens $tokens, int $classStart, int $classEnd): void
{
// check calls to the parent constructor
foreach ($tokens->findGivenKind(\T_EXTENDS) as $index => $token) {
$parentIndex = $tokens->getNextMeaningfulToken($index);
$parentClass = $tokens[$parentIndex]->getContent();
// using parent::ParentClassName() or ParentClassName::ParentClassName()
$parentSeq = $tokens->findSequence([
[\T_STRING],
[\T_DOUBLE_COLON],
[\T_STRING, $parentClass],
'(',
], $classStart, $classEnd, [2 => false]);
if (null !== $parentSeq) {
// we only need indices
$parentSeq = array_keys($parentSeq);
// match either of the possibilities
if ($tokens[$parentSeq[0]]->equalsAny([[\T_STRING, 'parent'], [\T_STRING, $parentClass]], false)) {
// replace with parent::__construct
$tokens[$parentSeq[0]] = new Token([\T_STRING, 'parent']);
$tokens[$parentSeq[2]] = new Token([\T_STRING, '__construct']);
}
}
foreach (Token::getObjectOperatorKinds() as $objectOperatorKind) {
// using $this->ParentClassName()
$parentSeq = $tokens->findSequence([
[\T_VARIABLE, '$this'],
[$objectOperatorKind],
[\T_STRING, $parentClass],
'(',
], $classStart, $classEnd, [2 => false]);
if (null !== $parentSeq) {
// we only need indices
$parentSeq = array_keys($parentSeq);
// replace call with parent::__construct()
$tokens[$parentSeq[0]] = new Token([
\T_STRING,
'parent',
]);
$tokens[$parentSeq[1]] = new Token([
\T_DOUBLE_COLON,
'::',
]);
$tokens[$parentSeq[2]] = new Token([\T_STRING, '__construct']);
}
}
}
}
/**
* Fix a particular infinite recursion issue happening when the parent class has __construct and the child has only
* a PHP4 constructor that calls the parent constructor as $this->__construct().
*
* @param Tokens $tokens the Tokens instance
* @param int $start the PHP4 constructor body start
* @param int $end the PHP4 constructor body end
*/
private function fixInfiniteRecursion(Tokens $tokens, int $start, int $end): void
{
foreach (Token::getObjectOperatorKinds() as $objectOperatorKind) {
$seq = [
[\T_VARIABLE, '$this'],
[$objectOperatorKind],
[\T_STRING, '__construct'],
];
while (true) {
$callSeq = $tokens->findSequence($seq, $start, $end, [2 => false]);
if (null === $callSeq) {
return;
}
$callSeq = array_keys($callSeq);
$tokens[$callSeq[0]] = new Token([\T_STRING, 'parent']);
$tokens[$callSeq[1]] = new Token([\T_DOUBLE_COLON, '::']);
}
}
}
/**
* Generate the sequence of tokens necessary for the body of a wrapper method that simply
* calls $this->{$method}( [args...] ) with the same arguments as its own signature.
*
* @param Tokens $tokens the Tokens instance
* @param string $method the wrapped method name
* @param int $startIndex function/method start index
* @param int $bodyIndex function/method body index
*
* @return array{non-empty-list<non-empty-list<_PhpTokenPrototypePartial>>, array{3: false}}
*/
private function getWrapperMethodSequence(Tokens $tokens, string $method, int $startIndex, int $bodyIndex): array
{
$sequences = [];
foreach (Token::getObjectOperatorKinds() as $objectOperatorKind) {
// initialise sequence as { $this->{$method}(
$seq = [
'{',
[\T_VARIABLE, '$this'],
[$objectOperatorKind],
[\T_STRING, $method],
'(',
];
// parse method parameters, if any
$index = $startIndex;
while (true) {
// find the next variable name
$index = $tokens->getNextTokenOfKind($index, [[\T_VARIABLE]]);
if (null === $index || $index >= $bodyIndex) {
// we've reached the body already
break;
}
// append a comma if it's not the first variable
if (\count($seq) > 5) {
$seq[] = ',';
}
// append variable name to the sequence
$seq[] = [\T_VARIABLE, $tokens[$index]->getContent()];
}
// almost done, close the sequence with ); }
$seq[] = ')';
$seq[] = ';';
$seq[] = '}';
$sequences[] = $seq;
}
return [$sequences, [3 => false]];
}
/**
* Find a function or method matching a given name within certain bounds.
*
* Returns:
* - nameIndex (int): The index of the function/method name.
* - startIndex (int): The index of the function/method start.
* - endIndex (int): The index of the function/method end.
* - bodyIndex (int): The index of the function/method body.
* - modifiers (array): The modifiers as array keys and their index as the values, e.g. array(T_PUBLIC => 10)
*
* @param Tokens $tokens the Tokens instance
* @param string $name the function/Method name
* @param int $startIndex the search start index
* @param int $endIndex the search end index
*
* @return null|array{
* nameIndex: int,
* startIndex: int,
* endIndex: int,
* bodyIndex: int,
* modifiers: list<int>,
* }
*/
private function findFunction(Tokens $tokens, string $name, int $startIndex, int $endIndex): ?array
{
$function = $tokens->findSequence([
[\T_FUNCTION],
[\T_STRING, $name],
'(',
], $startIndex, $endIndex, false);
if (null === $function) {
return null;
}
// keep only the indices
$function = array_keys($function);
// find previous block, saving method modifiers for later use
$possibleModifiers = [\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_STATIC, \T_ABSTRACT, \T_FINAL];
$modifiers = [];
$prevBlock = $tokens->getPrevMeaningfulToken($function[0]);
while (null !== $prevBlock && $tokens[$prevBlock]->isGivenKind($possibleModifiers)) {
$modifiers[$tokens[$prevBlock]->getId()] = $prevBlock;
$prevBlock = $tokens->getPrevMeaningfulToken($prevBlock);
}
if (isset($modifiers[\T_ABSTRACT])) {
// abstract methods have no body
$bodyStart = null;
$funcEnd = $tokens->getNextTokenOfKind($function[2], [';']);
} else {
// find method body start and the end of the function definition
$bodyStart = $tokens->getNextTokenOfKind($function[2], ['{']);
$funcEnd = null !== $bodyStart ? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $bodyStart) : null;
}
return [
'nameIndex' => $function[1],
'startIndex' => $prevBlock + 1,
'endIndex' => $funcEnd,
'bodyIndex' => $bodyStart,
'modifiers' => $modifiers,
];
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/OrderedTraitsFixer.php | src/Fixer/ClassNotation/OrderedTraitsFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* case_sensitive?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* case_sensitive: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class OrderedTraitsFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Trait `use` statements must be sorted alphabetically.',
[
new CodeSample("<?php class Foo { \nuse Z; use A; }\n"),
new CodeSample(
"<?php class Foo { \nuse Aaa; use AA; }\n",
[
'case_sensitive' => true,
],
),
],
null,
'Risky when depending on order of the imports.',
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(CT::T_USE_TRAIT);
}
public function isRisky(): bool
{
return true;
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('case_sensitive', 'Whether the sorting should be case sensitive.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($this->findUseStatementsGroups($tokens) as $uses) {
$this->sortUseStatements($tokens, $uses);
}
}
/**
* @return iterable<array<int, Tokens>>
*/
private function findUseStatementsGroups(Tokens $tokens): iterable
{
$uses = [];
for ($index = 1, $max = \count($tokens); $index < $max; ++$index) {
$token = $tokens[$index];
if ($token->isWhitespace() || $token->isComment()) {
continue;
}
if (!$token->isGivenKind(CT::T_USE_TRAIT)) {
if (\count($uses) > 0) {
yield $uses;
$uses = [];
}
continue;
}
$startIndex = $tokens->getNextNonWhitespace($tokens->getPrevMeaningfulToken($index));
\assert(\is_int($startIndex));
$endIndex = $tokens->getNextTokenOfKind($index, [';', '{']);
if ($tokens[$endIndex]->equals('{')) {
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $endIndex);
}
$use = [];
for ($i = $startIndex; $i <= $endIndex; ++$i) {
$use[] = $tokens[$i];
}
$uses[$startIndex] = Tokens::fromArray($use);
$index = $endIndex;
}
}
/**
* @param array<int, Tokens> $uses
*/
private function sortUseStatements(Tokens $tokens, array $uses): void
{
foreach ($uses as $use) {
$this->sortMultipleTraitsInStatement($use);
}
$this->sort($tokens, $uses);
}
private function sortMultipleTraitsInStatement(Tokens $use): void
{
$traits = [];
$indexOfName = null;
$name = [];
for ($index = 0, $max = \count($use); $index < $max; ++$index) {
$token = $use[$index];
if ($token->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) {
$name[] = $token;
if (null === $indexOfName) {
$indexOfName = $index;
}
continue;
}
if ($token->equalsAny([',', ';', '{'])) {
\assert(null !== $indexOfName);
$traits[$indexOfName] = Tokens::fromArray($name);
$name = [];
$indexOfName = null;
}
if ($token->equals('{')) {
$index = $use->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
}
}
$this->sort($use, $traits);
}
/**
* @param array<int, Tokens> $elements
*/
private function sort(Tokens $tokens, array $elements): void
{
$toTraitName = static function (Tokens $use): string {
$string = '';
foreach ($use as $token) {
if ($token->equalsAny([';', '{'])) {
break;
}
if ($token->isGivenKind([\T_NS_SEPARATOR, \T_STRING])) {
$string .= $token->getContent();
}
}
return ltrim($string, '\\');
};
$sortedElements = $elements;
uasort(
$sortedElements,
fn (Tokens $useA, Tokens $useB): int => true === $this->configuration['case_sensitive']
? $toTraitName($useA) <=> $toTraitName($useB)
: strcasecmp($toTraitName($useA), $toTraitName($useB)),
);
$sortedElements = array_combine(
array_keys($elements),
array_values($sortedElements),
);
$beforeOverrideCount = $tokens->count();
foreach (array_reverse($sortedElements, true) as $index => $tokensToInsert) {
$tokens->overrideRange(
$index,
$index + \count($elements[$index]) - 1,
$tokensToInsert,
);
}
if ($beforeOverrideCount < $tokens->count()) {
$tokens->clearEmptyTokens();
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/FinalInternalClassFixer.php | src/Fixer/ClassNotation/FinalInternalClassFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use PhpCsFixer\Utils;
use Symfony\Component\OptionsResolver\Options;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* annotation_exclude?: list<string>,
* annotation_include?: list<string>,
* consider_absent_docblock_as_internal_class?: bool,
* exclude?: list<string>,
* include?: list<string>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* annotation_exclude: array<string, string>,
* annotation_include: array<string, string>,
* consider_absent_docblock_as_internal_class: bool,
* exclude: array<string, string>,
* include: array<string, string>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class FinalInternalClassFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private const DEFAULTS = [
'include' => [
'internal',
],
'exclude' => [
'final',
'Entity',
'ORM\Entity',
'ORM\Mapping\Entity',
'Mapping\Entity',
'Document',
'ODM\Document',
],
];
private const CLASS_CANDIDATE_ACCEPT_TYPES = [
CT::T_ATTRIBUTE_CLOSE,
\T_DOC_COMMENT,
\T_COMMENT, // Skip comments
FCT::T_READONLY,
];
private bool $checkAttributes;
public function __construct()
{
parent::__construct();
$this->checkAttributes = \PHP_VERSION_ID >= 8_00_00;
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Internal classes should be `final`.',
[
new CodeSample("<?php\n/**\n * @internal\n */\nclass Sample\n{\n}\n"),
new CodeSample(
"<?php\n/**\n * @CUSTOM\n */\nclass A{}\n\n/**\n * @CUSTOM\n * @not-fix\n */\nclass B{}\n",
[
'include' => ['@Custom'],
'exclude' => ['@not-fix'],
],
),
],
null,
'Changing classes to `final` might cause code execution to break.',
);
}
/**
* {@inheritdoc}
*
* Must run before ProtectedToPrivateFixer, SelfStaticAccessorFixer.
* Must run after PhpUnitInternalClassFixer.
*/
public function getPriority(): int
{
return 67;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_CLASS);
}
public function isRisky(): bool
{
return true;
}
protected function configurePostNormalisation(): void
{
$this->assertConfigHasNoConflicts();
}
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) || !$this->isClassCandidate($tokensAnalyzer, $tokens, $index)) {
continue;
}
// make class 'final'
$tokens->insertSlices([
$index => [
new Token([\T_FINAL, 'final']),
new Token([\T_WHITESPACE, ' ']),
],
]);
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
$annotationsAsserts = [static function (array $values): bool {
foreach ($values as $value) {
if ('' === $value) {
return false;
}
}
return true;
}];
$annotationsNormalizer = static function (Options $options, array $value): array {
$newValue = [];
foreach ($value as $key) {
if (str_starts_with($key, '@')) {
$key = substr($key, 1);
}
$newValue[strtolower($key)] = true;
}
return $newValue;
};
return new FixerConfigurationResolver([
(new FixerOptionBuilder('annotation_include', 'Class level attribute or annotation tags that must be set in order to fix the class (case insensitive).'))
->setAllowedTypes(['string[]'])
->setAllowedValues($annotationsAsserts)
->setDefault(
array_map(
static fn (string $string) => '@'.$string,
self::DEFAULTS['include'],
),
)
->setNormalizer($annotationsNormalizer)
->setDeprecationMessage('Use `include` to configure PHPDoc annotations tags and attributes.')
->getOption(),
(new FixerOptionBuilder('annotation_exclude', 'Class level attribute or annotation tags that must be omitted to fix the class, even if all of the white list ones are used as well (case insensitive).'))
->setAllowedTypes(['string[]'])
->setAllowedValues($annotationsAsserts)
->setDefault(
array_map(
static fn (string $string) => '@'.$string,
self::DEFAULTS['exclude'],
),
)
->setNormalizer($annotationsNormalizer)
->setDeprecationMessage('Use `exclude` to configure PHPDoc annotations tags and attributes.')
->getOption(),
(new FixerOptionBuilder('include', 'Class level attribute or annotation tags that must be set in order to fix the class (case insensitive).'))
->setAllowedTypes(['string[]'])
->setAllowedValues($annotationsAsserts)
->setDefault(self::DEFAULTS['include'])
->setNormalizer($annotationsNormalizer)
->getOption(),
(new FixerOptionBuilder('exclude', 'Class level attribute or annotation tags that must be omitted to fix the class, even if all of the white list ones are used as well (case insensitive).'))
->setAllowedTypes(['string[]'])
->setAllowedValues($annotationsAsserts)
->setDefault(self::DEFAULTS['exclude'])
->setNormalizer($annotationsNormalizer)
->getOption(),
(new FixerOptionBuilder('consider_absent_docblock_as_internal_class', 'Whether classes without any DocBlock should be fixed to final.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
/**
* @param int $index T_CLASS index
*/
private function isClassCandidate(TokensAnalyzer $tokensAnalyzer, Tokens $tokens, int $index): bool
{
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
}
$decisions = [];
$currentIndex = $index;
while (null !== $currentIndex) {
$currentIndex = $tokens->getPrevNonWhitespace($currentIndex);
if (!$tokens[$currentIndex]->isGivenKind(self::CLASS_CANDIDATE_ACCEPT_TYPES)) {
break;
}
if ($this->checkAttributes && $tokens[$currentIndex]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) {
$attributeStartIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $currentIndex);
$decisions[] = $this->isClassCandidateBasedOnAttribute($tokens, $attributeStartIndex, $currentIndex);
$currentIndex = $attributeStartIndex;
}
if ($tokens[$currentIndex]->isGivenKind(\T_DOC_COMMENT)) {
$decisions[] = $this->isClassCandidateBasedOnPhpDoc($tokens, $currentIndex);
}
}
if (\in_array(false, $decisions, true)) {
return false;
}
return \in_array(true, $decisions, true)
|| ([] === $decisions && true === $this->configuration['consider_absent_docblock_as_internal_class']);
}
private function isClassCandidateBasedOnPhpDoc(Tokens $tokens, int $index): ?bool
{
$doc = new DocBlock($tokens[$index]->getContent());
$tags = [];
foreach ($doc->getAnnotations() as $annotation) {
if (!Preg::match('/@([^\(\s]+)/', $annotation->getContent(), $matches)) {
continue;
}
$tag = strtolower(substr(array_shift($matches), 1));
$tags[$tag] = true;
}
if (\count(array_intersect_key($this->configuration['exclude'], $tags)) > 0) {
return false;
}
if ($this->isConfiguredAsInclude($tags)) {
return true;
}
return null;
}
private function isClassCandidateBasedOnAttribute(Tokens $tokens, int $startIndex, int $endIndex): ?bool
{
$attributeCandidates = [];
$attributeString = '';
$currentIndex = $startIndex;
while ($currentIndex < $endIndex && null !== ($currentIndex = $tokens->getNextMeaningfulToken($currentIndex))) {
if (!$tokens[$currentIndex]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) {
if ('' !== $attributeString) {
$attributeCandidates[$attributeString] = true;
$attributeString = '';
}
continue;
}
$attributeString .= strtolower($tokens[$currentIndex]->getContent());
}
if (\count(array_intersect_key($this->configuration['exclude'], $attributeCandidates)) > 0) {
return false;
}
if ($this->isConfiguredAsInclude($attributeCandidates)) {
return true;
}
return null;
}
/**
* @param array<string, bool> $attributes
*/
private function isConfiguredAsInclude(array $attributes): bool
{
if (0 === \count($this->configuration['include'])) {
return true;
}
return \count(array_intersect_key($this->configuration['include'], $attributes)) > 0;
}
private function assertConfigHasNoConflicts(): void
{
foreach (['include' => 'annotation_include', 'exclude' => 'annotation_exclude'] as $newConfigKey => $oldConfigKey) {
$defaults = [];
foreach (self::DEFAULTS[$newConfigKey] as $foo) {
$defaults[strtolower($foo)] = true;
}
$newConfigIsSet = $this->configuration[$newConfigKey] !== $defaults;
$oldConfigIsSet = $this->configuration[$oldConfigKey] !== $defaults;
if ($newConfigIsSet && $oldConfigIsSet) {
throw new InvalidFixerConfigurationException($this->getName(), \sprintf('Configuration cannot contain deprecated option "%s" and new option "%s".', $oldConfigKey, $newConfigKey));
}
if ($oldConfigIsSet) {
$this->configuration[$newConfigKey] = $this->configuration[$oldConfigKey]; // @phpstan-ignore-line crazy mapping, to be removed while cleaning up deprecated options
$this->checkAttributes = false; // run in old mode
}
// if ($newConfigIsSet) - only new config is set, all good
// if (!$newConfigIsSet && !$oldConfigIsSet) - both are set as to default values, all good
unset($this->configuration[$oldConfigKey]); // @phpstan-ignore-line crazy mapping, to be removed while cleaning up deprecated options
}
$intersect = array_intersect_assoc($this->configuration['include'], $this->configuration['exclude']);
if (\count($intersect) > 0) {
throw new InvalidFixerConfigurationException($this->getName(), \sprintf('Annotation cannot be used in both "include" and "exclude" list, got duplicates: %s.', Utils::naturalLanguageJoin(array_keys($intersect))));
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/ModifierKeywordsFixer.php | src/Fixer/ClassNotation/ModifierKeywordsFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* Fixer for rules defined in PSR2 ¶4.3, ¶4.5.
*
* @phpstan-type _AutogeneratedInputConfiguration array{
* elements?: list<'const'|'method'|'property'>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* elements: list<'const'|'method'|'property'>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ModifierKeywordsFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private const PROPERTY_TYPE_DECLARATION_KINDS = [\T_STRING, \T_NS_SEPARATOR, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE];
private const EXPECTED_KINDS_GENERIC = [\T_ABSTRACT, \T_FINAL, \T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC, \T_VAR, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET];
private const EXPECTED_KINDS_PROPERTY_KINDS = [...self::EXPECTED_KINDS_GENERIC, ...self::PROPERTY_TYPE_DECLARATION_KINDS];
/**
* @var list<'const'|'method'|'promoted_property'|'property'>
*/
private array $elements = ['const', 'method', 'property'];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Classes, constants, properties, and methods MUST have visibility declared, and keyword modifiers MUST be in the following order:'
.' inheritance modifier (`abstract` or `final`),'
.' visibility modifier (`public`, `protected`, or `private`),'
.' set-visibility modifier (`public(set)`, `protected(set)`, or `private(set)`),'
.' scope modifier (`static`),'
.' mutation modifier (`readonly`),'
.' type declaration, name.',
[
new CodeSample(
<<<'PHP'
<?php
abstract class ClassName
{
const SAMPLE = 1;
var $a;
protected string $foo;
static protected int $beep;
static public final function bar() {}
protected abstract function zim();
function zex() {}
}
PHP,
),
new VersionSpecificCodeSample(
<<<'PHP'
<?php
abstract class ClassName
{
const SAMPLE = 1;
var $a;
readonly protected string $foo;
static protected int $beep;
static public final function bar() {}
protected abstract function zim();
function zex() {}
}
readonly final class ValueObject
{
// ...
}
PHP,
new VersionSpecification(8_02_00),
),
new VersionSpecificCodeSample(
<<<'PHP'
<?php
abstract class ClassName
{
const SAMPLE = 1;
var $a;
protected abstract string $bar { get => "a"; set; }
readonly final protected string $foo;
static protected final int $beep;
static public final function bar() {}
protected abstract function zim();
function zex() {}
}
readonly final class ValueObject
{
// ...
}
PHP,
new VersionSpecification(8_04_00),
),
new CodeSample(
<<<'PHP'
<?php
class Sample
{
const SAMPLE = 1;
}
PHP,
['elements' => ['const']],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before ClassAttributesSeparationFixer.
*/
public function getPriority(): int
{
return 56;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds());
}
/**
* @protected
*
* @TODO 4.0 move visibility from annotation to code when `VisibilityRequiredFixer` is removed
*/
public function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
$elements = ['const', 'method', 'property'];
return new FixerConfigurationResolver([
(new FixerOptionBuilder('elements', 'The structural elements to fix.'))
->setAllowedTypes(['string[]'])
->setAllowedValues([new AllowedValueSubset($elements)])
->setDefault($elements)
->getOption(),
]);
}
protected function configurePostNormalisation(): void
{
$this->elements = $this->configuration['elements'];
if (\in_array('property', $this->elements, true)) {
$this->elements[] = 'promoted_property';
}
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
foreach (array_reverse($tokensAnalyzer->getClassyElements(), true) as $index => $element) {
if (!\in_array($element['type'], $this->elements, true)) {
continue;
}
$abstractFinalIndex = null;
$visibilityIndex = null;
$visibilitySetIndex = null;
$staticIndex = null;
$typeIndex = null;
$readOnlyIndex = null;
$prevIndex = $tokens->getPrevMeaningfulToken($index);
$expectedKinds = 'property' === $element['type'] || 'promoted_property' === $element['type']
? self::EXPECTED_KINDS_PROPERTY_KINDS
: self::EXPECTED_KINDS_GENERIC;
while ($tokens[$prevIndex]->isGivenKind($expectedKinds) || $tokens[$prevIndex]->equals('&')) {
if ($tokens[$prevIndex]->isGivenKind([\T_ABSTRACT, \T_FINAL])) {
$abstractFinalIndex = $prevIndex;
} elseif ($tokens[$prevIndex]->isGivenKind(\T_STATIC)) {
$staticIndex = $prevIndex;
} elseif ($tokens[$prevIndex]->isGivenKind(FCT::T_READONLY)) {
$readOnlyIndex = $prevIndex;
} elseif ($tokens[$prevIndex]->isGivenKind([FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET])) {
$visibilitySetIndex = $prevIndex;
} elseif ($tokens[$prevIndex]->isGivenKind(self::PROPERTY_TYPE_DECLARATION_KINDS)) {
$typeIndex = $prevIndex;
} elseif (!$tokens[$prevIndex]->equals('&')) {
$visibilityIndex = $prevIndex;
}
$prevIndex = $tokens->getPrevMeaningfulToken($prevIndex);
}
if (null !== $typeIndex) {
$index = $typeIndex;
}
if ('property' === $element['type'] && $tokens[$prevIndex]->equals(',')) {
continue;
}
$swapIndex = $staticIndex ?? $readOnlyIndex; // "static" property cannot be "readonly", so there can always be at most one swap
if (null !== $swapIndex) {
if ($this->isKeywordPlacedProperly($tokens, $swapIndex, $index)) {
$index = $swapIndex;
} else {
$this->moveTokenAndEnsureSingleSpaceFollows($tokens, $swapIndex, $index);
}
}
if (null !== $visibilitySetIndex) {
if ($this->isKeywordPlacedProperly($tokens, $visibilitySetIndex, $index)) {
$index = $visibilitySetIndex;
} else {
$this->moveTokenAndEnsureSingleSpaceFollows($tokens, $visibilitySetIndex, $index);
}
}
if (null === $visibilityIndex) {
$tokens->insertAt($index, [new Token(['promoted_property' === $element['type'] ? CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC : \T_PUBLIC, 'public']), new Token([\T_WHITESPACE, ' '])]);
} else {
if ($tokens[$visibilityIndex]->isGivenKind(\T_VAR)) {
$tokens[$visibilityIndex] = new Token([\T_PUBLIC, 'public']);
}
if ($this->isKeywordPlacedProperly($tokens, $visibilityIndex, $index)) {
$index = $visibilityIndex;
} else {
$this->moveTokenAndEnsureSingleSpaceFollows($tokens, $visibilityIndex, $index);
}
}
if (null === $abstractFinalIndex) {
continue;
}
if ($this->isKeywordPlacedProperly($tokens, $abstractFinalIndex, $index)) {
continue;
}
$this->moveTokenAndEnsureSingleSpaceFollows($tokens, $abstractFinalIndex, $index);
}
}
private function isKeywordPlacedProperly(Tokens $tokens, int $keywordIndex, int $comparedIndex): bool
{
return ' ' === $tokens[$keywordIndex + 1]->getContent()
&& (
$keywordIndex + 2 === $comparedIndex
|| $keywordIndex + 3 === $comparedIndex && $tokens[$keywordIndex + 2]->equals('&')
);
}
private function moveTokenAndEnsureSingleSpaceFollows(Tokens $tokens, int $fromIndex, int $toIndex): void
{
$tokens->insertAt($toIndex, [$tokens[$fromIndex], new Token([\T_WHITESPACE, ' '])]);
$tokens->clearAt($fromIndex);
if ($tokens[$fromIndex + 1]->isWhitespace()) {
$tokens->clearAt($fromIndex + 1);
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/SingleClassElementPerStatementFixer.php | src/Fixer/ClassNotation/SingleClassElementPerStatementFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* Fixer for rules defined in PSR2 ¶4.2.
*
* @phpstan-type _AutogeneratedInputConfiguration array{
* elements?: list<'const'|'property'>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* elements: list<'const'|'property'>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Javier Spagnoletti <phansys@gmail.com>
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class SingleClassElementPerStatementFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds());
}
/**
* {@inheritdoc}
*
* Must run before ClassAttributesSeparationFixer.
*/
public function getPriority(): int
{
return 56;
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There MUST NOT be more than one property or constant declared per statement.',
[
new CodeSample(
<<<'PHP'
<?php
final class Example
{
const FOO_1 = 1, FOO_2 = 2;
private static $bar1 = array(1,2,3), $bar2 = [1,2,3];
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
final class Example
{
const FOO_1 = 1, FOO_2 = 2;
private static $bar1 = array(1,2,3), $bar2 = [1,2,3];
}
PHP,
['elements' => ['property']],
),
],
);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$analyzer = new TokensAnalyzer($tokens);
$elements = array_reverse($analyzer->getClassyElements(), true);
foreach ($elements as $index => $element) {
if (!\in_array($element['type'], $this->configuration['elements'], true)) {
continue; // not in configuration
}
$this->fixElement($tokens, $element['type'], $index);
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
$values = ['const', 'property'];
return new FixerConfigurationResolver([
(new FixerOptionBuilder('elements', 'List of strings which element should be modified.'))
->setDefault($values)
->setAllowedTypes(['string[]'])
->setAllowedValues([new AllowedValueSubset($values)])
->getOption(),
]);
}
private function fixElement(Tokens $tokens, string $type, int $index): void
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
$repeatIndex = $index;
while (true) {
$repeatIndex = $tokens->getNextMeaningfulToken($repeatIndex);
$repeatToken = $tokens[$repeatIndex];
if ($tokensAnalyzer->isArray($repeatIndex)) {
if ($repeatToken->isGivenKind(\T_ARRAY)) {
$repeatIndex = $tokens->getNextTokenOfKind($repeatIndex, ['(']);
$repeatIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $repeatIndex);
} else {
$repeatIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $repeatIndex);
}
continue;
}
if ($repeatToken->equalsAny([';', [CT::T_PROPERTY_HOOK_BRACE_OPEN]])) {
return; // no repeating found, no fixing needed
}
if ($repeatToken->equals(',')) {
break;
}
}
$start = $tokens->getPrevTokenOfKind($index, [';', '{', '}']);
$this->expandElement(
$tokens,
$type,
$tokens->getNextMeaningfulToken($start),
$tokens->getNextTokenOfKind($index, [';']),
);
}
private function expandElement(Tokens $tokens, string $type, int $startIndex, int $endIndex): void
{
$divisionContent = null;
if ($tokens[$startIndex - 1]->isWhitespace()) {
$divisionContent = $tokens[$startIndex - 1]->getContent();
if (Preg::match('#(\n|\r\n)#', $divisionContent, $matches)) {
$divisionContent = $matches[0].trim($divisionContent, "\r\n");
}
}
// iterate variables to split up
for ($i = $endIndex - 1; $i > $startIndex; --$i) {
$token = $tokens[$i];
if ($token->equals(')')) {
$i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $i);
continue;
}
if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_CLOSE)) {
$i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $i);
continue;
}
if (!$tokens[$i]->equals(',')) {
continue;
}
$tokens[$i] = new Token(';');
if ($tokens[$i + 1]->isWhitespace()) {
$tokens->clearAt($i + 1);
}
if (null !== $divisionContent && '' !== $divisionContent) {
$tokens->insertAt($i + 1, new Token([\T_WHITESPACE, $divisionContent]));
}
// collect modifiers
$sequence = $this->getModifiersSequences($tokens, $type, $startIndex, $endIndex);
$tokens->insertAt($i + 2, $sequence);
}
}
/**
* @return list<Token>
*/
private function getModifiersSequences(Tokens $tokens, string $type, int $startIndex, int $endIndex): array
{
if ('property' === $type) {
$tokenKinds = [\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_STATIC, \T_VAR, \T_STRING, \T_NS_SEPARATOR, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET];
} else {
$tokenKinds = [\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_CONST];
}
$sequence = [];
for ($i = $startIndex; $i < $endIndex - 1; ++$i) {
if ($tokens[$i]->isComment()) {
continue;
}
if (!$tokens[$i]->isWhitespace() && !$tokens[$i]->isGivenKind($tokenKinds)) {
break;
}
$sequence[] = clone $tokens[$i];
}
return $sequence;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/SingleTraitInsertPerStatementFixer.php | src/Fixer/ClassNotation/SingleTraitInsertPerStatementFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class SingleTraitInsertPerStatementFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Each trait `use` must be done as single statement.',
[
new CodeSample(
<<<'PHP'
<?php
final class Example
{
use Foo, Bar;
}
PHP,
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before BracesFixer, SpaceAfterSemicolonFixer.
*/
public function getPriority(): int
{
return 36;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(CT::T_USE_TRAIT);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = \count($tokens) - 1; 1 < $index; --$index) {
if ($tokens[$index]->isGivenKind(CT::T_USE_TRAIT)) {
$candidates = $this->getCandidates($tokens, $index);
if (\count($candidates) > 0) {
$this->fixTraitUse($tokens, $index, $candidates);
}
}
}
}
/**
* @param list<int> $candidates ',' indices to fix
*/
private function fixTraitUse(Tokens $tokens, int $useTraitIndex, array $candidates): void
{
foreach ($candidates as $commaIndex) {
$inserts = [
new Token([CT::T_USE_TRAIT, 'use']),
new Token([\T_WHITESPACE, ' ']),
];
$nextImportStartIndex = $tokens->getNextMeaningfulToken($commaIndex);
if ($tokens[$nextImportStartIndex - 1]->isWhitespace()) {
if (Preg::match('/\R/', $tokens[$nextImportStartIndex - 1]->getContent())) {
array_unshift($inserts, clone $tokens[$useTraitIndex - 1]);
}
$tokens->clearAt($nextImportStartIndex - 1);
}
$tokens[$commaIndex] = new Token(';');
$tokens->insertAt($nextImportStartIndex, $inserts);
}
}
/**
* @return list<int>
*/
private function getCandidates(Tokens $tokens, int $index): array
{
$indices = [];
$index = $tokens->getNextTokenOfKind($index, [',', ';', '{']);
while (!$tokens[$index]->equals(';')) {
if ($tokens[$index]->equals('{')) {
return []; // do not fix use cases with grouping
}
$indices[] = $index;
$index = $tokens->getNextTokenOfKind($index, [',', ';', '{']);
}
return array_reverse($indices);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/OrderedTypesFixer.php | src/Fixer/ClassNotation/OrderedTypesFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Future;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* case_sensitive?: bool,
* null_adjustment?: 'always_first'|'always_last'|'none',
* sort_algorithm?: 'alpha'|'none',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* case_sensitive: bool,
* null_adjustment: 'always_first'|'always_last'|'none',
* sort_algorithm: 'alpha'|'none',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author John Paul E. Balandan, CPA <paulbalandan@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class OrderedTypesFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private const PROPERTY_MODIFIERS = [\T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC, \T_VAR, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Sort union types and intersection types using configured order.',
[
new CodeSample(
<<<'PHP'
<?php
try {
cache()->save($foo);
} catch (\RuntimeException|CacheException $e) {
logger($e);
throw $e;
}
PHP,
),
new VersionSpecificCodeSample(
<<<'PHP'
<?php
interface Foo
{
public function bar(\Aaa|\AA $foo): string|int;
}
PHP,
new VersionSpecification(8_00_00),
[
'case_sensitive' => true,
],
),
new VersionSpecificCodeSample(
<<<'PHP'
<?php
interface Foo
{
public function bar(null|string|int $foo): string|int;
public function foo(\Stringable&\Countable $obj): int;
}
PHP,
new VersionSpecification(8_01_00),
['null_adjustment' => 'always_last'],
),
new VersionSpecificCodeSample(
<<<'PHP'
<?php
interface Bar
{
public function bar(null|string|int $foo): string|int;
}
PHP,
new VersionSpecification(8_00_00),
[
'sort_algorithm' => 'none',
'null_adjustment' => 'always_last',
],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before TypesSpacesFixer.
* Must run after NullableTypeDeclarationFixer, NullableTypeDeclarationForDefaultNullValueFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION]);
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('sort_algorithm', 'Whether the types should be sorted alphabetically, or not sorted.'))
->setAllowedValues(['alpha', 'none'])
->setDefault('alpha')
->getOption(),
(new FixerOptionBuilder('null_adjustment', 'Forces the position of `null` (overrides `sort_algorithm`).'))
->setAllowedValues(['always_first', 'always_last', 'none'])
->setDefault(
Future::getV4OrV3(
'always_last', // as recommended in https://github.com/php-fig/per-coding-style/blob/master/migration-3.0.md#section-25---keywords-and-types
'always_first',
),
)
->getOption(),
(new FixerOptionBuilder('case_sensitive', 'Whether the sorting should be case sensitive.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$functionsAnalyzer = new FunctionsAnalyzer();
foreach ($this->getElements($tokens) as $index => $type) {
if ('catch' === $type) {
$this->fixCatchArgumentType($tokens, $index);
continue;
}
if ('property' === $type) {
$this->fixPropertyType($tokens, $index);
continue;
}
$this->fixMethodArgumentType($functionsAnalyzer, $tokens, $index);
$this->fixMethodReturnType($functionsAnalyzer, $tokens, $index);
}
}
/**
* @return array<int, string>
*
* @phpstan-return array<int, 'catch'|'method'|'property'>
*/
private function getElements(Tokens $tokens): array
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
$elements = array_map(
static fn (array $element): string => $element['type'],
array_filter(
$tokensAnalyzer->getClassyElements(),
static fn (array $element): bool => \in_array($element['type'], ['method', 'property'], true),
),
);
foreach ($tokens as $index => $token) {
if ($token->isGivenKind(\T_CATCH)) {
$elements[$index] = 'catch';
continue;
}
if (
$token->isGivenKind(\T_FN)
|| ($token->isGivenKind(\T_FUNCTION) && !isset($elements[$index]))
) {
$elements[$index] = 'method';
}
}
return $elements;
}
private function collectTypeAnalysis(Tokens $tokens, int $startIndex, int $endIndex): ?TypeAnalysis
{
$type = '';
$typeStartIndex = $tokens->getNextMeaningfulToken($startIndex);
$typeEndIndex = $typeStartIndex;
for ($i = $typeStartIndex; $i < $endIndex; ++$i) {
if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) {
continue;
}
$type .= $tokens[$i]->getContent();
$typeEndIndex = $i;
}
return '' !== $type ? new TypeAnalysis($type, $typeStartIndex, $typeEndIndex) : null;
}
private function fixCatchArgumentType(Tokens $tokens, int $index): void
{
$catchStart = $tokens->getNextTokenOfKind($index, ['(']);
$catchEnd = $tokens->getNextTokenOfKind($catchStart, [')', [\T_VARIABLE]]);
$catchArgumentType = $this->collectTypeAnalysis($tokens, $catchStart, $catchEnd);
if (null === $catchArgumentType || !$this->isTypeSortable($catchArgumentType)) {
return; // nothing to fix
}
$this->sortTypes($catchArgumentType, $tokens);
}
private function fixPropertyType(Tokens $tokens, int $index): void
{
$propertyIndex = $index;
do {
$index = $tokens->getPrevMeaningfulToken($index);
} while (!$tokens[$index]->isGivenKind(self::PROPERTY_MODIFIERS));
$propertyType = $this->collectTypeAnalysis($tokens, $index, $propertyIndex);
if (null === $propertyType || !$this->isTypeSortable($propertyType)) {
return; // nothing to fix
}
$this->sortTypes($propertyType, $tokens);
}
private function fixMethodArgumentType(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index): void
{
foreach ($functionsAnalyzer->getFunctionArguments($tokens, $index) as $argumentInfo) {
$argumentType = $argumentInfo->getTypeAnalysis();
if (null === $argumentType || !$this->isTypeSortable($argumentType)) {
continue; // nothing to fix
}
$this->sortTypes($argumentType, $tokens);
}
}
private function fixMethodReturnType(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index): void
{
$returnType = $functionsAnalyzer->getFunctionReturnType($tokens, $index);
if (null === $returnType || !$this->isTypeSortable($returnType)) {
return; // nothing to fix
}
$this->sortTypes($returnType, $tokens);
}
private function sortTypes(TypeAnalysis $typeAnalysis, Tokens $tokens): void
{
$type = $typeAnalysis->getName();
if (str_contains($type, '|') && str_contains($type, '&')) {
// a DNF type of the form (A&B)|C, available as of PHP 8.2
[$originalTypes, $glue] = $this->collectDisjunctiveNormalFormTypes($type);
} else {
[$originalTypes, $glue] = $this->collectUnionOrIntersectionTypes($type);
}
// If the $types array is coming from a DNF type, then we have parts
// which are also array. If so, we sort those sub-types first before
// running the sorting algorithm to the entire $types array.
$sortedTypes = array_map(function ($subType) {
if (\is_array($subType)) {
return $this->runTypesThroughSortingAlgorithm($subType);
}
return $subType;
}, $originalTypes);
$sortedTypes = $this->runTypesThroughSortingAlgorithm($sortedTypes);
if ($sortedTypes === $originalTypes) {
return;
}
$tokens->overrideRange(
$typeAnalysis->getStartIndex(),
$typeAnalysis->getEndIndex(),
$this->createTypeDeclarationTokens($sortedTypes, $glue),
);
}
private function isTypeSortable(TypeAnalysis $type): bool
{
return str_contains($type->getName(), '|') || str_contains($type->getName(), '&');
}
/**
* @return array{0: non-empty-list<non-empty-list<string>|string>, 1: string}
*/
private function collectDisjunctiveNormalFormTypes(string $type): array
{
$types = array_map(static function (string $subType) {
if (str_starts_with($subType, '(')) {
return explode('&', trim($subType, '()'));
}
return $subType;
}, explode('|', $type));
return [$types, '|'];
}
/**
* @return array{0: non-empty-list<string>, 1: string}
*/
private function collectUnionOrIntersectionTypes(string $type): array
{
$types = explode('|', $type);
$glue = '|';
if (1 === \count($types)) {
$types = explode('&', $type);
$glue = '&';
}
return [$types, $glue];
}
/**
* @param list<list<string>|string> $types
*
* @return ($types is list<string> ? list<string> : list<list<string>>)
*/
private function runTypesThroughSortingAlgorithm(array $types): array
{
$normalizeType = static fn (string $type): string => Preg::replace('/^\\\?/', '', $type);
usort($types, function ($a, $b) use ($normalizeType): int {
if (\is_array($a)) {
$a = implode('&', $a);
}
if (\is_array($b)) {
$b = implode('&', $b);
}
$a = $normalizeType($a);
$b = $normalizeType($b);
$lowerCaseA = strtolower($a);
$lowerCaseB = strtolower($b);
if ('none' !== $this->configuration['null_adjustment']) {
if ('null' === $lowerCaseA && 'null' !== $lowerCaseB) {
return 'always_last' === $this->configuration['null_adjustment'] ? 1 : -1;
}
if ('null' !== $lowerCaseA && 'null' === $lowerCaseB) {
return 'always_last' === $this->configuration['null_adjustment'] ? -1 : 1;
}
}
if ('alpha' === $this->configuration['sort_algorithm']) {
return true === $this->configuration['case_sensitive'] ? $a <=> $b : strcasecmp($a, $b);
}
return 0;
});
return $types;
}
/**
* @param list<list<string>|string> $types
*
* @return list<Token>
*/
private function createTypeDeclarationTokens(array $types, string $glue, bool $isDisjunctive = false): array
{
$specialTypes = [
'array' => [CT::T_ARRAY_TYPEHINT, 'array'],
'callable' => [\T_CALLABLE, 'callable'],
'static' => [\T_STATIC, 'static'],
];
$count = \count($types);
$newTokens = [];
foreach ($types as $i => $type) {
if (\is_array($type)) {
$newTokens = [
...$newTokens,
...$this->createTypeDeclarationTokens($type, '&', true),
];
} elseif (isset($specialTypes[$type])) {
$newTokens[] = new Token($specialTypes[$type]);
} else {
foreach (explode('\\', $type) as $nsIndex => $value) {
if (0 === $nsIndex && '' === $value) {
continue;
}
if ($nsIndex > 0) {
$newTokens[] = new Token([\T_NS_SEPARATOR, '\\']);
}
$newTokens[] = new Token([\T_STRING, $value]);
}
}
if ($i <= $count - 2) {
$newTokens[] = new Token([
'|' => [CT::T_TYPE_ALTERNATION, '|'],
'&' => [CT::T_TYPE_INTERSECTION, '&'],
][$glue]);
}
}
if ($isDisjunctive) {
array_unshift($newTokens, new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, '(']));
$newTokens[] = new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, ')']);
}
return $newTokens;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/PhpdocReadonlyClassCommentToKeywordFixer.php | src/Fixer/ClassNotation/PhpdocReadonlyClassCommentToKeywordFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Marcel Behrmann <marcel@behrmann.dev>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class PhpdocReadonlyClassCommentToKeywordFixer extends AbstractFixer
{
/**
* {@inheritdoc}
*
* Must run before NoEmptyPhpdocFixer, NoExtraBlankLinesFixer, PhpdocAlignFixer.
* Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer.
*/
public function getPriority(): int
{
return 4;
}
public function isCandidate(Tokens $tokens): bool
{
return \PHP_VERSION_ID >= 8_02_00 && $tokens->isTokenKindFound(\T_DOC_COMMENT);
}
public function isRisky(): bool
{
return true;
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Converts readonly comment on classes to the readonly keyword.',
[
new VersionSpecificCodeSample(
<<<EOT
<?php
/** @readonly */
class C {
}\n
EOT,
new VersionSpecification(8_02_00),
),
],
null,
'If classes marked with `@readonly` annotation were extended anyway, applying this fixer may break the inheritance for their child classes.',
);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(\T_DOC_COMMENT)) {
continue;
}
$doc = new DocBlock($token->getContent());
$annotations = $doc->getAnnotationsOfType('readonly');
if (0 === \count($annotations)) {
continue;
}
foreach ($annotations as $annotation) {
$annotation->remove();
}
$mainIndex = $index;
$index = $tokens->getNextMeaningfulToken($index);
$addReadonly = true;
while ($tokens[$index]->isGivenKind([
\T_ABSTRACT,
\T_FINAL,
\T_PRIVATE,
\T_PUBLIC,
\T_PROTECTED,
\T_READONLY,
])) {
if ($tokens[$index]->isGivenKind(\T_READONLY)) {
$addReadonly = false;
}
$index = $tokens->getNextMeaningfulToken($index);
}
if (!$tokens[$index]->isGivenKind(\T_CLASS)) {
continue;
}
if ($addReadonly) {
$tokens->insertAt($index, [new Token([\T_READONLY, 'readonly']), new Token([\T_WHITESPACE, ' '])]);
}
$newContent = $doc->getContent();
if ('' === $newContent) {
$tokens->clearTokenAndMergeSurroundingWhitespace($mainIndex);
continue;
}
$tokens[$mainIndex] = new Token([\T_DOC_COMMENT, $doc->getContent()]);
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassNotation/SelfStaticAccessorFixer.php | src/Fixer/ClassNotation/SelfStaticAccessorFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\ClassNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class SelfStaticAccessorFixer extends AbstractFixer
{
private const CLASSY_TYPES = [\T_CLASS, FCT::T_ENUM];
private const CLASSY_TOKENS_OF_INTEREST = [[\T_CLASS], [FCT::T_ENUM]];
private TokensAnalyzer $tokensAnalyzer;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Inside an enum or `final`/anonymous class, `self` should be preferred over `static`.',
[
new CodeSample(
<<<'PHP'
<?php
final class Sample
{
private static $A = 1;
public function getBar()
{
return static::class.static::test().static::$A;
}
private static function test()
{
return 'test';
}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
final class Foo
{
public function bar()
{
return new static();
}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
final class Foo
{
public function isBar()
{
return $foo instanceof static;
}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
$a = new class() {
public function getBar()
{
return static::class;
}
};
PHP,
),
new VersionSpecificCodeSample(
<<<'PHP'
<?php
enum Foo
{
public const A = 123;
public static function bar(): void
{
echo static::A;
}
}
PHP,
new VersionSpecification(8_01_00),
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_STATIC)
&& $tokens->isAnyTokenKindsFound(self::CLASSY_TYPES)
&& $tokens->isAnyTokenKindsFound([\T_DOUBLE_COLON, \T_NEW, \T_INSTANCEOF]);
}
/**
* {@inheritdoc}
*
* Must run after FinalClassFixer, FinalInternalClassFixer, FunctionToConstantFixer, PhpUnitTestCaseStaticMethodCallsFixer.
*/
public function getPriority(): int
{
return -10;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$this->tokensAnalyzer = new TokensAnalyzer($tokens);
$classyIndex = $tokens->getNextTokenOfKind(0, self::CLASSY_TOKENS_OF_INTEREST);
while (null !== $classyIndex) {
if ($tokens[$classyIndex]->isGivenKind(\T_CLASS)) {
$modifiers = $this->tokensAnalyzer->getClassyModifiers($classyIndex);
if (
isset($modifiers['final'])
|| $this->tokensAnalyzer->isAnonymousClass($classyIndex)
) {
$classyIndex = $this->fixClassy($tokens, $classyIndex);
}
} else {
$classyIndex = $this->fixClassy($tokens, $classyIndex);
}
$classyIndex = $tokens->getNextTokenOfKind($classyIndex, self::CLASSY_TOKENS_OF_INTEREST);
}
}
private function fixClassy(Tokens $tokens, int $index): int
{
$index = $tokens->getNextTokenOfKind($index, ['{']);
$classOpenCount = 1;
while ($classOpenCount > 0) {
++$index;
if ($tokens[$index]->equals('{')) {
++$classOpenCount;
continue;
}
if ($tokens[$index]->equals('}')) {
--$classOpenCount;
continue;
}
if ($tokens[$index]->isGivenKind(\T_FUNCTION)) {
// do not fix inside lambda
if ($this->tokensAnalyzer->isLambda($index)) {
// figure out where the lambda starts
$index = $tokens->getNextTokenOfKind($index, ['{']);
$openCount = 1;
do {
$index = $tokens->getNextTokenOfKind($index, ['}', '{', [\T_CLASS]]);
if ($tokens[$index]->equals('}')) {
--$openCount;
} elseif ($tokens[$index]->equals('{')) {
++$openCount;
} else {
$index = $this->fixClassy($tokens, $index);
}
} while ($openCount > 0);
}
continue;
}
if ($tokens[$index]->isGivenKind([\T_NEW, \T_INSTANCEOF])) {
$index = $tokens->getNextMeaningfulToken($index);
if ($tokens[$index]->isGivenKind(\T_STATIC)) {
$tokens[$index] = new Token([\T_STRING, 'self']);
}
continue;
}
if (!$tokens[$index]->isGivenKind(\T_STATIC)) {
continue;
}
$staticIndex = $index;
$index = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$index]->isGivenKind(\T_DOUBLE_COLON)) {
continue;
}
$tokens[$staticIndex] = new Token([\T_STRING, 'self']);
}
return $index;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Casing/ClassReferenceNameCasingFixer.php | src/Fixer/Casing/ClassReferenceNameCasingFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Casing;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ClassReferenceNameCasingFixer extends AbstractFixer
{
private const NOT_BEFORE_KINDS = [
CT::T_USE_TRAIT,
\T_AS,
\T_CASE, // PHP 8.1 trait enum-case
\T_CLASS,
\T_CONST,
\T_DOUBLE_ARROW,
\T_DOUBLE_COLON,
\T_FUNCTION,
\T_INTERFACE,
\T_OBJECT_OPERATOR,
\T_TRAIT,
FCT::T_NULLSAFE_OBJECT_OPERATOR,
FCT::T_ENUM,
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'When referencing an internal class it must be written using the correct casing.',
[
new CodeSample("<?php\nthrow new \\exception();\n"),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_STRING);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$namespaceUsesAnalyzer = new NamespaceUsesAnalyzer();
$classNames = $this->getClassNames();
foreach ($tokens->getNamespaceDeclarations() as $namespace) {
$uses = [];
foreach ($namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace) as $use) {
$uses[strtolower($use->getShortName())] = true;
}
foreach ($this->getClassReference($tokens, $namespace) as $reference) {
$currentContent = $tokens[$reference]->getContent();
$lowerCurrentContent = strtolower($currentContent);
if (isset($classNames[$lowerCurrentContent]) && $currentContent !== $classNames[$lowerCurrentContent] && !isset($uses[$lowerCurrentContent])) {
$tokens[$reference] = new Token([\T_STRING, $classNames[$lowerCurrentContent]]);
}
}
}
}
private function getClassReference(Tokens $tokens, NamespaceAnalysis $namespace): \Generator
{
static $blockKinds;
if (null === $blockKinds) {
$blockKinds = ['before' => [','], 'after' => [',']];
foreach (Tokens::getBlockEdgeDefinitions() as $definition) {
$blockKinds['before'][] = $definition['start'];
$blockKinds['after'][] = $definition['end'];
}
}
$namespaceIsGlobal = $namespace->isGlobalNamespace();
for ($index = $namespace->getScopeStartIndex(); $index < $namespace->getScopeEndIndex(); ++$index) {
if (!$tokens[$index]->isGivenKind(\T_STRING)) {
continue;
}
$nextIndex = $tokens->getNextMeaningfulToken($index);
if ($tokens[$nextIndex]->isGivenKind(\T_NS_SEPARATOR)) {
continue;
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
$nextIndex = $tokens->getNextMeaningfulToken($index);
$isNamespaceSeparator = $tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR);
if (!$isNamespaceSeparator && !$namespaceIsGlobal) {
continue;
}
if ($isNamespaceSeparator) {
$prevIndex = $tokens->getPrevMeaningfulToken($prevIndex);
if ($tokens[$prevIndex]->isGivenKind(\T_STRING)) {
continue;
}
} elseif ($tokens[$prevIndex]->isGivenKind(self::NOT_BEFORE_KINDS)) {
continue;
}
if ($tokens[$prevIndex]->equalsAny($blockKinds['before']) && $tokens[$nextIndex]->equalsAny($blockKinds['after'])) {
continue;
}
if (!$tokens[$prevIndex]->isGivenKind(\T_NEW) && $tokens[$nextIndex]->equalsAny(['(', ';', [\T_CLOSE_TAG]])) {
continue;
}
yield $index;
}
}
/**
* @return array<string, string>
*/
private function getClassNames(): array
{
static $classes = null;
if (null === $classes) {
$classes = [];
foreach (get_declared_classes() as $class) {
if ((new \ReflectionClass($class))->isInternal()) {
$classes[strtolower($class)] = $class;
}
}
}
return $classes;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Casing/NativeTypeDeclarationCasingFixer.php | src/Fixer/Casing/NativeTypeDeclarationCasingFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Casing;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NativeTypeDeclarationCasingFixer extends AbstractFixer
{
/**
* https://secure.php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration.
*
* self PHP 5.0
* array PHP 5.1
* callable PHP 5.4
* bool PHP 7.0
* float PHP 7.0
* int PHP 7.0
* string PHP 7.0
* iterable PHP 7.1
* void PHP 7.1
* object PHP 7.2
* static PHP 8.0 (return type only)
* mixed PHP 8.0
* false PHP 8.0 (union return type only)
* null PHP 8.0 (union return type only)
* never PHP 8.1 (return type only)
* true PHP 8.2 (standalone type: https://wiki.php.net/rfc/true-type)
* false PHP 8.2 (standalone type: https://wiki.php.net/rfc/null-false-standalone-types)
* null PHP 8.2 (standalone type: https://wiki.php.net/rfc/null-false-standalone-types)
*
* @var array<string, true>
*/
private array $types;
public function __construct()
{
parent::__construct();
$this->types = [
'array' => true,
'bool' => true,
'callable' => true,
'float' => true,
'int' => true,
'iterable' => true,
'object' => true,
'parent' => true,
'self' => true,
'static' => true,
'string' => true,
'void' => true,
];
if (\PHP_VERSION_ID >= 8_00_00) {
$this->types['false'] = true;
$this->types['mixed'] = true;
$this->types['null'] = true;
}
if (\PHP_VERSION_ID >= 8_01_00) {
$this->types['never'] = true;
}
if (\PHP_VERSION_ID >= 8_02_00) {
$this->types['true'] = true;
}
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Native type declarations should be used in the correct case.',
[
new CodeSample(
"<?php\nclass Bar {\n public function Foo(CALLABLE \$bar): INT\n {\n return 1;\n }\n}\n",
),
new VersionSpecificCodeSample(
"<?php\nclass Foo\n{\n const INT BAR = 1;\n}\n",
new VersionSpecification(8_03_00),
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
$classyFound = $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds());
return
$tokens->isAnyTokenKindsFound([\T_FUNCTION, \T_FN])
|| ($classyFound && $tokens->isTokenKindFound(\T_STRING))
|| (
\PHP_VERSION_ID >= 8_03_00
&& $tokens->isTokenKindFound(\T_CONST)
&& $classyFound
);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
$content = $token->getContent();
$lowercaseContent = strtolower($content);
if ($content === $lowercaseContent) {
continue;
}
if (!isset($this->types[$lowercaseContent])) {
continue;
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevIndex]->equals('=') || $tokens[$prevIndex]->isGivenKind([\T_CASE, \T_OBJECT_OPERATOR, \T_DOUBLE_COLON, \T_NS_SEPARATOR])) {
continue;
}
$nextIndex = $tokens->getNextMeaningfulToken($index);
if ($tokens[$nextIndex]->equals('=') || $tokens[$nextIndex]->isGivenKind(\T_NS_SEPARATOR)) {
continue;
}
if (
!$tokens[$prevIndex]->isGivenKind([\T_CONST, CT::T_NULLABLE_TYPE, CT::T_TYPE_ALTERNATION, CT::T_TYPE_COLON])
&& !$tokens[$nextIndex]->isGivenKind([\T_VARIABLE, CT::T_TYPE_ALTERNATION])
) {
continue;
}
$tokens[$index] = new Token([$token->getId(), $lowercaseContent]);
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Casing/LowercaseKeywordsFixer.php | src/Fixer/Casing/LowercaseKeywordsFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Casing;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* Fixer for rules defined in PSR2 ¶2.5.
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class LowercaseKeywordsFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'PHP keywords MUST be in lower case.',
[
new CodeSample(
<<<'PHP'
<?php
FOREACH($a AS $B) {
TRY {
NEW $C($a, ISSET($B));
WHILE($B) {
INCLUDE "test.php";
}
} CATCH(\Exception $e) {
EXIT(1);
}
}
PHP,
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound(Token::getKeywords());
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if ($token->isKeyword() && !$token->isGivenKind(\T_HALT_COMPILER)) {
$tokens[$index] = new Token([$token->getId(), strtolower($token->getContent())]);
}
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Casing/LowercaseStaticReferenceFixer.php | src/Fixer/Casing/LowercaseStaticReferenceFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Casing;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Kuba Werłos <werlos@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class LowercaseStaticReferenceFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Class static references `self`, `static` and `parent` MUST be in lower case.',
[
new CodeSample(
<<<'PHP'
<?php
class Foo extends Bar
{
public function baz1()
{
return STATIC::baz2();
}
public function baz2($x)
{
return $x instanceof Self;
}
public function baz3(PaRent $x)
{
return true;
}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
class Foo extends Bar
{
public function baz(?self $x) : SELF
{
return false;
}
}
PHP,
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([\T_STATIC, \T_STRING]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if (!$token->equalsAny([[\T_STRING, 'self'], [\T_STATIC, 'static'], [\T_STRING, 'parent']], false)) {
continue;
}
if (!self::isTokenToFix($tokens, $index)) {
continue;
}
$tokens[$index] = new Token([$token->getId(), strtolower($token->getContent())]);
}
}
private static function isTokenToFix(Tokens $tokens, int $index): bool
{
if ($tokens[$index]->getContent() === strtolower($tokens[$index]->getContent())) {
return false; // case is already correct
}
$nextIndex = $tokens->getNextMeaningfulToken($index);
if ($tokens[$nextIndex]->isGivenKind(\T_DOUBLE_COLON)) {
return true;
}
if (!$tokens[$nextIndex]->isGivenKind([\T_VARIABLE, CT::T_TYPE_ALTERNATION]) && !$tokens[$nextIndex]->equalsAny(['(', ')', '{', ';'])) {
return false;
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevIndex]->isGivenKind(\T_INSTANCEOF)) {
return true;
}
if ($tokens[$prevIndex]->isGivenKind(\T_CASE)) {
return !$tokens[$nextIndex]->equals(';');
}
if (!$tokens[$prevIndex]->isGivenKind([\T_NEW, \T_PRIVATE, \T_PROTECTED, \T_PUBLIC, CT::T_NULLABLE_TYPE, CT::T_TYPE_COLON, CT::T_TYPE_ALTERNATION]) && !$tokens[$prevIndex]->equalsAny(['(', '{'])) {
return false;
}
if ($tokens[$prevIndex]->equals('(') && $tokens[$nextIndex]->equals(')')) {
return false;
}
if ('static' === strtolower($tokens[$index]->getContent()) && $tokens[$nextIndex]->isGivenKind(\T_VARIABLE)) {
return false;
}
return true;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Casing/NativeFunctionTypeDeclarationCasingFixer.php | src/Fixer/Casing/NativeFunctionTypeDeclarationCasingFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Casing;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
/**
* @deprecated in favour of NativeTypeDeclarationCasingFixer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NativeFunctionTypeDeclarationCasingFixer extends AbstractProxyFixer implements DeprecatedFixerInterface
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Native type declarations for functions should use the correct case.',
[
new CodeSample("<?php\nclass Bar {\n public function Foo(CALLABLE \$bar)\n {\n return 1;\n }\n}\n"),
new CodeSample(
"<?php\nfunction Foo(INT \$a): Bool\n{\n return true;\n}\n",
),
new CodeSample(
"<?php\nfunction Foo(Iterable \$a): VOID\n{\n echo 'Hello world';\n}\n",
),
new CodeSample(
"<?php\nfunction Foo(Object \$a)\n{\n return 'hi!';\n}\n",
),
],
);
}
public function getSuccessorsNames(): array
{
return array_keys($this->proxyFixers);
}
protected function createProxyFixers(): array
{
$fixer = new NativeTypeDeclarationCasingFixer();
return [$fixer];
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Casing/IntegerLiteralCaseFixer.php | src/Fixer/Casing/IntegerLiteralCaseFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Casing;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class IntegerLiteralCaseFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Integer literals must be in correct case.',
[
new CodeSample(
"<?php\n\$foo = 0Xff;\n\$bar = 0B11111111;\n",
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_LNUMBER);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(\T_LNUMBER)) {
continue;
}
$content = $token->getContent();
$newContent = Preg::replaceCallback(
'#^0([boxBOX])([0-9a-fA-F_]+)$#',
// @phpstan-ignore-next-line offsetAccess.notFound
static fn (array $matches): string => '0'.strtolower($matches[1]).strtoupper($matches[2]),
$content,
);
if ($content === $newContent) {
continue;
}
$tokens[$index] = new Token([\T_LNUMBER, $newContent]);
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Casing/MagicConstantCasingFixer.php | src/Fixer/Casing/MagicConstantCasingFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Casing;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author ntzm
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class MagicConstantCasingFixer extends AbstractFixer
{
private const MAGIC_CONSTANTS = [
\T_LINE => '__LINE__',
\T_FILE => '__FILE__',
\T_DIR => '__DIR__',
\T_FUNC_C => '__FUNCTION__',
\T_CLASS_C => '__CLASS__',
\T_METHOD_C => '__METHOD__',
\T_NS_C => '__NAMESPACE__',
CT::T_CLASS_CONSTANT => 'class',
\T_TRAIT_C => '__TRAIT__',
FCT::T_PROPERTY_C => '__PROPERTY__',
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Magic constants should be referred to using the correct casing.',
[new CodeSample("<?php\necho __dir__;\n")],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound($this->getMagicConstantTokens());
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$magicConstantTokens = $this->getMagicConstantTokens();
foreach ($tokens as $index => $token) {
if ($token->isGivenKind($magicConstantTokens)) {
$tokens[$index] = new Token([$token->getId(), self::MAGIC_CONSTANTS[$token->getId()]]);
}
}
}
/**
* @return non-empty-list<int>
*/
private function getMagicConstantTokens(): array
{
static $magicConstantTokens = null;
if (null === $magicConstantTokens) {
$magicConstantTokens = array_keys(self::MAGIC_CONSTANTS);
}
return $magicConstantTokens;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Casing/NativeFunctionCasingFixer.php | src/Fixer/Casing/NativeFunctionCasingFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Casing;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NativeFunctionCasingFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Function defined by PHP should be called using the correct casing.',
[new CodeSample("<?php\nSTRLEN(\$str);\n")],
);
}
/**
* {@inheritdoc}
*
* Must run after FunctionToConstantFixer, NoUselessSprintfFixer, PowToExponentiationFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_STRING);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$functionsAnalyzer = new FunctionsAnalyzer();
static $nativeFunctionNames = null;
if (null === $nativeFunctionNames) {
$nativeFunctionNames = $this->getNativeFunctionNames();
}
for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) {
// test if we are at a function all
if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) {
continue;
}
// test if the function call is to a native PHP function
$lower = strtolower($tokens[$index]->getContent());
if (!\array_key_exists($lower, $nativeFunctionNames)) {
continue;
}
$tokens[$index] = new Token([\T_STRING, $nativeFunctionNames[$lower]]);
}
}
/**
* @return array<string, string>
*/
private function getNativeFunctionNames(): array
{
$allFunctions = get_defined_functions();
$functions = [];
foreach ($allFunctions['internal'] as $function) {
$functions[strtolower($function)] = $function;
}
return $functions;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Casing/ConstantCaseFixer.php | src/Fixer/Casing/ConstantCaseFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Casing;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* Fixer for constants case.
*
* @phpstan-type _AutogeneratedInputConfiguration array{
* case?: 'lower'|'upper',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* case: 'lower'|'upper',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Pol Dellaiera <pol.dellaiera@protonmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ConstantCaseFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* Hold the function that will be used to convert the constants.
*
* @var callable
*/
private $fixFunction;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'The PHP constants `true`, `false`, and `null` MUST be written using the correct casing.',
[
new CodeSample("<?php\n\$a = FALSE;\n\$b = True;\n\$c = nuLL;\n"),
new CodeSample("<?php\n\$a = FALSE;\n\$b = True;\n\$c = nuLL;\n", ['case' => 'upper']),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_STRING);
}
protected function configurePostNormalisation(): void
{
if ('lower' === $this->configuration['case']) {
$this->fixFunction = static fn (string $content): string => strtolower($content);
}
if ('upper' === $this->configuration['case']) {
$this->fixFunction = static fn (string $content): string => strtoupper($content);
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('case', 'Whether to use the `upper` or `lower` case syntax.'))
->setAllowedValues(['upper', 'lower'])
->setDefault('lower')
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
static $forbiddenPrevKinds = null;
if (null === $forbiddenPrevKinds) {
$forbiddenPrevKinds = [
\T_DOUBLE_COLON,
\T_EXTENDS,
\T_IMPLEMENTS,
\T_INSTANCEOF,
\T_NAMESPACE,
\T_NEW,
\T_NS_SEPARATOR,
...Token::getObjectOperatorKinds(),
];
}
foreach ($tokens as $index => $token) {
if (!$token->equalsAny([[\T_STRING, 'true'], [\T_STRING, 'false'], [\T_STRING, 'null']], false)) {
continue;
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevIndex]->isGivenKind($forbiddenPrevKinds)) {
continue;
}
$nextIndex = $tokens->getNextMeaningfulToken($index);
if ($tokens[$nextIndex]->isGivenKind([\T_PAAMAYIM_NEKUDOTAYIM, \T_NS_SEPARATOR]) || $tokens[$nextIndex]->equals('=', false)) {
continue;
}
if ($tokens[$prevIndex]->isGivenKind(\T_CASE) && $tokens[$nextIndex]->equals(';')) {
continue;
}
$tokens[$index] = new Token([$token->getId(), ($this->fixFunction)($token->getContent())]);
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Casing/MagicMethodCasingFixer.php | src/Fixer/Casing/MagicMethodCasingFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Casing;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class MagicMethodCasingFixer extends AbstractFixer
{
/**
* @var array<string, string>
*/
private const MAGIC_NAMES = [
'__call' => '__call',
'__callstatic' => '__callStatic',
'__clone' => '__clone',
'__construct' => '__construct',
'__debuginfo' => '__debugInfo',
'__destruct' => '__destruct',
'__get' => '__get',
'__invoke' => '__invoke',
'__isset' => '__isset',
'__serialize' => '__serialize',
'__set' => '__set',
'__set_state' => '__set_state',
'__sleep' => '__sleep',
'__tostring' => '__toString',
'__unserialize' => '__unserialize',
'__unset' => '__unset',
'__wakeup' => '__wakeup',
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Magic method definitions and calls must be using the correct casing.',
[
new CodeSample(
<<<'PHP'
<?php
class Foo
{
public function __Sleep()
{
}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
$foo->__INVOKE(1);
PHP,
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_STRING) && $tokens->isAnyTokenKindsFound([\T_FUNCTION, \T_DOUBLE_COLON, ...Token::getObjectOperatorKinds()]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$inClass = 0;
$tokenCount = \count($tokens);
for ($index = 1; $index < $tokenCount - 2; ++$index) {
if (0 === $inClass && $tokens[$index]->isClassy()) {
$inClass = 1;
$index = $tokens->getNextTokenOfKind($index, ['{']);
continue;
}
if (0 !== $inClass) {
if ($tokens[$index]->equals('{')) {
++$inClass;
continue;
}
if ($tokens[$index]->equals('}')) {
--$inClass;
continue;
}
}
if (!$tokens[$index]->isGivenKind(\T_STRING)) {
continue; // wrong type
}
$content = $tokens[$index]->getContent();
if (!str_starts_with($content, '__')) {
continue; // cheap look ahead
}
$name = strtolower($content);
if (!$this->isMagicMethodName($name)) {
continue; // method name is not one of the magic ones we can fix
}
$nameInCorrectCasing = $this->getMagicMethodNameInCorrectCasing($name);
if ($nameInCorrectCasing === $content) {
continue; // method name is already in the correct casing, no fix needed
}
if ($this->isFunctionSignature($tokens, $index)) {
if (0 !== $inClass) {
// this is a method definition we want to fix
$this->setTokenToCorrectCasing($tokens, $index, $nameInCorrectCasing);
}
continue;
}
if ($this->isMethodCall($tokens, $index)) {
$this->setTokenToCorrectCasing($tokens, $index, $nameInCorrectCasing);
continue;
}
if (
('__callstatic' === $name || '__set_state' === $name)
&& $this->isStaticMethodCall($tokens, $index)
) {
$this->setTokenToCorrectCasing($tokens, $index, $nameInCorrectCasing);
}
}
}
private function isFunctionSignature(Tokens $tokens, int $index): bool
{
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if (!$tokens[$prevIndex]->isGivenKind(\T_FUNCTION)) {
return false; // not a method signature
}
return $tokens[$tokens->getNextMeaningfulToken($index)]->equals('(');
}
private function isMethodCall(Tokens $tokens, int $index): bool
{
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if (!$tokens[$prevIndex]->isObjectOperator()) {
return false; // not a "simple" method call
}
return $tokens[$tokens->getNextMeaningfulToken($index)]->equals('(');
}
private function isStaticMethodCall(Tokens $tokens, int $index): bool
{
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if (!$tokens[$prevIndex]->isGivenKind(\T_DOUBLE_COLON)) {
return false; // not a "simple" static method call
}
return $tokens[$tokens->getNextMeaningfulToken($index)]->equals('(');
}
/**
* @phpstan-assert-if-true key-of<self::MAGIC_NAMES> $name
*/
private function isMagicMethodName(string $name): bool
{
return isset(self::MAGIC_NAMES[$name]);
}
/**
* @param key-of<self::MAGIC_NAMES> $name name of a magic method
*
* @return value-of<self::MAGIC_NAMES>
*/
private function getMagicMethodNameInCorrectCasing(string $name): string
{
return self::MAGIC_NAMES[$name];
}
private function setTokenToCorrectCasing(Tokens $tokens, int $index, string $nameInCorrectCasing): void
{
$tokens[$index] = new Token([\T_STRING, $nameInCorrectCasing]);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/AttributeNotation/OrderedAttributesFixer.php | src/Fixer/AttributeNotation/OrderedAttributesFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\AttributeNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\AttributeAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\FullyQualifiedNameAnalyzer;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Options;
/**
* @phpstan-import-type _AttributeItems from AttributeAnalysis
*
* @phpstan-type _AutogeneratedInputConfiguration array{
* order?: list<string>,
* sort_algorithm?: 'alpha'|'custom',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* order: array<string, int>,
* sort_algorithm: 'alpha'|'custom',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author HypeMC <hypemc@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class OrderedAttributesFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public const ORDER_ALPHA = 'alpha';
public const ORDER_CUSTOM = 'custom';
private const SUPPORTED_SORT_ALGORITHMS = [
self::ORDER_ALPHA,
self::ORDER_CUSTOM,
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Sorts attributes using the configured sort algorithm.',
[
new VersionSpecificCodeSample(
<<<'EOL'
<?php
#[Foo]
#[Bar(3)]
#[Qux(new Bar(5))]
#[Corge(a: 'test')]
class Sample1 {}
#[
Foo,
Bar(3),
Qux(new Bar(5)),
Corge(a: 'test'),
]
class Sample2 {}
EOL,
new VersionSpecification(8_00_00),
),
new VersionSpecificCodeSample(
<<<'EOL'
<?php
use A\B\Foo;
use A\B\Bar as BarAlias;
use A\B as AB;
#[Foo]
#[BarAlias(3)]
#[AB\Qux(new Bar(5))]
#[\A\B\Corge(a: 'test')]
class Sample1 {}
EOL,
new VersionSpecification(8_00_00),
['sort_algorithm' => self::ORDER_CUSTOM, 'order' => ['A\B\Qux', 'A\B\Bar', 'A\B\Corge']],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after FullyQualifiedStrictTypesFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(FCT::T_ATTRIBUTE);
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
$fixerName = $this->getName();
return new FixerConfigurationResolver([
(new FixerOptionBuilder('sort_algorithm', 'How the attributes should be sorted.'))
->setAllowedValues(self::SUPPORTED_SORT_ALGORITHMS)
->setDefault(self::ORDER_ALPHA)
->setNormalizer(static function (Options $options, string $value) use ($fixerName): string {
if (self::ORDER_CUSTOM === $value && [] === $options['order']) {
throw new InvalidFixerConfigurationException(
$fixerName,
'The custom order strategy requires providing `order` option with a list of attributes\'s FQNs.',
);
}
return $value;
})
->getOption(),
(new FixerOptionBuilder('order', 'A list of FQCNs of attributes defining the desired order used when custom sorting algorithm is configured.'))
->setAllowedTypes(['string[]'])
->setDefault([])
->setNormalizer(static function (Options $options, array $value) use ($fixerName): array {
if ($value !== array_unique($value)) {
throw new InvalidFixerConfigurationException($fixerName, 'The list includes attributes that are not unique.');
}
return array_flip(array_values(
array_map(static fn (string $attribute): string => ltrim($attribute, '\\'), $value),
));
})
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$fullyQualifiedNameAnalyzer = new FullyQualifiedNameAnalyzer($tokens);
$index = 0;
while (null !== $index = $tokens->getNextTokenOfKind($index, [[\T_ATTRIBUTE]])) {
/** @var _AttributeItems $elements */
$elements = array_map(fn (AttributeAnalysis $attributeAnalysis): array => [
'name' => $this->sortAttributes($fullyQualifiedNameAnalyzer, $tokens, $attributeAnalysis->getStartIndex(), $attributeAnalysis->getAttributes()),
'start' => $attributeAnalysis->getStartIndex(),
'end' => $attributeAnalysis->getEndIndex(),
], AttributeAnalyzer::collect($tokens, $index));
$endIndex = end($elements)['end'];
try {
if (1 === \count($elements)) {
continue;
}
$sortedElements = $this->sortElements($elements);
if ($elements === $sortedElements) {
continue;
}
$this->sortTokens($tokens, $index, $endIndex, $sortedElements);
} finally {
$index = $endIndex;
}
}
}
/**
* @param _AttributeItems $attributes
*/
private function sortAttributes(FullyQualifiedNameAnalyzer $fullyQualifiedNameAnalyzer, Tokens $tokens, int $index, array $attributes): string
{
if (1 === \count($attributes)) {
return $this->getAttributeName($fullyQualifiedNameAnalyzer, $attributes[0]['name'], $attributes[0]['start']);
}
foreach ($attributes as &$attribute) {
$attribute['name'] = $this->getAttributeName($fullyQualifiedNameAnalyzer, $attribute['name'], $attribute['start']);
}
$sortedElements = $this->sortElements($attributes);
if ($attributes === $sortedElements) {
return $attributes[0]['name'];
}
$this->sortTokens($tokens, $index + 1, end($attributes)['end'], $sortedElements, new Token(','));
return $sortedElements[0]['name'];
}
private function getAttributeName(FullyQualifiedNameAnalyzer $fullyQualifiedNameAnalyzer, string $name, int $index): string
{
if (self::ORDER_CUSTOM === $this->configuration['sort_algorithm']) {
return $fullyQualifiedNameAnalyzer->getFullyQualifiedName($name, $index, NamespaceUseAnalysis::TYPE_CLASS);
}
return ltrim($name, '\\');
}
/**
* @param _AttributeItems $elements
*
* @return _AttributeItems
*/
private function sortElements(array $elements): array
{
usort($elements, function (array $a, array $b): int {
$sortAlgorithm = $this->configuration['sort_algorithm'];
if (self::ORDER_ALPHA === $sortAlgorithm) {
return $a['name'] <=> $b['name'];
}
if (self::ORDER_CUSTOM === $sortAlgorithm) {
return
($this->configuration['order'][$a['name']] ?? \PHP_INT_MAX)
<=> ($this->configuration['order'][$b['name']] ?? \PHP_INT_MAX);
}
throw new \InvalidArgumentException(\sprintf('Invalid sort algorithm "%s" provided.', $sortAlgorithm));
});
return $elements;
}
/**
* @param _AttributeItems $elements
*/
private function sortTokens(Tokens $tokens, int $startIndex, int $endIndex, array $elements, ?Token $delimiter = null): void
{
$replaceTokens = [];
foreach ($elements as $pos => $element) {
for ($i = $element['start']; $i <= $element['end']; ++$i) {
$replaceTokens[] = clone $tokens[$i];
}
if (null !== $delimiter && $pos !== \count($elements) - 1) {
$replaceTokens[] = clone $delimiter;
}
}
$tokens->overrideRange($startIndex, $endIndex, $replaceTokens);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/AttributeNotation/AttributeEmptyParenthesesFixer.php | src/Fixer/AttributeNotation/AttributeEmptyParenthesesFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\AttributeNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* use_parentheses?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* use_parentheses: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author HypeMC <hypemc@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class AttributeEmptyParenthesesFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'PHP attributes declared without arguments must (not) be followed by empty parentheses.',
[
new CodeSample("<?php\n\n#[Foo()]\nclass Sample1 {}\n\n#[Bar(), Baz()]\nclass Sample2 {}\n"),
new CodeSample(
"<?php\n\n#[Foo]\nclass Sample1 {}\n\n#[Bar, Baz]\nclass Sample2 {}\n",
['use_parentheses' => true],
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(FCT::T_ATTRIBUTE);
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('use_parentheses', 'Whether attributes should be followed by parentheses or not.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$index = 0;
while (null !== $index = $tokens->getNextTokenOfKind($index, [[\T_ATTRIBUTE]])) {
$nextIndex = $index;
do {
$parenthesesIndex = $tokens->getNextTokenOfKind($nextIndex, ['(', ',', [CT::T_ATTRIBUTE_CLOSE]]);
if (true === $this->configuration['use_parentheses']) {
$this->ensureParenthesesAt($tokens, $parenthesesIndex);
} else {
$this->ensureNoParenthesesAt($tokens, $parenthesesIndex);
}
$nextIndex = $tokens->getNextTokenOfKind($nextIndex, ['(', ',', [CT::T_ATTRIBUTE_CLOSE]]);
// Find closing parentheses, we need to do this in case there's a comma inside the parentheses
if ($tokens[$nextIndex]->equals('(')) {
$nextIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex);
$nextIndex = $tokens->getNextTokenOfKind($nextIndex, [',', [CT::T_ATTRIBUTE_CLOSE]]);
}
// In case there's a comma right before T_ATTRIBUTE_CLOSE
if (!$tokens[$nextIndex]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) {
$nextIndex = $tokens->getNextMeaningfulToken($nextIndex);
}
} while (!$tokens[$nextIndex]->isGivenKind(CT::T_ATTRIBUTE_CLOSE));
}
}
private function ensureParenthesesAt(Tokens $tokens, int $index): void
{
if ($tokens[$index]->equals('(')) {
return;
}
$tokens->insertAt(
$tokens->getPrevMeaningfulToken($index) + 1,
[new Token('('), new Token(')')],
);
}
private function ensureNoParenthesesAt(Tokens $tokens, int $index): void
{
if (!$tokens[$index]->equals('(')) {
return;
}
$closingIndex = $tokens->getNextMeaningfulToken($index);
// attribute has arguments - parentheses can not be removed
if (!$tokens[$closingIndex]->equals(')')) {
return;
}
$tokens->clearTokenAndMergeSurroundingWhitespace($closingIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/AttributeNotation/GeneralAttributeRemoveFixer.php | src/Fixer/AttributeNotation/GeneralAttributeRemoveFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\AttributeNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\AttributeAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-import-type _AttributeItems from AttributeAnalysis
* @phpstan-import-type _AttributeItem from AttributeAnalysis
*
* @phpstan-type _AutogeneratedInputConfiguration array{
* attributes?: list<class-string>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* attributes: list<class-string>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Raffaele Carelle <raffaele.carelle@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class GeneralAttributeRemoveFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Removes configured attributes by their respective FQN.',
[
new CodeSample(
<<<'PHP'
<?php
#[\A\B\Foo]
function foo() {}
PHP,
['attributes' => ['\A\B\Foo']],
),
new CodeSample(
<<<'PHP'
<?php
use A\B\Bar as BarAlias;
#[\A\B\Foo]
#[BarAlias]
function foo() {}
PHP,
['attributes' => ['\A\B\Foo', 'A\B\Bar']],
),
],
);
}
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(FCT::T_ATTRIBUTE);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
if (0 === \count($this->configuration['attributes'])) {
return;
}
$index = 0;
while (null !== $index = $tokens->getNextTokenOfKind($index, [[\T_ATTRIBUTE]])) {
$attributeAnalysis = AttributeAnalyzer::collectOne($tokens, $index);
$endIndex = $attributeAnalysis->getEndIndex();
$removedCount = 0;
foreach ($attributeAnalysis->getAttributes() as $element) {
$fullname = AttributeAnalyzer::determineAttributeFullyQualifiedName($tokens, $element['name'], $element['start']);
if (!\in_array($fullname, $this->configuration['attributes'], true)) {
continue;
}
$tokens->clearRange($element['start'], $element['end']);
++$removedCount;
$siblingIndex = $tokens->getNonEmptySibling($element['end'], 1);
// Clear element comma
if (',' === $tokens[$siblingIndex]->getContent()) {
$tokens->clearAt($siblingIndex);
}
}
// Clear whole attribute if all are removed (multiline attribute case)
if (\count($attributeAnalysis->getAttributes()) === $removedCount) {
$tokens->clearRange($attributeAnalysis->getStartIndex(), $attributeAnalysis->getEndIndex());
}
// Clear trailing comma
$tokenIndex = $tokens->getMeaningfulTokenSibling($attributeAnalysis->getClosingBracketIndex(), -1);
if (',' === $tokens[$tokenIndex]->getContent()) {
$tokens->clearAt($tokenIndex);
}
$index = $endIndex;
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('attributes', 'List of FQNs of attributes for removal.'))
->setAllowedTypes(['class-string[]'])
->setDefault([])
->getOption(),
]);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/CastNotation/NoShortBoolCastFixer.php | src/Fixer/CastNotation/NoShortBoolCastFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\CastNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoShortBoolCastFixer extends AbstractFixer
{
/**
* {@inheritdoc}
*
* Must run before CastSpacesFixer.
*/
public function getPriority(): int
{
return -9;
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Short cast `bool` using double exclamation mark should not be used.',
[new CodeSample("<?php\n\$a = !!\$b;\n")],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound('!');
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = \count($tokens) - 1; $index > 1; --$index) {
if ($tokens[$index]->equals('!')) {
$index = $this->fixShortCast($tokens, $index);
}
}
}
private function fixShortCast(Tokens $tokens, int $index): int
{
for ($i = $index - 1; $i > 1; --$i) {
if ($tokens[$i]->equals('!')) {
$this->fixShortCastToBoolCast($tokens, $i, $index);
break;
}
if (!$tokens[$i]->isComment() && !$tokens[$i]->isWhitespace()) {
break;
}
}
return $i;
}
private function fixShortCastToBoolCast(Tokens $tokens, int $start, int $end): void
{
for (; $start <= $end; ++$start) {
if (
!$tokens[$start]->isComment()
&& !($tokens[$start]->isWhitespace() && $tokens[$start - 1]->isComment())
) {
$tokens->clearAt($start);
}
}
$tokens->insertAt($start, new Token([\T_BOOL_CAST, '(bool)']));
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/CastNotation/ShortScalarCastFixer.php | src/Fixer/CastNotation/ShortScalarCastFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\CastNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ShortScalarCastFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Cast `(boolean)` and `(integer)` should be written as `(bool)` and `(int)`, `(double)` and `(real)` as `(float)`, `(binary)` as `(string)`.',
[
new CodeSample(
"<?php\n\$a = (boolean) \$b;\n\$a = (integer) \$b;\n\$a = (double) \$b;\n\n\$a = (binary) \$b;\n",
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound(Token::getCastTokenKinds());
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) {
if (!$tokens[$index]->isCast()) {
continue;
}
$castFrom = trim(substr($tokens[$index]->getContent(), 1, -1));
$castFromLowered = strtolower($castFrom);
$castTo = [
'boolean' => 'bool',
'integer' => 'int',
'double' => 'float',
'real' => 'float',
'binary' => 'string',
][$castFromLowered] ?? null;
if (null === $castTo) {
continue;
}
$tokens[$index] = new Token([
$tokens[$index]->getId(),
str_replace($castFrom, $castTo, $tokens[$index]->getContent()),
]);
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/CastNotation/CastSpacesFixer.php | src/Fixer/CastNotation/CastSpacesFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\CastNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* space?: 'none'|'single',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* space: 'none'|'single',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class CastSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private const INSIDE_CAST_SPACE_REPLACE_MAP = [
' ' => '',
"\t" => '',
"\n" => '',
"\r" => '',
"\0" => '',
"\x0B" => '',
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'A single space or none should be between cast and variable.',
[
new CodeSample(
"<?php\n\$bar = ( string ) \$a;\n\$foo = (int)\$b;\n",
),
new CodeSample(
"<?php\n\$bar = ( string ) \$a;\n\$foo = (int)\$b;\n",
['space' => 'single'],
),
new CodeSample(
"<?php\n\$bar = ( string ) \$a;\n\$foo = (int) \$b;\n",
['space' => 'none'],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after NoShortBoolCastFixer.
*/
public function getPriority(): int
{
return -10;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound(Token::getCastTokenKinds());
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if (!$token->isCast()) {
continue;
}
$tokens[$index] = new Token([
$token->getId(),
strtr($token->getContent(), self::INSIDE_CAST_SPACE_REPLACE_MAP),
]);
if ('single' === $this->configuration['space']) {
// force single whitespace after cast token:
if ($tokens[$index + 1]->isWhitespace(" \t")) {
// - if next token is whitespaces that contains only spaces and tabs - override next token with single space
$tokens[$index + 1] = new Token([\T_WHITESPACE, ' ']);
} elseif (!$tokens[$index + 1]->isWhitespace()) {
// - if next token is not whitespaces that contains spaces, tabs and new lines - append single space to current token
$tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' ']));
}
continue;
}
// force no whitespace after cast token:
if ($tokens[$index + 1]->isWhitespace()) {
$tokens->clearAt($index + 1);
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('space', 'Spacing to apply between cast and variable.'))
->setAllowedValues(['none', 'single'])
->setDefault('single')
->getOption(),
]);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/CastNotation/ModernizeTypesCastingFixer.php | src/Fixer/CastNotation/ModernizeTypesCastingFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\CastNotation;
use PhpCsFixer\AbstractFunctionReferenceFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Vladimir Reznichenko <kalessil@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ModernizeTypesCastingFixer extends AbstractFunctionReferenceFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Replaces `intval`, `floatval`, `doubleval`, `strval` and `boolval` function calls with according type casting operator.',
[
new CodeSample(
<<<'PHP'
<?php
$a = intval($b);
$a = floatval($b);
$a = doubleval($b);
$a = strval ($b);
$a = boolval($b);
PHP,
),
],
null,
'Risky if any of the functions `intval`, `floatval`, `doubleval`, `strval` or `boolval` are overridden.',
);
}
/**
* {@inheritdoc}
*
* Must run before NoUnneededControlParenthesesFixer.
*/
public function getPriority(): int
{
return 31;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$argumentsAnalyzer = new ArgumentsAnalyzer();
foreach ([
'intval' => [\T_INT_CAST, '(int)'],
'floatval' => [\T_DOUBLE_CAST, '(float)'],
'doubleval' => [\T_DOUBLE_CAST, '(float)'],
'strval' => [\T_STRING_CAST, '(string)'],
'boolval' => [\T_BOOL_CAST, '(bool)'],
] as $functionIdentity => $newToken) {
$currIndex = 0;
do {
// try getting function reference and translate boundaries for humans
$boundaries = $this->find($functionIdentity, $tokens, $currIndex, $tokens->count() - 1);
if (null === $boundaries) {
// next function search, as current one not found
continue 2;
}
[$functionName, $openParenthesis, $closeParenthesis] = $boundaries;
// analysing cursor shift
$currIndex = $openParenthesis;
// indicator that the function is overridden
if (1 !== $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $closeParenthesis)) {
continue;
}
$paramContentEnd = $closeParenthesis;
$commaCandidate = $tokens->getPrevMeaningfulToken($paramContentEnd);
if ($tokens[$commaCandidate]->equals(',')) {
$tokens->removeTrailingWhitespace($commaCandidate);
$tokens->clearAt($commaCandidate);
$paramContentEnd = $commaCandidate;
}
// check if something complex passed as an argument and preserve parentheses then
$countParamTokens = 0;
for ($paramContentIndex = $openParenthesis + 1; $paramContentIndex < $paramContentEnd; ++$paramContentIndex) {
// not a space, means some sensible token
if (!$tokens[$paramContentIndex]->isGivenKind(\T_WHITESPACE)) {
++$countParamTokens;
}
}
$preserveParentheses = $countParamTokens > 1;
$afterCloseParenthesisIndex = $tokens->getNextMeaningfulToken($closeParenthesis);
$afterCloseParenthesisToken = $tokens[$afterCloseParenthesisIndex];
$wrapInParentheses = $afterCloseParenthesisToken->equalsAny(['[', '{']) || $afterCloseParenthesisToken->isGivenKind(\T_POW);
// analyse namespace specification (root one or none) and decide what to do
$prevTokenIndex = $tokens->getPrevMeaningfulToken($functionName);
if ($tokens[$prevTokenIndex]->isGivenKind(\T_NS_SEPARATOR)) {
// get rid of root namespace when it used
$tokens->removeTrailingWhitespace($prevTokenIndex);
$tokens->clearAt($prevTokenIndex);
}
// perform transformation
$replacementSequence = [
new Token($newToken),
new Token([\T_WHITESPACE, ' ']),
];
if ($wrapInParentheses) {
array_unshift($replacementSequence, new Token('('));
}
if (!$preserveParentheses) {
// closing parenthesis removed with leading spaces
$tokens->removeLeadingWhitespace($closeParenthesis);
$tokens->clearAt($closeParenthesis);
// opening parenthesis removed with trailing spaces
$tokens->removeLeadingWhitespace($openParenthesis);
$tokens->removeTrailingWhitespace($openParenthesis);
$tokens->clearAt($openParenthesis);
} else {
// we'll need to provide a space after a casting operator
$tokens->removeTrailingWhitespace($functionName);
}
if ($wrapInParentheses) {
$tokens->insertAt($closeParenthesis, new Token(')'));
}
$tokens->overrideRange($functionName, $functionName, $replacementSequence);
// nested transformations support
$currIndex = $functionName;
} while (null !== $currIndex);
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/CastNotation/NoUnsetCastFixer.php | src/Fixer/CastNotation/NoUnsetCastFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\CastNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoUnsetCastFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Variables must be set `null` instead of using `(unset)` casting.',
[new CodeSample("<?php\n\$a = (unset) \$b;\n")],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_UNSET_CAST);
}
/**
* {@inheritdoc}
*
* Must run before BinaryOperatorSpacesFixer.
*/
public function getPriority(): int
{
return 0;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = \count($tokens) - 1; $index > 0; --$index) {
if ($tokens[$index]->isGivenKind(\T_UNSET_CAST)) {
$this->fixUnsetCast($tokens, $index);
}
}
}
private function fixUnsetCast(Tokens $tokens, int $index): void
{
$assignmentIndex = $tokens->getPrevMeaningfulToken($index);
if (null === $assignmentIndex || !$tokens[$assignmentIndex]->equals('=')) {
return;
}
$varIndex = $tokens->getNextMeaningfulToken($index);
if (null === $varIndex || !$tokens[$varIndex]->isGivenKind(\T_VARIABLE)) {
return;
}
$afterVar = $tokens->getNextMeaningfulToken($varIndex);
if (null === $afterVar || !$tokens[$afterVar]->equalsAny([';', [\T_CLOSE_TAG]])) {
return;
}
$nextIsWhiteSpace = $tokens[$assignmentIndex + 1]->isWhitespace();
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
$tokens->clearTokenAndMergeSurroundingWhitespace($varIndex);
++$assignmentIndex;
if (!$nextIsWhiteSpace) {
$tokens->insertAt($assignmentIndex, new Token([\T_WHITESPACE, ' ']));
}
++$assignmentIndex;
$tokens->insertAt($assignmentIndex, new Token([\T_STRING, 'null']));
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/CastNotation/LowercaseCastFixer.php | src/Fixer/CastNotation/LowercaseCastFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\CastNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class LowercaseCastFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Cast should be written in lower case.',
[
new CodeSample(
<<<'PHP'
<?php
$a = (BOOLEAN) $b;
$a = (BOOL) $b;
$a = (INTEGER) $b;
$a = (INT) $b;
$a = (DOUBLE) $b;
$a = (FLoaT) $b;
$a = (flOAT) $b;
$a = (stRING) $b;
$a = (ARRAy) $b;
$a = (OBJect) $b;
$a = (UNset) $b;
$a = (Binary) $b;
PHP,
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound(Token::getCastTokenKinds());
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) {
if (!$tokens[$index]->isCast()) {
continue;
}
$tokens[$index] = new Token([$tokens[$index]->getId(), strtolower($tokens[$index]->getContent())]);
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Import/FullyQualifiedStrictTypesFixer.php | src/Fixer/Import/FullyQualifiedStrictTypesFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Import;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\TypeExpression;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Processor\ImportProcessor;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* import_symbols?: bool,
* leading_backslash_in_global_namespace?: bool,
* phpdoc_tags?: list<string>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* import_symbols: bool,
* leading_backslash_in_global_namespace: bool,
* phpdoc_tags: list<string>,
* }
* @phpstan-type _Uses array{
* constant?: array<non-empty-string, non-empty-string>,
* class?: array<non-empty-string, non-empty-string>,
* function?: array<non-empty-string, non-empty-string>
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author VeeWee <toonverwerft@gmail.com>
* @author Tomas Jadrny <developer@tomasjadrny.cz>
* @author Greg Korba <greg@codito.dev>
* @author SpacePossum <possumfromspace@gmail.com>
* @author Michael Vorisek <https://github.com/mvorisek>
*
* @phpstan-import-type _ImportType from \PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class FullyQualifiedStrictTypesFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private const REGEX_CLASS = '(?:\\\?+'.TypeExpression::REGEX_IDENTIFIER
.'(\\\\'.TypeExpression::REGEX_IDENTIFIER.')*+)';
private const CLASSY_KINDS = [\T_CLASS, \T_INTERFACE, \T_TRAIT, FCT::T_ENUM];
/**
* @var null|array{
* constant?: list<non-empty-string>,
* class?: list<non-empty-string>,
* function?: list<non-empty-string>
* }
*/
private ?array $discoveredSymbols;
/**
* @var array{
* constant?: array<string, non-empty-string>,
* class?: array<string, non-empty-string>,
* function?: array<string, non-empty-string>
* }
*/
private array $symbolsForImport = [];
/**
* @var array<int<0, max>, array<string, true>>
*/
private array $reservedIdentifiersByLevel;
/**
* @var array{
* constant?: array<string, string>,
* class?: array<string, string>,
* function?: array<string, string>
* }
*/
private array $cacheUsesLast = [];
/**
* @var array{
* constant?: array<non-empty-lowercase-string, non-empty-string>,
* class?: array<non-empty-lowercase-string, non-empty-string>,
* function?: array<non-empty-lowercase-string, non-empty-string>
* }
*/
private array $cacheUseNameByShortNameLower;
/** @var _Uses */
private array $cacheUseShortNameByName;
/** @var _Uses */
private array $cacheUseShortNameByNormalizedName;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Removes the leading part of fully qualified symbol references if a given symbol is imported or belongs to the current namespace.',
[
new CodeSample(
<<<'PHP'
<?php
use Foo\Bar;
use Foo\Bar\Baz;
use Foo\OtherClass;
use Foo\SomeContract;
use Foo\SomeException;
/**
* @see \Foo\Bar\Baz
*/
class SomeClass extends \Foo\OtherClass implements \Foo\SomeContract
{
/**
* @var \Foo\Bar\Baz
*/
public $baz;
/**
* @param \Foo\Bar\Baz $baz
*/
public function __construct($baz) {
$this->baz = $baz;
}
/**
* @return \Foo\Bar\Baz
*/
public function getBaz() {
return $this->baz;
}
public function doX(\Foo\Bar $foo, \Exception $e): \Foo\Bar\Baz
{
try {}
catch (\Foo\SomeException $e) {}
}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
class SomeClass
{
public function doY(Foo\NotImported $u, \Foo\NotImported $v)
{
}
}
PHP,
['leading_backslash_in_global_namespace' => true],
),
new CodeSample(
<<<'PHP'
<?php
namespace {
use Foo\A;
try {
foo();
} catch (\Exception|\Foo\A $e) {
}
}
namespace Foo\Bar {
class SomeClass implements \Foo\Bar\Baz
{
}
}
PHP,
['leading_backslash_in_global_namespace' => true],
),
new CodeSample(
<<<'PHP'
<?php
namespace Foo\Test;
class Foo extends \Other\BaseClass implements \Other\Interface1, \Other\Interface2
{
/** @var \Other\PropertyPhpDoc */
private $array;
public function __construct(\Other\FunctionArgument $arg) {}
public function foo(): \Other\FunctionReturnType
{
try {
\Other\StaticFunctionCall::bar();
} catch (\Other\CaughtThrowable $e) {}
}
}
PHP,
['import_symbols' => true],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before NoSuperfluousPhpdocTagsFixer, OrderedAttributesFixer, OrderedImportsFixer, OrderedInterfacesFixer, StatementIndentationFixer.
* Must run after ClassKeywordFixer, PhpUnitAttributesFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer.
*/
public function getPriority(): int
{
return 7;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([
CT::T_USE_TRAIT,
FCT::T_ATTRIBUTE,
\T_CATCH,
\T_DOUBLE_COLON,
\T_DOC_COMMENT,
\T_EXTENDS,
\T_FUNCTION,
\T_IMPLEMENTS,
\T_INSTANCEOF,
\T_NEW,
\T_VARIABLE,
]);
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder(
'leading_backslash_in_global_namespace',
'Whether FQCN is prefixed with backslash when that FQCN is used in global namespace context.',
))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
(new FixerOptionBuilder(
'import_symbols',
'Whether FQCNs should be automatically imported.',
))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
(new FixerOptionBuilder(
'phpdoc_tags',
'Collection of PHPDoc annotation tags where FQCNs should be processed. As of now only simple tags with `@tag \F\Q\C\N` format are supported (no complex types).',
))
->setAllowedTypes(['string[]'])
->setDefault([
'param',
'phpstan-param',
'phpstan-property',
'phpstan-property-read',
'phpstan-property-write',
'phpstan-return',
'phpstan-var',
'property',
'property-read',
'property-write',
'psalm-param',
'psalm-property',
'psalm-property-read',
'psalm-property-write',
'psalm-return',
'psalm-var',
'return',
'see',
'throws',
'var',
])
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$namespaceUsesAnalyzer = new NamespaceUsesAnalyzer();
$functionsAnalyzer = new FunctionsAnalyzer();
$this->symbolsForImport = [];
foreach ($tokens->getNamespaceDeclarations() as $namespaceIndex => $namespace) {
$namespace = $tokens->getNamespaceDeclarations()[$namespaceIndex];
$namespaceName = $namespace->getFullName();
$uses = [];
$lastUse = null;
foreach ($namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace, true) as $use) {
if (!$use->isClass()) {
continue;
}
$fullName = ltrim($use->getFullName(), '\\');
\assert('' !== $fullName);
$uses[$use->getHumanFriendlyType()][$fullName] = $use->getShortName();
$lastUse = $use;
}
$indexDiff = 0;
foreach (true === $this->configuration['import_symbols'] ? [true, false] : [false] as $discoverSymbolsPhase) {
$this->discoveredSymbols = $discoverSymbolsPhase ? [] : null;
$openedCurlyBrackets = 0;
$this->reservedIdentifiersByLevel = [];
for ($index = $namespace->getScopeStartIndex(); $index < $namespace->getScopeEndIndex() + $indexDiff; ++$index) {
$origSize = \count($tokens);
$token = $tokens[$index];
if ($token->equals('{')) {
++$openedCurlyBrackets;
} elseif ($token->equals('}')) {
unset($this->reservedIdentifiersByLevel[$openedCurlyBrackets]);
--$openedCurlyBrackets;
\assert($openedCurlyBrackets >= 0);
} elseif ($token->isGivenKind(\T_VARIABLE)) {
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if (null !== $prevIndex && $tokens[$prevIndex]->isGivenKind(\T_STRING)) {
$this->fixPrevName($tokens, $index, $uses, $namespaceName);
}
} elseif ($token->isGivenKind(\T_DOUBLE_COLON)) {
$this->fixPrevName($tokens, $index, $uses, $namespaceName);
} elseif ($token->isGivenKind(\T_FUNCTION)) {
$this->fixFunction($functionsAnalyzer, $tokens, $index, $uses, $namespaceName);
} elseif ($token->isGivenKind(FCT::T_ATTRIBUTE)) {
$this->fixAttribute($tokens, $index, $uses, $namespaceName);
} elseif ($token->isGivenKind(\T_CATCH)) {
$this->fixCatch($tokens, $index, $uses, $namespaceName);
} elseif ($discoverSymbolsPhase && $token->isGivenKind(self::CLASSY_KINDS)) {
$this->fixNextName($tokens, $index, $uses, $namespaceName);
} elseif ($token->isGivenKind([\T_EXTENDS, \T_IMPLEMENTS])) {
$this->fixExtendsImplements($tokens, $index, $uses, $namespaceName);
} elseif ($token->isGivenKind([\T_INSTANCEOF, \T_NEW, CT::T_USE_TRAIT, CT::T_TYPE_COLON])) {
$this->fixNextName($tokens, $index, $uses, $namespaceName);
} elseif ($discoverSymbolsPhase && $token->isGivenKind(\T_COMMENT) && Preg::match('/#\[\s*('.self::REGEX_CLASS.')/', $token->getContent(), $matches)) { // @TODO: drop when PHP 8.0+ is required
$attributeClass = $matches[1];
$this->determineShortType($attributeClass, 'class', $uses, $namespaceName);
} elseif ($token->isGivenKind(\T_DOC_COMMENT)) {
Preg::matchAll('/\*\h*@(?:psalm-|phpstan-)?(?:template(?:-covariant|-contravariant)?|(?:import-)?type)\h+('.TypeExpression::REGEX_IDENTIFIER.')(?!\S)/i', $token->getContent(), $matches);
foreach ($matches[1] as $reservedIdentifier) {
$this->reservedIdentifiersByLevel[$openedCurlyBrackets + 1][$reservedIdentifier] = true;
}
$this->fixPhpDoc($tokens, $index, $uses, $namespaceName);
}
$indexDiff += \count($tokens) - $origSize;
}
$this->reservedIdentifiersByLevel = [];
if ($discoverSymbolsPhase) {
$this->setupUsesFromDiscoveredSymbols($uses, $namespaceName);
}
}
if ([] !== $this->symbolsForImport) {
if (null !== $lastUse) {
$atIndex = $lastUse->getEndIndex() + 1;
} elseif (0 !== $namespace->getEndIndex()) {
$atIndex = $namespace->getEndIndex() + 1;
} else {
$firstTokenIndex = $tokens->getNextMeaningfulToken($namespace->getScopeStartIndex());
if (null !== $firstTokenIndex && $tokens[$firstTokenIndex]->isGivenKind(\T_DECLARE)) {
$atIndex = $tokens->getNextTokenOfKind($firstTokenIndex, [';']) + 1;
} else {
$atIndex = $namespace->getScopeStartIndex() + 1;
}
}
// Insert all registered FQCNs
$this->createImportProcessor()->insertImports($tokens, $this->symbolsForImport, $atIndex);
$this->symbolsForImport = [];
}
}
}
/**
* @param _Uses $uses
*/
private function refreshUsesCache(array $uses): void
{
if ($this->cacheUsesLast === $uses) {
return;
}
$this->cacheUsesLast = $uses;
$this->cacheUseNameByShortNameLower = [];
$this->cacheUseShortNameByName = [];
$this->cacheUseShortNameByNormalizedName = [];
foreach ($uses as $kind => $kindUses) {
foreach ($kindUses as $useLongName => $useShortName) {
$this->cacheUseNameByShortNameLower[$kind][strtolower($useShortName)] = $useLongName;
$this->cacheUseShortNameByName[$kind][$useLongName] = $useShortName;
/** @var non-empty-string */
$normalizedUseLongName = $this->normalizeFqcn($useLongName);
$this->cacheUseShortNameByNormalizedName[$kind][$normalizedUseLongName] = $useShortName;
}
}
}
private function isReservedIdentifier(string $symbol): bool
{
if (str_contains($symbol, '\\')) { // optimization only
return false;
}
if ((new TypeAnalysis($symbol))->isReservedType()) {
return true;
}
foreach ($this->reservedIdentifiersByLevel as $reservedIdentifiers) {
if (isset($reservedIdentifiers[$symbol])) {
return true;
}
}
return false;
}
/**
* Resolve absolute or relative symbol to normalized FQCN.
*
* @param _ImportType $importKind
* @param _Uses $uses
*
* @return non-empty-string
*/
private function resolveSymbol(string $symbol, string $importKind, array $uses, string $namespaceName): string
{
if (str_starts_with($symbol, '\\')) {
return substr($symbol, 1); // @phpstan-ignore return.type
}
if ($this->isReservedIdentifier($symbol)) {
return $symbol; // @phpstan-ignore return.type
}
$this->refreshUsesCache($uses);
$symbolArr = explode('\\', $symbol, 2);
$shortStartNameLower = strtolower($symbolArr[0]);
if (isset($this->cacheUseNameByShortNameLower[$importKind][$shortStartNameLower])) {
return $this->cacheUseNameByShortNameLower[$importKind][$shortStartNameLower].(isset($symbolArr[1]) ? '\\'.$symbolArr[1] : '');
}
return ('' !== $namespaceName ? $namespaceName.'\\' : '').$symbol; // @phpstan-ignore return.type
}
/**
* Shorten normalized FQCN as much as possible.
*
* @param _ImportType $importKind
* @param _Uses $uses
*/
private function shortenSymbol(string $fqcn, string $importKind, array $uses, string $namespaceName): string
{
if ($this->isReservedIdentifier($fqcn)) {
return $fqcn;
}
$this->refreshUsesCache($uses);
$res = null;
// try to shorten the name using namespace
$iMin = 0;
if (str_starts_with($fqcn, $namespaceName.'\\')) {
$tmpRes = substr($fqcn, \strlen($namespaceName) + 1);
if (!isset($this->cacheUseNameByShortNameLower[$importKind][strtolower(explode('\\', $tmpRes, 2)[0])]) && !$this->isReservedIdentifier($tmpRes)) {
$res = $tmpRes;
$iMin = substr_count($namespaceName, '\\') + 1;
}
}
// try to shorten the name using uses
$tmp = $fqcn;
for ($i = substr_count($fqcn, '\\'); $i >= $iMin; --$i) {
if (isset($this->cacheUseShortNameByName[$importKind][$tmp])) {
$tmpRes = $this->cacheUseShortNameByName[$importKind][$tmp].substr($fqcn, \strlen($tmp));
if (!$this->isReservedIdentifier($tmpRes)) {
$res = $tmpRes;
break;
}
}
if ($i > 0) {
$tmp = substr($tmp, 0, strrpos($tmp, '\\'));
}
}
if (null === $res) {
$normalizedFqcn = $this->normalizeFqcn($fqcn);
$tmpRes = $this->cacheUseShortNameByNormalizedName[$importKind][$normalizedFqcn] ?? null;
if (null !== $tmpRes && !$this->isReservedIdentifier($tmpRes)) {
$res = $tmpRes;
}
}
// shortening is not possible, add leading backslash if needed
if (null === $res) {
$res = $fqcn;
if ('' !== $namespaceName
|| true === $this->configuration['leading_backslash_in_global_namespace']
|| isset($this->cacheUseNameByShortNameLower[$importKind][strtolower(explode('\\', $res, 2)[0])])
) {
$res = '\\'.$res;
}
}
return $res;
}
/**
* @param _Uses $uses
*/
private function setupUsesFromDiscoveredSymbols(array &$uses, string $namespaceName): void
{
foreach ($this->discoveredSymbols as $kind => $discoveredSymbols) {
$discoveredFqcnByShortNameLower = [];
if ('' === $namespaceName) {
foreach ($discoveredSymbols as $symbol) {
if (!str_starts_with($symbol, '\\')) {
$shortStartName = explode('\\', ltrim($symbol, '\\'), 2)[0];
\assert('' !== $shortStartName);
$shortStartNameLower = strtolower($shortStartName);
$discoveredFqcnByShortNameLower[$kind][$shortStartNameLower] = $this->resolveSymbol($shortStartName, $kind, $uses, $namespaceName);
}
}
}
foreach ($uses[$kind] ?? [] as $useLongName => $useShortName) {
$discoveredFqcnByShortNameLower[$kind][strtolower($useShortName)] = $useLongName;
}
$useByShortNameLower = [];
foreach ($uses[$kind] ?? [] as $useShortName) {
$useByShortNameLower[strtolower($useShortName)] = true;
}
uasort($discoveredSymbols, static function ($a, $b) {
$res = str_starts_with($a, '\\') <=> str_starts_with($b, '\\');
if (0 !== $res) {
return $res;
}
return substr_count($a, '\\') <=> substr_count($b, '\\');
});
foreach ($discoveredSymbols as $symbol) {
while (true) {
$shortEndNameLower = strtolower(str_contains($symbol, '\\') ? substr($symbol, (int) strrpos($symbol, '\\') + 1) : $symbol);
if (!isset($discoveredFqcnByShortNameLower[$kind][$shortEndNameLower])) {
$shortStartNameLower = strtolower(explode('\\', ltrim($symbol, '\\'), 2)[0]);
if (str_starts_with($symbol, '\\') || ('' === $namespaceName && !isset($useByShortNameLower[$shortStartNameLower]))
|| !str_contains($symbol, '\\')
) {
$discoveredFqcnByShortNameLower[$kind][$shortEndNameLower] = $this->resolveSymbol($symbol, $kind, $uses, $namespaceName);
break;
}
}
// else short name collision - keep unimported
if (str_starts_with($symbol, '\\') || '' === $namespaceName || !str_contains($symbol, '\\')) {
break;
}
$symbol = substr($symbol, 0, strrpos($symbol, '\\'));
}
}
foreach ($uses[$kind] ?? [] as $useLongName => $useShortName) {
$discoveredLongName = $discoveredFqcnByShortNameLower[$kind][strtolower($useShortName)] ?? null;
if (strtolower($discoveredLongName) === strtolower($useLongName)) {
unset($discoveredFqcnByShortNameLower[$kind][strtolower($useShortName)]);
}
}
foreach ($discoveredFqcnByShortNameLower[$kind] ?? [] as $fqcn) {
$shortenedName = ltrim($this->shortenSymbol($fqcn, $kind, [], $namespaceName), '\\');
if (str_contains($shortenedName, '\\')) { // prevent importing non-namespaced names in global namespace
$shortEndName = str_contains($fqcn, '\\') ? substr($fqcn, (int) strrpos($fqcn, '\\') + 1) : $fqcn;
\assert('' !== $shortEndName);
$uses[$kind][$fqcn] = $shortEndName;
$this->symbolsForImport[$kind][$shortEndName] = $fqcn;
}
}
if (isset($this->symbolsForImport[$kind])) {
ksort($this->symbolsForImport[$kind], \SORT_NATURAL);
}
}
}
/**
* @param _Uses $uses
*/
private function fixFunction(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index, array $uses, string $namespaceName): void
{
$arguments = $functionsAnalyzer->getFunctionArguments($tokens, $index);
foreach ($arguments as $i => $argument) {
$argument = $functionsAnalyzer->getFunctionArguments($tokens, $index)[$i];
if ($argument->hasTypeAnalysis()) {
$this->replaceByShortType($tokens, $argument->getTypeAnalysis(), $uses, $namespaceName);
}
}
$returnTypeAnalysis = $functionsAnalyzer->getFunctionReturnType($tokens, $index);
if (null !== $returnTypeAnalysis) {
$this->replaceByShortType($tokens, $returnTypeAnalysis, $uses, $namespaceName);
}
}
/**
* @param _Uses $uses
*/
private function fixPhpDoc(Tokens $tokens, int $index, array $uses, string $namespaceName): void
{
$allowedTags = $this->configuration['phpdoc_tags'];
if ([] === $allowedTags) {
return;
}
$phpDoc = $tokens[$index];
$phpDocContent = $phpDoc->getContent();
$phpDocContentNew = Preg::replaceCallback('/([*{]\h*@)(\S+)(\h+)('.TypeExpression::REGEX_TYPES.')(?!(?!\})\S)/', function ($matches) use ($allowedTags, $uses, $namespaceName) {
if (!\in_array($matches[2], $allowedTags, true)) {
return $matches[0];
}
return $matches[1].$matches[2].$matches[3].$this->fixPhpDocType($matches[4], $uses, $namespaceName);
}, $phpDocContent);
if ($phpDocContentNew !== $phpDocContent) {
$tokens[$index] = new Token([\T_DOC_COMMENT, $phpDocContentNew]);
}
}
/**
* @param _Uses $uses
*/
private function fixPhpDocType(string $type, array $uses, string $namespaceName): string
{
$typeExpression = new TypeExpression($type, null, []);
$typeExpression = $typeExpression->mapTypes(function (TypeExpression $type) use ($uses, $namespaceName) {
$currentTypeValue = $type->toString();
if ($type->isCompositeType() || !Preg::match('/^'.self::REGEX_CLASS.'$/', $currentTypeValue) || \in_array($currentTypeValue, ['min', 'max'], true)) {
return $type;
}
/** @var non-empty-string $currentTypeValue */
$shortTokens = $this->determineShortType($currentTypeValue, 'class', $uses, $namespaceName);
if (null === $shortTokens) {
return $type;
}
$newTypeValue = implode('', array_map(
static fn (Token $token) => $token->getContent(),
$shortTokens,
));
return $currentTypeValue === $newTypeValue
? $type
: new TypeExpression($newTypeValue, null, []);
});
return $typeExpression->toString();
}
/**
* @param _Uses $uses
*/
private function fixExtendsImplements(Tokens $tokens, int $index, array $uses, string $namespaceName): void
{
// We handle `extends` and `implements` with similar logic, but we need to exit the loop under different conditions.
$isExtends = $tokens[$index]->isGivenKind(\T_EXTENDS);
$index = $tokens->getNextMeaningfulToken($index);
$typeStartIndex = null;
$typeEndIndex = null;
while (true) {
if ($tokens[$index]->equalsAny([',', '{', [\T_IMPLEMENTS]])) {
if (null !== $typeStartIndex) {
$index += $this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName);
}
$typeStartIndex = null;
if ($tokens[$index]->equalsAny($isExtends ? [[\T_IMPLEMENTS], '{'] : ['{'])) {
break;
}
} else {
if (null === $typeStartIndex) {
$typeStartIndex = $index;
}
$typeEndIndex = $index;
}
$index = $tokens->getNextMeaningfulToken($index);
}
}
/**
* @param _Uses $uses
*/
private function fixCatch(Tokens $tokens, int $index, array $uses, string $namespaceName): void
{
$index = $tokens->getNextMeaningfulToken($index); // '('
$index = $tokens->getNextMeaningfulToken($index); // first part of first exception class to be caught
$typeStartIndex = null;
$typeEndIndex = null;
while (true) {
if ($tokens[$index]->equalsAny([')', [\T_VARIABLE], [CT::T_TYPE_ALTERNATION]])) {
if (null === $typeStartIndex) {
break;
}
$index += $this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName);
$typeStartIndex = null;
if ($tokens[$index]->equals(')')) {
break;
}
} else {
if (null === $typeStartIndex) {
$typeStartIndex = $index;
}
$typeEndIndex = $index;
}
$index = $tokens->getNextMeaningfulToken($index);
}
}
/**
* @param _Uses $uses
*/
private function fixAttribute(Tokens $tokens, int $index, array $uses, string $namespaceName): void
{
$attributeAnalysis = AttributeAnalyzer::collectOne($tokens, $index);
foreach ($attributeAnalysis->getAttributes() as $attribute) {
$index = $attribute['start'];
while ($tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) {
$index = $tokens->getPrevMeaningfulToken($index);
}
$this->fixNextName($tokens, $index, $uses, $namespaceName);
}
}
/**
* @param _Uses $uses
*/
private function fixPrevName(Tokens $tokens, int $index, array $uses, string $namespaceName): void
{
$typeStartIndex = null;
$typeEndIndex = null;
while (true) {
$index = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$index]->isObjectOperator()) {
break;
}
if ($tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) {
$typeStartIndex = $index;
if (null === $typeEndIndex) {
$typeEndIndex = $index;
}
} else {
if (null !== $typeEndIndex) {
$this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName);
}
break;
}
}
}
/**
* @param _Uses $uses
*/
private function fixNextName(Tokens $tokens, int $index, array $uses, string $namespaceName): void
{
$typeStartIndex = null;
$typeEndIndex = null;
while (true) {
$index = $tokens->getNextMeaningfulToken($index);
if ($tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) {
if (null === $typeStartIndex) {
$typeStartIndex = $index;
}
$typeEndIndex = $index;
} else {
if (null !== $typeStartIndex) {
$this->shortenClassIfPossible($tokens, $typeStartIndex, $typeEndIndex, $uses, $namespaceName);
}
break;
}
}
}
/**
* @param _Uses $uses
*/
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | true |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Import/GroupImportFixer.php | src/Fixer/Import/GroupImportFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Import;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Utils;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* group_types?: list<string>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* group_types: list<string>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Volodymyr Kupriienko <vldmr.kuprienko@gmail.com>
* @author Greg Korba <greg@codito.dev>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class GroupImportFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/** @internal */
public const GROUP_CLASSY = 'classy';
/** @internal */
public const GROUP_CONSTANTS = 'constants';
/** @internal */
public const GROUP_FUNCTIONS = 'functions';
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There MUST be group use for the same namespaces.',
[
new CodeSample(
"<?php\nuse Foo\\Bar;\nuse Foo\\Baz;\n",
),
new CodeSample(
<<<'PHP'
<?php
use A\Foo;
use function B\foo;
use A\Bar;
use function B\bar;
PHP,
['group_types' => [self::GROUP_CLASSY]],
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_USE);
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
$allowedTypes = [self::GROUP_CLASSY, self::GROUP_FUNCTIONS, self::GROUP_CONSTANTS];
return new FixerConfigurationResolver([
(new FixerOptionBuilder('group_types', 'Defines the order of import types.'))
->setAllowedTypes(['string[]'])
->setAllowedValues([static function (array $types) use ($allowedTypes): bool {
foreach ($types as $type) {
if (!\in_array($type, $allowedTypes, true)) {
throw new InvalidOptionsException(
\sprintf(
'Invalid group type: %s, allowed types: %s.',
$type,
Utils::naturalLanguageJoin($allowedTypes),
),
);
}
}
return true;
}])
->setDefault($allowedTypes)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$useWithSameNamespaces = $this->getSameNamespacesByType($tokens);
if ([] === $useWithSameNamespaces) {
return;
}
$typeMap = [
NamespaceUseAnalysis::TYPE_CLASS => self::GROUP_CLASSY,
NamespaceUseAnalysis::TYPE_FUNCTION => self::GROUP_FUNCTIONS,
NamespaceUseAnalysis::TYPE_CONSTANT => self::GROUP_CONSTANTS,
];
// As a first step we need to remove all the use statements for the enabled import types.
// We can't add new group imports yet, because we need to operate on previously determined token indices for all types.
foreach ($useWithSameNamespaces as $type => $uses) {
if (!\in_array($typeMap[$type], $this->configuration['group_types'], true)) {
continue;
}
$this->removeSingleUseStatements($uses, $tokens);
}
foreach ($useWithSameNamespaces as $type => $uses) {
if (!\in_array($typeMap[$type], $this->configuration['group_types'], true)) {
continue;
}
$this->addGroupUseStatements($uses, $tokens);
}
}
/**
* Gets namespace use analyzers with same namespaces.
*
* @return array<NamespaceUseAnalysis::TYPE_*, non-empty-list<NamespaceUseAnalysis>>
*/
private function getSameNamespacesByType(Tokens $tokens): array
{
$useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens);
if (0 === \count($useDeclarations)) {
return [];
}
$allNamespaceAndType = array_map(
fn (NamespaceUseAnalysis $useDeclaration): string => $this->getNamespaceNameWithSlash($useDeclaration).$useDeclaration->getType(),
$useDeclarations,
);
$sameNamespaces = array_filter(array_count_values($allNamespaceAndType), static fn (int $count): bool => $count > 1);
$sameNamespaces = array_keys($sameNamespaces);
$sameNamespaceAnalysis = array_filter($useDeclarations, function (NamespaceUseAnalysis $useDeclaration) use ($sameNamespaces): bool {
$namespaceNameAndType = $this->getNamespaceNameWithSlash($useDeclaration).$useDeclaration->getType();
return \in_array($namespaceNameAndType, $sameNamespaces, true);
});
usort($sameNamespaceAnalysis, function (NamespaceUseAnalysis $a, NamespaceUseAnalysis $b): int {
$namespaceA = $this->getNamespaceNameWithSlash($a);
$namespaceB = $this->getNamespaceNameWithSlash($b);
$namespaceDifference = \strlen($namespaceA) <=> \strlen($namespaceB);
return 0 !== $namespaceDifference ? $namespaceDifference : $a->getFullName() <=> $b->getFullName();
});
$sameNamespaceAnalysisByType = [];
foreach ($sameNamespaceAnalysis as $analysis) {
$sameNamespaceAnalysisByType[$analysis->getType()][] = $analysis;
}
ksort($sameNamespaceAnalysisByType);
return $sameNamespaceAnalysisByType;
}
/**
* @param list<NamespaceUseAnalysis> $statements
*/
private function removeSingleUseStatements(array $statements, Tokens $tokens): void
{
foreach ($statements as $useDeclaration) {
$index = $useDeclaration->getStartIndex();
$endIndex = $useDeclaration->getEndIndex();
$useStatementTokens = [\T_USE, \T_WHITESPACE, \T_STRING, \T_NS_SEPARATOR, \T_AS, CT::T_CONST_IMPORT, CT::T_FUNCTION_IMPORT];
while ($index !== $endIndex) {
if ($tokens[$index]->isGivenKind($useStatementTokens)) {
$tokens->clearAt($index);
}
++$index;
}
if (isset($tokens[$index]) && $tokens[$index]->equals(';')) {
$tokens->clearAt($index);
}
++$index;
if (isset($tokens[$index]) && $tokens[$index]->isGivenKind(\T_WHITESPACE)) {
$tokens->clearAt($index);
}
}
}
/**
* @param list<NamespaceUseAnalysis> $statements
*/
private function addGroupUseStatements(array $statements, Tokens $tokens): void
{
$currentUseDeclaration = null;
$insertIndex = $statements[0]->getStartIndex();
// If group import was inserted in place of removed imports, it may have more tokens than before,
// and indices stored in imports of another type can be out-of-sync, and can point in the middle of group import.
// Let's move the pointer to the closest empty token (erased single import).
if (null !== $tokens[$insertIndex]->getId() || '' !== $tokens[$insertIndex]->getContent()) {
do {
++$insertIndex;
} while (null !== $tokens[$insertIndex]->getId() || '' !== $tokens[$insertIndex]->getContent());
}
foreach ($statements as $index => $useDeclaration) {
if ($this->areDeclarationsDifferent($currentUseDeclaration, $useDeclaration)) {
$currentUseDeclaration = $useDeclaration;
$insertIndex += $this->createNewGroup(
$tokens,
$insertIndex,
$useDeclaration,
rtrim($this->getNamespaceNameWithSlash($currentUseDeclaration), '\\'),
);
} else {
$newTokens = [
new Token(','),
new Token([\T_WHITESPACE, ' ']),
];
if ($useDeclaration->isAliased()) {
$tokens->insertAt($insertIndex, $newTokens);
$insertIndex += \count($newTokens);
$newTokens = [];
$insertIndex += $this->insertToGroupUseWithAlias($tokens, $insertIndex, $useDeclaration);
}
$newTokens[] = new Token([\T_STRING, $useDeclaration->getShortName()]);
if (!isset($statements[$index + 1]) || $this->areDeclarationsDifferent($currentUseDeclaration, $statements[$index + 1])) {
$newTokens[] = new Token([CT::T_GROUP_IMPORT_BRACE_CLOSE, '}']);
$newTokens[] = new Token(';');
$newTokens[] = new Token([\T_WHITESPACE, "\n"]);
}
$tokens->insertAt($insertIndex, $newTokens);
$insertIndex += \count($newTokens);
}
}
}
private function getNamespaceNameWithSlash(NamespaceUseAnalysis $useDeclaration): string
{
$position = strrpos($useDeclaration->getFullName(), '\\');
if (false === $position || 0 === $position) {
return $useDeclaration->getFullName();
}
return substr($useDeclaration->getFullName(), 0, $position + 1);
}
/**
* Insert use with alias to the group.
*/
private function insertToGroupUseWithAlias(Tokens $tokens, int $insertIndex, NamespaceUseAnalysis $useDeclaration): int
{
$newTokens = [
new Token([\T_STRING, substr($useDeclaration->getFullName(), (int) strripos($useDeclaration->getFullName(), '\\') + 1)]),
new Token([\T_WHITESPACE, ' ']),
new Token([\T_AS, 'as']),
new Token([\T_WHITESPACE, ' ']),
];
$tokens->insertAt($insertIndex, $newTokens);
return \count($newTokens);
}
/**
* Creates new use statement group.
*/
private function createNewGroup(Tokens $tokens, int $insertIndex, NamespaceUseAnalysis $useDeclaration, string $currentNamespace): int
{
$insertedTokens = 0;
$newTokens = [
new Token([\T_USE, 'use']),
new Token([\T_WHITESPACE, ' ']),
];
if ($useDeclaration->isFunction() || $useDeclaration->isConstant()) {
$importStatementParams = $useDeclaration->isFunction()
? [CT::T_FUNCTION_IMPORT, 'function']
: [CT::T_CONST_IMPORT, 'const'];
$newTokens[] = new Token($importStatementParams);
$newTokens[] = new Token([\T_WHITESPACE, ' ']);
}
$namespaceParts = explode('\\', $currentNamespace);
foreach ($namespaceParts as $part) {
$newTokens[] = new Token([\T_STRING, $part]);
$newTokens[] = new Token([\T_NS_SEPARATOR, '\\']);
}
$newTokens[] = new Token([CT::T_GROUP_IMPORT_BRACE_OPEN, '{']);
$newTokensCount = \count($newTokens);
$tokens->insertAt($insertIndex, $newTokens);
$insertedTokens += $newTokensCount;
$insertIndex += $newTokensCount;
if ($useDeclaration->isAliased()) {
$inserted = $this->insertToGroupUseWithAlias($tokens, $insertIndex + 1, $useDeclaration) + 1;
$insertedTokens += $inserted;
$insertIndex += $inserted;
}
$tokens->insertAt($insertIndex, new Token([\T_STRING, $useDeclaration->getShortName()]));
return ++$insertedTokens;
}
/**
* Check if namespace use analyses are different.
*/
private function areDeclarationsDifferent(?NamespaceUseAnalysis $analysis1, ?NamespaceUseAnalysis $analysis2): bool
{
if (null === $analysis1 || null === $analysis2) {
return true;
}
$namespaceName1 = $this->getNamespaceNameWithSlash($analysis1);
$namespaceName2 = $this->getNamespaceNameWithSlash($analysis2);
return $namespaceName1 !== $namespaceName2 || $analysis1->getType() !== $analysis2->getType();
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Import/NoUnneededImportAliasFixer.php | src/Fixer/Import/NoUnneededImportAliasFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Import;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoUnneededImportAliasFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Imports should not be aliased as the same name.',
[new CodeSample("<?php\nuse A\\B\\Foo as Foo;\n")],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAllTokenKindsFound([\T_USE, \T_AS]);
}
/**
* {@inheritdoc}
*
* Must run before NoSinglelineWhitespaceBeforeSemicolonsFixer.
* Must run after PhpUnitNamespacedFixer.
*/
public function getPriority(): int
{
return 1;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = \count($tokens) - 1; 0 <= $index; --$index) {
if (!$tokens[$index]->isGivenKind(\T_AS)) {
continue;
}
$aliasIndex = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$aliasIndex]->isGivenKind(\T_STRING)) {
continue;
}
$importIndex = $tokens->getPrevMeaningfulToken($index);
if (!$tokens[$importIndex]->isGivenKind(\T_STRING)) {
continue;
}
if ($tokens[$importIndex]->getContent() !== $tokens[$aliasIndex]->getContent()) {
continue;
}
do {
$importIndex = $tokens->getPrevMeaningfulToken($importIndex);
} while ($tokens[$importIndex]->isGivenKind([\T_NS_SEPARATOR, \T_STRING, \T_AS]) || $tokens[$importIndex]->equals(','));
if ($tokens[$importIndex]->isGivenKind([CT::T_FUNCTION_IMPORT, CT::T_CONST_IMPORT])) {
$importIndex = $tokens->getPrevMeaningfulToken($importIndex);
}
if (!$tokens[$importIndex]->isGivenKind([\T_USE, CT::T_GROUP_IMPORT_BRACE_OPEN])) {
continue;
}
$tokens->clearTokenAndMergeSurroundingWhitespace($aliasIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Import/SingleLineAfterImportsFixer.php | src/Fixer/Import/SingleLineAfterImportsFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Import;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use PhpCsFixer\Utils;
/**
* Fixer for rules defined in PSR2 ¶3.
*
* @author Ceeram <ceeram@cakephp.org>
* @author Graham Campbell <hello@gjcampbell.co.uk>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class SingleLineAfterImportsFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_USE);
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Each namespace use MUST go on its own line and there MUST be one blank line after the use statements block.',
[
new CodeSample(
<<<'PHP'
<?php
namespace Foo;
use Bar;
use Baz;
final class Example
{
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
namespace Foo;
use Bar;
use Baz;
final class Example
{
}
PHP,
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after NoUnusedImportsFixer.
*/
public function getPriority(): int
{
return -11;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$ending = $this->whitespacesConfig->getLineEnding();
$tokensAnalyzer = new TokensAnalyzer($tokens);
$added = 0;
foreach ($tokensAnalyzer->getImportUseIndexes() as $index) {
$index += $added;
$indent = '';
// if previous line ends with comment and current line starts with whitespace, use current indent
if ($tokens[$index - 1]->isWhitespace(" \t") && $tokens[$index - 2]->isGivenKind(\T_COMMENT)) {
$indent = $tokens[$index - 1]->getContent();
} elseif ($tokens[$index - 1]->isWhitespace()) {
$indent = Utils::calculateTrailingWhitespaceIndent($tokens[$index - 1]);
}
$semicolonIndex = $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]); // Handle insert index for inline T_COMMENT with whitespace after semicolon
$insertIndex = $semicolonIndex;
if ($tokens[$semicolonIndex]->isGivenKind(\T_CLOSE_TAG)) {
if ($tokens[$insertIndex - 1]->isWhitespace()) {
--$insertIndex;
}
$tokens->insertAt($insertIndex, new Token(';'));
++$added;
}
if ($semicolonIndex === \count($tokens) - 1) {
$tokens->insertAt($insertIndex + 1, new Token([\T_WHITESPACE, $ending.$ending.$indent]));
++$added;
} else {
$newline = $ending;
$tokens[$semicolonIndex]->isGivenKind(\T_CLOSE_TAG) ? --$insertIndex : ++$insertIndex;
if ($tokens[$insertIndex]->isWhitespace(" \t") && $tokens[$insertIndex + 1]->isComment()) {
++$insertIndex;
}
// Increment insert index for inline T_COMMENT or T_DOC_COMMENT
if ($tokens[$insertIndex]->isComment()) {
++$insertIndex;
}
$afterSemicolon = $tokens->getNextMeaningfulToken($semicolonIndex);
if (null === $afterSemicolon || !$tokens[$afterSemicolon]->isGivenKind(\T_USE)) {
$newline .= $ending;
}
if ($tokens[$insertIndex]->isWhitespace()) {
$nextToken = $tokens[$insertIndex];
if (2 === substr_count($nextToken->getContent(), "\n")) {
continue;
}
$nextMeaningfulAfterUseIndex = $tokens->getNextMeaningfulToken($insertIndex);
if (null !== $nextMeaningfulAfterUseIndex && $tokens[$nextMeaningfulAfterUseIndex]->isGivenKind(\T_USE)) {
if (substr_count($nextToken->getContent(), "\n") < 1) {
$tokens[$insertIndex] = new Token([\T_WHITESPACE, $newline.$indent.ltrim($nextToken->getContent())]);
}
} else {
$tokens[$insertIndex] = new Token([\T_WHITESPACE, $newline.$indent.ltrim($nextToken->getContent())]);
}
} else {
$tokens->insertAt($insertIndex, new Token([\T_WHITESPACE, $newline.$indent]));
++$added;
}
}
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Import/NoLeadingImportSlashFixer.php | src/Fixer/Import/NoLeadingImportSlashFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Import;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @author Carlos Cirello <carlos.cirello.nl@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoLeadingImportSlashFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Remove leading slashes in `use` clauses.',
[new CodeSample("<?php\nnamespace Foo;\nuse \\Bar;\n")],
);
}
/**
* {@inheritdoc}
*
* Must run before OrderedImportsFixer.
* Must run after NoUnusedImportsFixer, SingleImportPerStatementFixer.
*/
public function getPriority(): int
{
return -20;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_USE);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
$usesIndices = $tokensAnalyzer->getImportUseIndexes();
foreach ($usesIndices as $idx) {
$nextTokenIdx = $tokens->getNextMeaningfulToken($idx);
$nextToken = $tokens[$nextTokenIdx];
if ($nextToken->isGivenKind(\T_NS_SEPARATOR)) {
$this->removeLeadingImportSlash($tokens, $nextTokenIdx);
} elseif ($nextToken->isGivenKind([CT::T_FUNCTION_IMPORT, CT::T_CONST_IMPORT])) {
$nextTokenIdx = $tokens->getNextMeaningfulToken($nextTokenIdx);
if ($tokens[$nextTokenIdx]->isGivenKind(\T_NS_SEPARATOR)) {
$this->removeLeadingImportSlash($tokens, $nextTokenIdx);
}
}
}
}
private function removeLeadingImportSlash(Tokens $tokens, int $index): void
{
$previousIndex = $tokens->getPrevNonWhitespace($index);
if (
$previousIndex < $index - 1
|| $tokens[$previousIndex]->isComment()
) {
$tokens->clearAt($index);
return;
}
$tokens[$index] = new Token([\T_WHITESPACE, ' ']);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Import/NoUnusedImportsFixer.php | src/Fixer/Import/NoUnusedImportsFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Import;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoUnusedImportsFixer extends AbstractFixer
{
private const TOKENS_NOT_BEFORE_FUNCTION_CALL = [\T_NEW, FCT::T_ATTRIBUTE];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Unused `use` statements must be removed.',
[new CodeSample("<?php\nuse \\DateTime;\nuse \\Exception;\n\nnew DateTime();\n")],
);
}
/**
* {@inheritdoc}
*
* Must run before BlankLineAfterNamespaceFixer, NoExtraBlankLinesFixer, NoLeadingImportSlashFixer, SingleLineAfterImportsFixer.
* Must run after ClassKeywordRemoveFixer, GlobalNamespaceImportFixer, PhpUnitDedicateAssertFixer, PhpUnitFqcnAnnotationFixer.
*/
public function getPriority(): int
{
return -10;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_USE);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens, true);
if (0 === \count($useDeclarations)) {
return;
}
foreach ($tokens->getNamespaceDeclarations() as $namespace) {
$currentNamespaceUseDeclarations = [];
$currentNamespaceUseDeclarationIndices = [];
foreach ($useDeclarations as $useDeclaration) {
if ($useDeclaration->getStartIndex() >= $namespace->getScopeStartIndex() && $useDeclaration->getEndIndex() <= $namespace->getScopeEndIndex()) {
$currentNamespaceUseDeclarations[] = $useDeclaration;
$currentNamespaceUseDeclarationIndices[$useDeclaration->getStartIndex()] = $useDeclaration->getEndIndex();
}
}
foreach ($currentNamespaceUseDeclarations as $useDeclaration) {
if (!$this->isImportUsed($tokens, $namespace, $useDeclaration, $currentNamespaceUseDeclarationIndices)) {
$this->removeUseDeclaration($tokens, $useDeclaration);
}
}
$this->removeUsesInSameNamespace($tokens, $currentNamespaceUseDeclarations, $namespace);
}
}
/**
* @param array<int, int> $ignoredIndices indices of the use statements themselves that should not be checked as being "used"
*/
private function isImportUsed(Tokens $tokens, NamespaceAnalysis $namespace, NamespaceUseAnalysis $import, array $ignoredIndices): bool
{
$analyzer = new TokensAnalyzer($tokens);
$gotoLabelAnalyzer = new GotoLabelAnalyzer();
$namespaceEndIndex = $namespace->getScopeEndIndex();
$inAttribute = false;
for ($index = $namespace->getScopeStartIndex(); $index <= $namespaceEndIndex; ++$index) {
$token = $tokens[$index];
if ($token->isGivenKind(FCT::T_ATTRIBUTE)) {
$inAttribute = true;
continue;
}
if ($token->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) {
$inAttribute = false;
continue;
}
if (isset($ignoredIndices[$index])) {
$index = $ignoredIndices[$index];
continue;
}
if ($token->isGivenKind(\T_STRING)) {
if (0 !== strcasecmp($import->getShortName(), $token->getContent())) {
continue;
}
$prevMeaningfulToken = $tokens[$tokens->getPrevMeaningfulToken($index)];
if ($prevMeaningfulToken->isGivenKind(\T_NAMESPACE)) {
$index = $tokens->getNextTokenOfKind($index, [';', '{', [\T_CLOSE_TAG]]);
continue;
}
if (
$prevMeaningfulToken->isGivenKind([\T_NS_SEPARATOR, \T_FUNCTION, \T_CONST, \T_DOUBLE_COLON])
|| $prevMeaningfulToken->isObjectOperator()
) {
continue;
}
if ($inAttribute) {
return true;
}
$nextMeaningfulIndex = $tokens->getNextMeaningfulToken($index);
if ($gotoLabelAnalyzer->belongsToGoToLabel($tokens, $nextMeaningfulIndex)) {
continue;
}
$nextMeaningfulToken = $tokens[$nextMeaningfulIndex];
if ($analyzer->isConstantInvocation($index)) {
$type = NamespaceUseAnalysis::TYPE_CONSTANT;
} elseif ($nextMeaningfulToken->equals('(') && !$prevMeaningfulToken->isGivenKind(self::TOKENS_NOT_BEFORE_FUNCTION_CALL)) {
$type = NamespaceUseAnalysis::TYPE_FUNCTION;
} else {
$type = NamespaceUseAnalysis::TYPE_CLASS;
}
if ($import->getType() === $type) {
return true;
}
continue;
}
if ($token->isComment()
&& Preg::match(
'/(?<![[:alnum:]\$_])(?<!\\\)'.$import->getShortName().'(?![[:alnum:]_])/i',
$token->getContent(),
)
) {
return true;
}
}
return false;
}
private function removeUseDeclaration(
Tokens $tokens,
NamespaceUseAnalysis $useDeclaration,
bool $forceCompleteRemoval = false
): void {
[$start, $end] = ($useDeclaration->isInMulti() && !$forceCompleteRemoval)
? [$useDeclaration->getChunkStartIndex(), $useDeclaration->getChunkEndIndex()]
: [$useDeclaration->getStartIndex(), $useDeclaration->getEndIndex()];
$loopStartIndex = $useDeclaration->isInMulti() || $forceCompleteRemoval ? $end : $end - 1;
for ($index = $loopStartIndex; $index >= $start; --$index) {
if ($tokens[$index]->isComment()) {
continue;
}
if (!$tokens[$index]->isWhitespace() || !str_contains($tokens[$index]->getContent(), "\n")) {
$tokens->clearAt($index);
continue;
}
// when multi line white space keep the line feed if the previous token is a comment
$prevIndex = $tokens->getPrevNonWhitespace($index);
if ($tokens[$prevIndex]->isComment()) {
$content = $tokens[$index]->getContent();
$tokens[$index] = new Token([\T_WHITESPACE, substr($content, strrpos($content, "\n"))]); // preserve indent only
} else {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
}
// For multi-use import statements the tokens containing FQN were already removed in the loop above.
// We need to clean up tokens around the ex-chunk to keep the correct syntax and achieve proper formatting.
if (!$forceCompleteRemoval && $useDeclaration->isInMulti()) {
$this->cleanUpAfterImportChunkRemoval($tokens, $useDeclaration);
return;
}
if ($tokens[$useDeclaration->getEndIndex()]->equals(';')) { // do not remove `? >`
$tokens->clearAt($useDeclaration->getEndIndex());
}
$this->cleanUpSurroundingNewLines($tokens, $useDeclaration);
}
/**
* @param list<NamespaceUseAnalysis> $useDeclarations
*/
private function removeUsesInSameNamespace(Tokens $tokens, array $useDeclarations, NamespaceAnalysis $namespaceDeclaration): void
{
$namespace = $namespaceDeclaration->getFullName();
$nsLength = \strlen($namespace.'\\');
foreach ($useDeclarations as $useDeclaration) {
if ($useDeclaration->isAliased()) {
continue;
}
$useDeclarationFullName = ltrim($useDeclaration->getFullName(), '\\');
if (!str_starts_with($useDeclarationFullName, $namespace.'\\')) {
continue;
}
$partName = substr($useDeclarationFullName, $nsLength);
if (!str_contains($partName, '\\')) {
$this->removeUseDeclaration($tokens, $useDeclaration);
}
}
}
private function cleanUpAfterImportChunkRemoval(Tokens $tokens, NamespaceUseAnalysis $useDeclaration): void
{
$beforeChunkIndex = $tokens->getPrevMeaningfulToken($useDeclaration->getChunkStartIndex());
$afterChunkIndex = $tokens->getNextMeaningfulToken($useDeclaration->getChunkEndIndex());
$hasNonEmptyTokenBefore = $this->scanForNonEmptyTokensUntilNewLineFound(
$tokens,
$afterChunkIndex,
-1,
);
$hasNonEmptyTokenAfter = $this->scanForNonEmptyTokensUntilNewLineFound(
$tokens,
$afterChunkIndex,
1,
);
// We don't want to merge consequent new lines with indentation (leading to e.g. `\n \n `),
// so it's safe to merge whitespace only if there is any non-empty token before or after the chunk.
$mergingSurroundingWhitespaceIsSafe = $hasNonEmptyTokenBefore[1] || $hasNonEmptyTokenAfter[1];
$clearToken = static function (int $index) use ($tokens, $mergingSurroundingWhitespaceIsSafe): void {
if ($mergingSurroundingWhitespaceIsSafe) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
} else {
$tokens->clearAt($index);
}
};
if ($tokens[$afterChunkIndex]->equals(',')) {
$clearToken($afterChunkIndex);
} elseif ($tokens[$beforeChunkIndex]->equals(',')) {
$clearToken($beforeChunkIndex);
}
// Ensure there's a single space where applicable, otherwise no space (before comma, before closing brace)
for ($index = $beforeChunkIndex; $index <= $afterChunkIndex; ++$index) {
if (null === $tokens[$index]->getId() || !$tokens[$index]->isWhitespace(' ')) {
continue;
}
$nextTokenIndex = $tokens->getNextMeaningfulToken($index);
if (
$tokens[$nextTokenIndex]->equals(',')
|| $tokens[$nextTokenIndex]->equals(';')
|| $tokens[$nextTokenIndex]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)
) {
$tokens->clearAt($index);
} else {
$tokens[$index] = new Token([\T_WHITESPACE, ' ']);
}
$prevTokenIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevTokenIndex]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) {
$tokens->clearAt($index);
}
}
$this->removeLineIfEmpty($tokens, $useDeclaration);
$this->removeImportStatementIfEmpty($tokens, $useDeclaration);
}
private function cleanUpSurroundingNewLines(Tokens $tokens, NamespaceUseAnalysis $useDeclaration): void
{
$prevIndex = $useDeclaration->getStartIndex() - 1;
$prevToken = $tokens[$prevIndex];
if ($prevToken->isWhitespace()) {
$content = rtrim($prevToken->getContent(), " \t");
$tokens->ensureWhitespaceAtIndex($prevIndex, 0, $content);
$prevToken = $tokens[$prevIndex];
}
if (!isset($tokens[$useDeclaration->getEndIndex() + 1])) {
return;
}
$nextIndex = $tokens->getNonEmptySibling($useDeclaration->getEndIndex(), 1);
if (null === $nextIndex) {
return;
}
$nextToken = $tokens[$nextIndex];
if ($nextToken->isWhitespace()) {
$content = Preg::replace(
"#^\r\n|^\n#",
'',
ltrim($nextToken->getContent(), " \t"),
1,
);
$tokens->ensureWhitespaceAtIndex($nextIndex, 0, $content);
$nextToken = $tokens[$nextIndex];
}
if ($prevToken->isWhitespace() && $nextToken->isWhitespace()) {
$content = $prevToken->getContent().$nextToken->getContent();
$tokens->ensureWhitespaceAtIndex($nextIndex, 0, $content);
$tokens->clearAt($prevIndex);
}
}
private function removeImportStatementIfEmpty(Tokens $tokens, NamespaceUseAnalysis $useDeclaration): void
{
// First we look for empty groups where all chunks were removed (`use Foo\{};`).
// We're only interested in ending brace if its index is between start and end of the import statement.
$endingBraceIndex = $tokens->getPrevTokenOfKind(
$useDeclaration->getEndIndex(),
[[CT::T_GROUP_IMPORT_BRACE_CLOSE]],
);
if ($endingBraceIndex > $useDeclaration->getStartIndex()) {
$openingBraceIndex = $tokens->getPrevMeaningfulToken($endingBraceIndex);
if ($tokens[$openingBraceIndex]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) {
$this->removeUseDeclaration($tokens, $useDeclaration, true);
}
}
// Second we look for empty groups where all comma-separated chunks were removed (`use;`).
$beforeSemicolonIndex = $tokens->getPrevMeaningfulToken($useDeclaration->getEndIndex());
if (
$tokens[$beforeSemicolonIndex]->isGivenKind(\T_USE)
|| \in_array($tokens[$beforeSemicolonIndex]->getContent(), ['function', 'const'], true)
) {
$this->removeUseDeclaration($tokens, $useDeclaration, true);
}
}
private function removeLineIfEmpty(Tokens $tokens, NamespaceUseAnalysis $useAnalysis): void
{
if (!$useAnalysis->isInMulti()) {
return;
}
$hasNonEmptyTokenBefore = $this->scanForNonEmptyTokensUntilNewLineFound(
$tokens,
$useAnalysis->getChunkStartIndex(),
-1,
);
$hasNonEmptyTokenAfter = $this->scanForNonEmptyTokensUntilNewLineFound(
$tokens,
$useAnalysis->getChunkEndIndex(),
1,
);
if (
\is_int($hasNonEmptyTokenBefore[0])
&& !$hasNonEmptyTokenBefore[1]
&& \is_int($hasNonEmptyTokenAfter[0])
&& !$hasNonEmptyTokenAfter[1]
) {
$tokens->clearRange($hasNonEmptyTokenBefore[0], $hasNonEmptyTokenAfter[0] - 1);
}
}
/**
* Returns tuple with the index of first token with whitespace containing new line char
* and a flag if any non-empty token was found along the way.
*
* @param -1|1 $direction
*
* @return array{0: null|int, 1: bool}
*/
private function scanForNonEmptyTokensUntilNewLineFound(Tokens $tokens, int $index, int $direction): array
{
$hasNonEmptyToken = false;
$newLineTokenIndex = null;
// Iterate until we find new line OR we get out of $tokens bounds (next sibling index is `null`).
while (\is_int($index)) {
$index = $tokens->getNonEmptySibling($index, $direction);
if (null === $index || null === $tokens[$index]->getId()) {
continue;
}
if (!$tokens[$index]->isWhitespace()) {
$hasNonEmptyToken = true;
} elseif (str_starts_with($tokens[$index]->getContent(), "\n")) {
$newLineTokenIndex = $index;
break;
}
}
return [$newLineTokenIndex, $hasNonEmptyToken];
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Import/GlobalNamespaceImportFixer.php | src/Fixer/Import/GlobalNamespaceImportFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Import;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\Annotation;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\ClassyAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Processor\ImportProcessor;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* import_classes?: bool|null,
* import_constants?: bool|null,
* import_functions?: bool|null,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* import_classes: bool|null,
* import_constants: bool|null,
* import_functions: bool|null,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Gregor Harlan <gharlan@web.de>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class GlobalNamespaceImportFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private ImportProcessor $importProcessor;
public function __construct()
{
parent::__construct();
$this->importProcessor = new ImportProcessor($this->whitespacesConfig);
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Imports or fully qualifies global classes/functions/constants.',
[
new CodeSample(
<<<'PHP'
<?php
namespace Foo;
$d = new \DateTimeImmutable();
PHP,
),
new CodeSample(
<<<'PHP'
<?php
namespace Foo;
if (\count($x)) {
/** @var \DateTimeImmutable $d */
$d = new \DateTimeImmutable();
$p = \M_PI;
}
PHP,
['import_classes' => true, 'import_constants' => true, 'import_functions' => true],
),
new CodeSample(
<<<'PHP'
<?php
namespace Foo;
use DateTimeImmutable;
use function count;
use const M_PI;
if (count($x)) {
/** @var DateTimeImmutable $d */
$d = new DateTimeImmutable();
$p = M_PI;
}
PHP,
['import_classes' => false, 'import_constants' => false, 'import_functions' => false],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before NoUnusedImportsFixer, OrderedImportsFixer, StatementIndentationFixer.
* Must run after NativeConstantInvocationFixer, NativeFunctionInvocationFixer, StringableForToStringFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([\T_DOC_COMMENT, \T_NS_SEPARATOR, \T_USE])
&& $tokens->isTokenKindFound(\T_NAMESPACE)
&& 1 === $tokens->countTokenKind(\T_NAMESPACE)
&& $tokens->isMonolithicPhp();
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$namespaceAnalyses = $tokens->getNamespaceDeclarations();
if (1 !== \count($namespaceAnalyses) || $namespaceAnalyses[0]->isGlobalNamespace()) {
return;
}
$useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens);
$newImports = [];
if (true === $this->configuration['import_constants']) {
$newImports['const'] = $this->importConstants($tokens, $useDeclarations);
} elseif (false === $this->configuration['import_constants']) {
$this->fullyQualifyConstants($tokens, $useDeclarations);
}
if (true === $this->configuration['import_functions']) {
$newImports['function'] = $this->importFunctions($tokens, $useDeclarations);
} elseif (false === $this->configuration['import_functions']) {
$this->fullyQualifyFunctions($tokens, $useDeclarations);
}
if (true === $this->configuration['import_classes']) {
$newImports['class'] = $this->importClasses($tokens, $useDeclarations);
} elseif (false === $this->configuration['import_classes']) {
$this->fullyQualifyClasses($tokens, $useDeclarations);
}
if (\count($newImports) > 0) {
if (\count($useDeclarations) > 0) {
$useDeclaration = end($useDeclarations);
$atIndex = $useDeclaration->getEndIndex() + 1;
} else {
$namespace = $tokens->getNamespaceDeclarations()[0];
$atIndex = $namespace->getEndIndex() + 1;
}
$this->importProcessor->insertImports($tokens, $newImports, $atIndex);
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('import_constants', 'Whether to import, not import or ignore global constants.'))
->setDefault(null)
->setAllowedTypes(['null', 'bool'])
->getOption(),
(new FixerOptionBuilder('import_functions', 'Whether to import, not import or ignore global functions.'))
->setDefault(null)
->setAllowedTypes(['null', 'bool'])
->getOption(),
(new FixerOptionBuilder('import_classes', 'Whether to import, not import or ignore global classes.'))
->setDefault(true)
->setAllowedTypes(['null', 'bool'])
->getOption(),
]);
}
/**
* @param list<NamespaceUseAnalysis> $useDeclarations
*
* @return array<non-empty-string, non-empty-string>
*/
private function importConstants(Tokens $tokens, array $useDeclarations): array
{
[$global, $other] = $this->filterUseDeclarations($useDeclarations, static fn (NamespaceUseAnalysis $declaration): bool => $declaration->isConstant(), true);
// find namespaced const declarations (`const FOO = 1`)
// and add them to the not importable names (already used)
for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) {
$token = $tokens[$index];
if ($token->isClassy()) {
$index = $tokens->getNextTokenOfKind($index, ['{']);
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
continue;
}
if (!$token->isGivenKind(\T_CONST)) {
continue;
}
$index = $tokens->getNextMeaningfulToken($index);
$other[$tokens[$index]->getContent()] = true;
}
$analyzer = new TokensAnalyzer($tokens);
$indices = [];
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(\T_STRING)) {
continue;
}
$name = $token->getContent();
if (isset($other[$name])) {
continue;
}
if (!$analyzer->isConstantInvocation($index)) {
continue;
}
$nsSeparatorIndex = $tokens->getPrevMeaningfulToken($index);
if (!$tokens[$nsSeparatorIndex]->isGivenKind(\T_NS_SEPARATOR)) {
if (!isset($global[$name])) {
// found an unqualified constant invocation
// add it to the not importable names (already used)
$other[$name] = true;
}
continue;
}
$prevIndex = $tokens->getPrevMeaningfulToken($nsSeparatorIndex);
if ($tokens[$prevIndex]->isGivenKind([CT::T_NAMESPACE_OPERATOR, \T_STRING])) {
continue;
}
$indices[] = $index;
}
return $this->prepareImports($tokens, $indices, $global, $other, true);
}
/**
* @param list<NamespaceUseAnalysis> $useDeclarations
*
* @return array<non-empty-string, non-empty-string>
*/
private function importFunctions(Tokens $tokens, array $useDeclarations): array
{
[$global, $other] = $this->filterUseDeclarations($useDeclarations, static fn (NamespaceUseAnalysis $declaration): bool => $declaration->isFunction(), false);
// find function declarations
// and add them to the not importable names (already used)
foreach ($this->findFunctionDeclarations($tokens, 0, $tokens->count() - 1) as $name) {
$other[strtolower($name)] = true;
}
$analyzer = new FunctionsAnalyzer();
$indices = [];
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(\T_STRING)) {
continue;
}
$name = strtolower($token->getContent());
if (isset($other[$name])) {
continue;
}
if (!$analyzer->isGlobalFunctionCall($tokens, $index)) {
continue;
}
$nsSeparatorIndex = $tokens->getPrevMeaningfulToken($index);
if (!$tokens[$nsSeparatorIndex]->isGivenKind(\T_NS_SEPARATOR)) {
if (!isset($global[$name])) {
$other[$name] = true;
}
continue;
}
$indices[] = $index;
}
return $this->prepareImports($tokens, $indices, $global, $other, false);
}
/**
* @param list<NamespaceUseAnalysis> $useDeclarations
*
* @return array<non-empty-string, non-empty-string>
*/
private function importClasses(Tokens $tokens, array $useDeclarations): array
{
[$global, $other] = $this->filterUseDeclarations($useDeclarations, static fn (NamespaceUseAnalysis $declaration): bool => $declaration->isClass(), false);
/** @var array<int, DocBlock> $docBlocks */
$docBlocks = [];
// find class declarations and class usages in docblocks
// and add them to the not importable names (already used)
for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) {
$token = $tokens[$index];
if ($token->isGivenKind(\T_DOC_COMMENT)) {
$docBlocks[$index] = new DocBlock($token->getContent());
$this->traverseDocBlockTypes($docBlocks[$index], static function (string $type) use ($global, &$other): void {
if (str_contains($type, '\\')) {
return;
}
$name = strtolower($type);
if (!isset($global[$name])) {
$other[$name] = true;
}
});
}
if (!$token->isClassy()) {
continue;
}
$index = $tokens->getNextMeaningfulToken($index);
if ($tokens[$index]->isGivenKind(\T_STRING)) {
$other[strtolower($tokens[$index]->getContent())] = true;
}
}
$analyzer = new ClassyAnalyzer();
$indices = [];
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(\T_STRING)) {
continue;
}
$name = strtolower($token->getContent());
if (isset($other[$name])) {
continue;
}
if (!$analyzer->isClassyInvocation($tokens, $index)) {
continue;
}
$nsSeparatorIndex = $tokens->getPrevMeaningfulToken($index);
if (!$tokens[$nsSeparatorIndex]->isGivenKind(\T_NS_SEPARATOR)) {
if (!isset($global[$name])) {
$other[$name] = true;
}
continue;
}
if ($tokens[$tokens->getPrevMeaningfulToken($nsSeparatorIndex)]->isGivenKind([CT::T_NAMESPACE_OPERATOR, \T_STRING])) {
continue;
}
$indices[] = $index;
}
$imports = [];
foreach ($docBlocks as $index => $docBlock) {
$changed = $this->traverseDocBlockTypes($docBlock, static function (string $type) use ($global, $other, &$imports): string {
if ('\\' !== $type[0]) {
return $type;
}
/** @var non-empty-string $name */
$name = substr($type, 1);
$checkName = strtolower($name);
if (str_contains($checkName, '\\') || isset($other[$checkName])) {
return $type;
}
if (isset($global[$checkName])) {
return \is_string($global[$checkName]) ? $global[$checkName] : $name;
}
$imports[$checkName] = $name;
return $name;
});
if ($changed) {
$tokens[$index] = new Token([\T_DOC_COMMENT, $docBlock->getContent()]);
}
}
return array_merge($imports, $this->prepareImports($tokens, $indices, $global, $other, false));
}
/**
* Removes the leading slash at the given indices (when the name is not already used).
*
* @param list<int> $indices
* @param array<string, string|true> $global
* @param array<string, true> $other
*
* @return array<non-empty-string, non-empty-string> array keys contain the names that must be imported
*/
private function prepareImports(Tokens $tokens, array $indices, array $global, array $other, bool $caseSensitive): array
{
$imports = [];
foreach ($indices as $index) {
/** @var non-empty-string $name */
$name = $tokens[$index]->getContent();
$checkName = $caseSensitive ? $name : strtolower($name);
if (isset($other[$checkName])) {
continue;
}
if (!isset($global[$checkName])) {
$imports[$checkName] = $name;
} elseif (\is_string($global[$checkName])) {
$tokens[$index] = new Token([\T_STRING, $global[$checkName]]);
}
$tokens->clearAt($tokens->getPrevMeaningfulToken($index));
}
return $imports;
}
/**
* @param list<NamespaceUseAnalysis> $useDeclarations
*/
private function fullyQualifyConstants(Tokens $tokens, array $useDeclarations): void
{
if (!$tokens->isTokenKindFound(CT::T_CONST_IMPORT)) {
return;
}
[$global] = $this->filterUseDeclarations($useDeclarations, static fn (NamespaceUseAnalysis $declaration): bool => $declaration->isConstant() && !$declaration->isAliased(), true);
if ([] === $global) {
return;
}
$analyzer = new TokensAnalyzer($tokens);
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(\T_STRING)) {
continue;
}
if (!isset($global[$token->getContent()])) {
continue;
}
if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(\T_NS_SEPARATOR)) {
continue;
}
if (!$analyzer->isConstantInvocation($index)) {
continue;
}
$tokens->insertAt($index, new Token([\T_NS_SEPARATOR, '\\']));
}
}
/**
* @param list<NamespaceUseAnalysis> $useDeclarations
*/
private function fullyQualifyFunctions(Tokens $tokens, array $useDeclarations): void
{
if (!$tokens->isTokenKindFound(CT::T_FUNCTION_IMPORT)) {
return;
}
[$global] = $this->filterUseDeclarations($useDeclarations, static fn (NamespaceUseAnalysis $declaration): bool => $declaration->isFunction() && !$declaration->isAliased(), false);
if ([] === $global) {
return;
}
$analyzer = new FunctionsAnalyzer();
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(\T_STRING)) {
continue;
}
if (!isset($global[strtolower($token->getContent())])) {
continue;
}
if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(\T_NS_SEPARATOR)) {
continue;
}
if (!$analyzer->isGlobalFunctionCall($tokens, $index)) {
continue;
}
$tokens->insertAt($index, new Token([\T_NS_SEPARATOR, '\\']));
}
}
/**
* @param list<NamespaceUseAnalysis> $useDeclarations
*/
private function fullyQualifyClasses(Tokens $tokens, array $useDeclarations): void
{
if (!$tokens->isTokenKindFound(\T_USE)) {
return;
}
[$global] = $this->filterUseDeclarations($useDeclarations, static fn (NamespaceUseAnalysis $declaration): bool => $declaration->isClass() && !$declaration->isAliased(), false);
if ([] === $global) {
return;
}
$analyzer = new ClassyAnalyzer();
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if ($token->isGivenKind(\T_DOC_COMMENT)) {
$doc = new DocBlock($token->getContent());
$changed = $this->traverseDocBlockTypes($doc, static function (string $type) use ($global): string {
if (!isset($global[strtolower($type)])) {
return $type;
}
return '\\'.$type;
});
if ($changed) {
$tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]);
}
continue;
}
if (!$token->isGivenKind(\T_STRING)) {
continue;
}
if (!isset($global[strtolower($token->getContent())])) {
continue;
}
if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(\T_NS_SEPARATOR)) {
continue;
}
if (!$analyzer->isClassyInvocation($tokens, $index)) {
continue;
}
$tokens->insertAt($index, new Token([\T_NS_SEPARATOR, '\\']));
}
}
/**
* @param list<NamespaceUseAnalysis> $declarations
*
* @return array{0: array<string, string|true>, 1: array<string, true>}
*/
private function filterUseDeclarations(array $declarations, callable $callback, bool $caseSensitive): array
{
$global = [];
$other = [];
foreach ($declarations as $declaration) {
if (!$callback($declaration)) {
continue;
}
$fullName = ltrim($declaration->getFullName(), '\\');
if (str_contains($fullName, '\\')) {
$name = $caseSensitive ? $declaration->getShortName() : strtolower($declaration->getShortName());
$other[$name] = true;
continue;
}
$checkName = $caseSensitive ? $fullName : strtolower($fullName);
$alias = $declaration->getShortName();
$global[$checkName] = $alias === $fullName ? true : $alias;
}
return [$global, $other];
}
/**
* @return iterable<string>
*/
private function findFunctionDeclarations(Tokens $tokens, int $start, int $end): iterable
{
for ($index = $start; $index <= $end; ++$index) {
$token = $tokens[$index];
if ($token->isClassy()) {
$classStart = $tokens->getNextTokenOfKind($index, ['{']);
$classEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classStart);
for ($index = $classStart; $index <= $classEnd; ++$index) {
if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) {
continue;
}
$methodStart = $tokens->getNextTokenOfKind($index, ['{', ';']);
if ($tokens[$methodStart]->equals(';')) {
$index = $methodStart;
continue;
}
$methodEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $methodStart);
foreach ($this->findFunctionDeclarations($tokens, $methodStart, $methodEnd) as $function) {
yield $function;
}
$index = $methodEnd;
}
continue;
}
if (!$token->isGivenKind(\T_FUNCTION)) {
continue;
}
$index = $tokens->getNextMeaningfulToken($index);
if ($tokens[$index]->isGivenKind(CT::T_RETURN_REF)) {
$index = $tokens->getNextMeaningfulToken($index);
}
if ($tokens[$index]->isGivenKind(\T_STRING)) {
yield $tokens[$index]->getContent();
}
}
}
private function traverseDocBlockTypes(DocBlock $doc, callable $callback): bool
{
$annotations = $doc->getAnnotationsOfType(Annotation::TAGS_WITH_TYPES);
if (0 === \count($annotations)) {
return false;
}
$changed = false;
foreach ($annotations as $annotation) {
$types = $annotation->getTypes();
$new = array_map(static function (string $fullType) use ($callback): string {
Preg::matchAll('/[\\\\\w]+(?![\\\\\w:])/', $fullType, $matches, \PREG_OFFSET_CAPTURE);
foreach (array_reverse($matches[0]) as [$type, $offset]) {
$newType = $callback($type);
if (null !== $newType && $type !== $newType) {
$fullType = substr_replace($fullType, $newType, $offset, \strlen($type));
}
}
return $fullType;
}, $types);
if ($types !== $new) {
$annotation->setTypes($new);
$changed = true;
}
}
return $changed;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Import/OrderedImportsFixer.php | src/Fixer/Import/OrderedImportsFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Import;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\Console\Application;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Future;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use PhpCsFixer\Utils;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
use Symfony\Component\OptionsResolver\Options;
/**
* @phpstan-type _UseImportInfo array{
* namespace: non-empty-string,
* startIndex: int,
* endIndex: int,
* importType: self::IMPORT_TYPE_*,
* group: bool,
* }
* @phpstan-type _AutogeneratedInputConfiguration array{
* case_sensitive?: bool,
* imports_order?: list<string>|null,
* sort_algorithm?: 'alpha'|'length'|'none',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* case_sensitive: bool,
* imports_order: list<string>|null,
* sort_algorithm: 'alpha'|'length'|'none',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Sebastiaan Stok <s.stok@rollerscapes.net>
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
* @author Darius Matulionis <darius@matulionis.lt>
* @author Adriano Pilger <adriano.pilger@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class OrderedImportsFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @internal
*/
public const IMPORT_TYPE_CLASS = 'class';
/**
* @internal
*/
public const IMPORT_TYPE_CONST = 'const';
/**
* @internal
*/
public const IMPORT_TYPE_FUNCTION = 'function';
/**
* @internal
*/
public const SORT_ALPHA = 'alpha';
/**
* @TODO 4.0 remove the possibility to sort by length
*
* @internal
*/
public const SORT_LENGTH = 'length';
/**
* @internal
*/
public const SORT_NONE = 'none';
/**
* Array of supported sort types in configuration.
*
* @var non-empty-list<string>
*/
private const SUPPORTED_SORT_TYPES = [self::IMPORT_TYPE_CLASS, self::IMPORT_TYPE_CONST, self::IMPORT_TYPE_FUNCTION];
/**
* Array of supported sort algorithms in configuration.
*
* @var non-empty-list<string>
*/
private const SUPPORTED_SORT_ALGORITHMS = [self::SORT_ALPHA, self::SORT_LENGTH, self::SORT_NONE];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Ordering `use` statements.',
[
new CodeSample(
<<<'PHP'
<?php
use function AAC;
use const AAB;
use AAA;
PHP,
),
new CodeSample(
<<<'PHP'
<?php
use function Aaa;
use const AA;
PHP,
['case_sensitive' => true],
),
new CodeSample(
<<<'PHP'
<?php
use Acme\Bar;
use Bar1;
use Acme;
use Bar;
PHP,
['sort_algorithm' => self::SORT_LENGTH],
),
new CodeSample(
<<<'PHP'
<?php
use const AAAA;
use const BBB;
use Bar;
use AAC;
use Acme;
use function CCC\AA;
use function DDD;
PHP,
[
'sort_algorithm' => self::SORT_LENGTH,
'imports_order' => [
self::IMPORT_TYPE_CONST,
self::IMPORT_TYPE_CLASS,
self::IMPORT_TYPE_FUNCTION,
],
],
),
new CodeSample(
<<<'PHP'
<?php
use const BBB;
use const AAAA;
use Acme;
use AAC;
use Bar;
use function DDD;
use function CCC\AA;
PHP,
[
'sort_algorithm' => self::SORT_ALPHA,
'imports_order' => [
self::IMPORT_TYPE_CONST,
self::IMPORT_TYPE_CLASS,
self::IMPORT_TYPE_FUNCTION,
],
],
),
new CodeSample(
<<<'PHP'
<?php
use const BBB;
use const AAAA;
use function DDD;
use function CCC\AA;
use Acme;
use AAC;
use Bar;
PHP,
[
'sort_algorithm' => self::SORT_NONE,
'imports_order' => [
self::IMPORT_TYPE_CONST,
self::IMPORT_TYPE_CLASS,
self::IMPORT_TYPE_FUNCTION,
],
],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before BlankLineBetweenImportGroupsFixer.
* Must run after FullyQualifiedStrictTypesFixer, GlobalNamespaceImportFixer, NoLeadingImportSlashFixer.
*/
public function getPriority(): int
{
return -30;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_USE);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
$namespacesImports = $tokensAnalyzer->getImportUseIndexes(true);
foreach (array_reverse($namespacesImports) as $usesPerNamespaceIndices) {
$count = \count($usesPerNamespaceIndices);
if (0 === $count) {
continue; // nothing to sort
}
if (1 === $count) {
$this->setNewOrder($tokens, $this->getNewOrder($usesPerNamespaceIndices, $tokens));
continue;
}
$groupUsesOffset = 0;
$groupUses = [$groupUsesOffset => [$usesPerNamespaceIndices[0]]];
// if there's some logic between two `use` statements, sort only imports grouped before that logic
for ($index = 0; $index < $count - 1; ++$index) {
$nextGroupUse = $tokens->getNextTokenOfKind($usesPerNamespaceIndices[$index], [';', [\T_CLOSE_TAG]]);
if ($tokens[$nextGroupUse]->isGivenKind(\T_CLOSE_TAG)) {
$nextGroupUse = $tokens->getNextTokenOfKind($usesPerNamespaceIndices[$index], [[\T_OPEN_TAG]]);
}
$nextGroupUse = $tokens->getNextMeaningfulToken($nextGroupUse);
if ($nextGroupUse !== $usesPerNamespaceIndices[$index + 1]) {
$groupUses[++$groupUsesOffset] = [];
}
$groupUses[$groupUsesOffset][] = $usesPerNamespaceIndices[$index + 1];
}
for ($index = $groupUsesOffset; $index >= 0; --$index) {
$this->setNewOrder($tokens, $this->getNewOrder($groupUses[$index], $tokens));
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
$supportedSortTypes = self::SUPPORTED_SORT_TYPES;
$fixerName = $this->getName();
return new FixerConfigurationResolver([
(new FixerOptionBuilder('sort_algorithm', 'Whether the statements should be sorted alphabetically or by length (*deprecated*), or not sorted.')) // @TODO 4.0 drop 'length'
->setAllowedValues(self::SUPPORTED_SORT_ALGORITHMS)
->setDefault(self::SORT_ALPHA)
->setNormalizer(static function (Options $options, ?string $value) use ($fixerName): ?string {
if (self::SORT_LENGTH === $value) {
Future::triggerDeprecation(new InvalidFixerConfigurationException($fixerName, \sprintf(
'Option "sort_algorithm:%s" is deprecated and will be removed in version %d.0.',
self::SORT_LENGTH,
Application::getMajorVersion() + 1,
)));
}
return $value;
})
->getOption(),
(new FixerOptionBuilder('imports_order', 'Defines the order of import types.'))
->setAllowedTypes(['string[]', 'null'])
->setAllowedValues([static function (?array $value) use ($supportedSortTypes): bool {
if (null !== $value) {
$missing = array_diff($supportedSortTypes, $value);
if (\count($missing) > 0) {
throw new InvalidOptionsException(\sprintf(
'Missing sort %s %s.',
1 === \count($missing) ? 'type' : 'types',
Utils::naturalLanguageJoin(array_values($missing)),
));
}
$unknown = array_diff($value, $supportedSortTypes);
if (\count($unknown) > 0) {
throw new InvalidOptionsException(\sprintf(
'Unknown sort %s %s.',
1 === \count($unknown) ? 'type' : 'types',
Utils::naturalLanguageJoin(array_values($unknown)),
));
}
}
return true;
}])
->setDefault(
Future::getV4OrV3(['class', 'function', 'const'], null),
)
->getOption(),
(new FixerOptionBuilder('case_sensitive', 'Whether the sorting should be case sensitive.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
/**
* This method is used for sorting the uses in a namespace.
*
* @param _UseImportInfo $first
* @param _UseImportInfo $second
*/
private function sortAlphabetically(array $first, array $second): int
{
// Replace backslashes by spaces and remove opening braces before sorting for correct sort order
$firstNamespace = str_replace(['\\', '{'], [' ', ''], $this->prepareNamespace($first['namespace']));
$secondNamespace = str_replace(['\\', '{'], [' ', ''], $this->prepareNamespace($second['namespace']));
return true === $this->configuration['case_sensitive']
? $firstNamespace <=> $secondNamespace
: strcasecmp($firstNamespace, $secondNamespace);
}
/**
* This method is used for sorting the uses statements in a namespace by length.
*
* @param _UseImportInfo $first
* @param _UseImportInfo $second
*/
private function sortByLength(array $first, array $second): int
{
$firstNamespace = (self::IMPORT_TYPE_CLASS === $first['importType'] ? '' : $first['importType'].' ').$this->prepareNamespace($first['namespace']);
$secondNamespace = (self::IMPORT_TYPE_CLASS === $second['importType'] ? '' : $second['importType'].' ').$this->prepareNamespace($second['namespace']);
$firstNamespaceLength = \strlen($firstNamespace);
$secondNamespaceLength = \strlen($secondNamespace);
if ($firstNamespaceLength === $secondNamespaceLength) {
$sortResult = true === $this->configuration['case_sensitive']
? $firstNamespace <=> $secondNamespace
: strcasecmp($firstNamespace, $secondNamespace);
} else {
$sortResult = $firstNamespaceLength > $secondNamespaceLength ? 1 : -1;
}
return $sortResult;
}
private function prepareNamespace(string $namespace): string
{
return trim(Preg::replace('%/\*(.*)\*/%s', '', $namespace));
}
/**
* @param list<int> $uses
*
* @return array<int, _UseImportInfo>
*/
private function getNewOrder(array $uses, Tokens $tokens): array
{
$indices = [];
$originalIndices = [];
$lineEnding = $this->whitespacesConfig->getLineEnding();
$usesCount = \count($uses);
for ($i = 0; $i < $usesCount; ++$i) {
$index = $uses[$i];
$startIndex = $tokens->getTokenNotOfKindsSibling($index + 1, 1, [\T_WHITESPACE]);
$endIndex = $tokens->getNextTokenOfKind($startIndex, [';', [\T_CLOSE_TAG]]);
$previous = $tokens->getPrevMeaningfulToken($endIndex);
$group = $tokens[$previous]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE);
if ($tokens[$startIndex]->isGivenKind(CT::T_CONST_IMPORT)) {
$type = self::IMPORT_TYPE_CONST;
$index = $tokens->getNextNonWhitespace($startIndex);
} elseif ($tokens[$startIndex]->isGivenKind(CT::T_FUNCTION_IMPORT)) {
$type = self::IMPORT_TYPE_FUNCTION;
$index = $tokens->getNextNonWhitespace($startIndex);
} else {
$type = self::IMPORT_TYPE_CLASS;
$index = $startIndex;
}
$namespaceTokens = [];
while ($index <= $endIndex) {
$token = $tokens[$index];
if ($index === $endIndex || (!$group && $token->equals(','))) {
if ($group && self::SORT_NONE !== $this->configuration['sort_algorithm']) {
// if group import, sort the items within the group definition
// figure out where the list of namespace parts within the group def. starts
$namespaceTokensCount = \count($namespaceTokens) - 1;
$namespace = '';
for ($k = 0; $k < $namespaceTokensCount; ++$k) {
if ($namespaceTokens[$k]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) {
$namespace .= '{';
break;
}
$namespace .= $namespaceTokens[$k]->getContent();
}
// fetch all parts, split up in an array of strings, move comments to the end
$parts = [];
$firstIndent = '';
$separator = ', ';
$lastIndent = '';
$hasGroupTrailingComma = false;
for ($k1 = $k + 1; $k1 < $namespaceTokensCount; ++$k1) {
$comment = '';
$namespacePart = '';
for ($k2 = $k1;; ++$k2) {
if ($namespaceTokens[$k2]->equalsAny([',', [CT::T_GROUP_IMPORT_BRACE_CLOSE]])) {
break;
}
if ($namespaceTokens[$k2]->isComment()) {
$comment .= $namespaceTokens[$k2]->getContent();
continue;
}
// if there is any line ending inside the group import, it should be indented properly
if (
'' === $firstIndent
&& $namespaceTokens[$k2]->isWhitespace()
&& str_contains($namespaceTokens[$k2]->getContent(), $lineEnding)
) {
$lastIndent = $lineEnding;
$firstIndent = $lineEnding.$this->whitespacesConfig->getIndent();
$separator = ','.$firstIndent;
}
$namespacePart .= $namespaceTokens[$k2]->getContent();
}
$namespacePart = trim($namespacePart);
if ('' === $namespacePart) {
$hasGroupTrailingComma = true;
continue;
}
$comment = trim($comment);
if ('' !== $comment) {
$namespacePart .= ' '.$comment;
}
$parts[] = $namespacePart;
$k1 = $k2;
}
$sortedParts = $parts;
sort($parts);
// check if the order needs to be updated, otherwise don't touch as we might change valid CS (to other valid CS).
if ($sortedParts === $parts) {
$namespace = Tokens::fromArray($namespaceTokens)->generateCode();
} else {
$namespace .= $firstIndent.implode($separator, $parts).($hasGroupTrailingComma ? ',' : '').$lastIndent.'}';
}
} else {
$namespace = Tokens::fromArray($namespaceTokens)->generateCode();
}
$indices[$startIndex] = [
'namespace' => $namespace,
'startIndex' => $startIndex,
'endIndex' => $index - 1,
'importType' => $type,
'group' => $group,
];
$originalIndices[] = $startIndex;
if ($index === $endIndex) {
break;
}
$namespaceTokens = [];
$nextPartIndex = $tokens->getTokenNotOfKindSibling($index, 1, [',', [\T_WHITESPACE]]);
$startIndex = $nextPartIndex;
$index = $nextPartIndex;
continue;
}
$namespaceTokens[] = $token;
++$index;
}
}
// Is sort types provided, sorting by groups and each group by algorithm
if (null !== $this->configuration['imports_order']) {
// Grouping indices by import type.
$groupedByTypes = [];
foreach ($indices as $startIndex => $item) {
$groupedByTypes[$item['importType']][$startIndex] = $item;
}
// Sorting each group by algorithm.
foreach ($groupedByTypes as $type => $groupIndices) {
$groupedByTypes[$type] = $this->sortByAlgorithm($groupIndices);
}
// Ordering groups
$sortedGroups = [];
foreach ($this->configuration['imports_order'] as $type) {
if (isset($groupedByTypes[$type]) && [] !== $groupedByTypes[$type]) {
foreach ($groupedByTypes[$type] as $startIndex => $item) {
$sortedGroups[$startIndex] = $item;
}
}
}
$indices = $sortedGroups;
} else {
// Sorting only by algorithm
$indices = $this->sortByAlgorithm($indices);
}
$index = -1;
$usesOrder = [];
// Loop through the index but use original index order
foreach ($indices as $v) {
$usesOrder[$originalIndices[++$index]] = $v;
}
return $usesOrder;
}
/**
* @param array<int, _UseImportInfo> $indices
*
* @return array<int, _UseImportInfo>
*/
private function sortByAlgorithm(array $indices): array
{
if (self::SORT_ALPHA === $this->configuration['sort_algorithm']) {
uasort($indices, [$this, 'sortAlphabetically']);
} elseif (self::SORT_LENGTH === $this->configuration['sort_algorithm']) {
uasort($indices, [$this, 'sortByLength']);
}
return $indices;
}
/**
* @param array<int, _UseImportInfo> $usesOrder
*/
private function setNewOrder(Tokens $tokens, array $usesOrder): void
{
$mapStartToEnd = [];
foreach ($usesOrder as $use) {
$mapStartToEnd[$use['startIndex']] = $use['endIndex'];
}
// Now insert the new tokens, starting from the end
foreach (array_reverse($usesOrder, true) as $index => $use) {
$code = \sprintf(
'<?php use %s%s;',
self::IMPORT_TYPE_CLASS === $use['importType'] ? '' : ' '.$use['importType'].' ',
$use['namespace'],
);
$numberOfInitialTokensToClear = 3; // clear `<?php use `
if (self::IMPORT_TYPE_CLASS !== $use['importType']) {
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevIndex]->equals(',')) {
$numberOfInitialTokensToClear = 5; // clear `<?php use const ` or `<?php use function `
}
}
$declarationTokens = Tokens::fromCode($code);
$declarationTokens->clearRange(0, $numberOfInitialTokensToClear - 1);
$declarationTokens->clearAt(\count($declarationTokens) - 1); // clear `;`
$declarationTokens->clearEmptyTokens();
$tokens->overrideRange($index, $mapStartToEnd[$index], $declarationTokens);
if ($use['group']) {
// a group import must start with `use` and cannot be part of comma separated import list
self::fixCommaToUse($tokens, $tokens->getPrevMeaningfulToken($index));
$closeGroupIndex = $tokens->getNextTokenOfKind($index, [[CT::T_GROUP_IMPORT_BRACE_CLOSE]]);
self::fixCommaToUse($tokens, $tokens->getNextMeaningfulToken($closeGroupIndex));
}
}
}
private static function fixCommaToUse(Tokens $tokens, int $index): void
{
if (!$tokens[$index]->equals(',')) {
return;
}
$tokens[$index] = new Token(';');
$tokens->insertAt($index + 1, new Token([\T_USE, 'use']));
if (!$tokens[$index + 2]->isWhitespace()) {
$tokens->insertAt($index + 2, new Token([\T_WHITESPACE, ' ']));
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Import/SingleImportPerStatementFixer.php | src/Fixer/Import/SingleImportPerStatementFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Import;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* Fixer for rules defined in PSR2 ¶3.
*
* @phpstan-type _AutogeneratedInputConfiguration array{
* group_to_single_imports?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* group_to_single_imports: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class SingleImportPerStatementFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There MUST be one use keyword per declaration.',
[
new CodeSample(
<<<'PHP'
<?php
use Foo, Sample, Sample\Sample as Sample2;
PHP,
),
new CodeSample(
<<<'PHP'
<?php
use Space\Models\ {
TestModelA,
TestModelB,
TestModel,
};
PHP,
['group_to_single_imports' => true],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before MultilineWhitespaceBeforeSemicolonsFixer, NoLeadingImportSlashFixer, NoSinglelineWhitespaceBeforeSemicolonsFixer, SpaceAfterSemicolonFixer.
*/
public function getPriority(): int
{
return 1;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_USE);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
foreach (array_reverse($tokensAnalyzer->getImportUseIndexes()) as $index) {
$endIndex = $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]);
$groupClose = $tokens->getPrevMeaningfulToken($endIndex);
if ($tokens[$groupClose]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)) {
if (true === $this->configuration['group_to_single_imports']) {
$this->fixGroupUse($tokens, $index, $endIndex);
}
} else {
$this->fixMultipleUse($tokens, $index, $endIndex);
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('group_to_single_imports', 'Whether to change group imports into single imports.'))
->setAllowedTypes(['bool'])
->setDefault(true)
->getOption(),
]);
}
/**
* @return array{string, ?int, int, string}
*/
private function getGroupDeclaration(Tokens $tokens, int $index): array
{
$groupPrefix = '';
$comment = '';
$groupOpenIndex = null;
for ($i = $index + 1;; ++$i) {
if ($tokens[$i]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) {
$groupOpenIndex = $i;
break;
}
if ($tokens[$i]->isComment()) {
$comment .= $tokens[$i]->getContent();
if (!$tokens[$i - 1]->isWhitespace() && !$tokens[$i + 1]->isWhitespace()) {
$groupPrefix .= ' ';
}
continue;
}
if ($tokens[$i]->isWhitespace()) {
$groupPrefix .= ' ';
continue;
}
$groupPrefix .= $tokens[$i]->getContent();
}
return [
rtrim($groupPrefix),
$groupOpenIndex,
$tokens->findBlockEnd(Tokens::BLOCK_TYPE_GROUP_IMPORT_BRACE, $groupOpenIndex),
$comment,
];
}
/**
* @return list<string>
*/
private function getGroupStatements(Tokens $tokens, string $groupPrefix, int $groupOpenIndex, int $groupCloseIndex, string $comment): array
{
$statements = [];
$statement = $groupPrefix;
for ($i = $groupOpenIndex + 1; $i <= $groupCloseIndex; ++$i) {
$token = $tokens[$i];
if ($token->equals(',') && $tokens[$tokens->getNextMeaningfulToken($i)]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)) {
continue;
}
if ($token->equalsAny([',', [CT::T_GROUP_IMPORT_BRACE_CLOSE]])) {
$statements[] = 'use'.$statement.';';
$statement = $groupPrefix;
continue;
}
if ($token->isWhitespace()) {
$j = $tokens->getNextMeaningfulToken($i);
if ($tokens[$j]->isGivenKind(\T_AS)) {
$statement .= ' as ';
$i += 2;
} elseif ($tokens[$j]->isGivenKind(CT::T_FUNCTION_IMPORT)) {
$statement = ' function'.$statement;
$i += 2;
} elseif ($tokens[$j]->isGivenKind(CT::T_CONST_IMPORT)) {
$statement = ' const'.$statement;
$i += 2;
}
if ($token->isWhitespace(" \t") || !str_starts_with($tokens[$i - 1]->getContent(), '//')) {
continue;
}
}
$statement .= $token->getContent();
}
if ('' !== $comment) {
$statements[0] .= ' '.$comment;
}
return $statements;
}
private function fixGroupUse(Tokens $tokens, int $index, int $endIndex): void
{
[$groupPrefix, $groupOpenIndex, $groupCloseIndex, $comment] = $this->getGroupDeclaration($tokens, $index);
$statements = $this->getGroupStatements($tokens, $groupPrefix, $groupOpenIndex, $groupCloseIndex, $comment);
$tokens->clearRange($index, $groupCloseIndex);
if ($tokens[$endIndex]->equals(';')) {
$tokens->clearAt($endIndex);
}
$ending = $this->whitespacesConfig->getLineEnding();
$importTokens = Tokens::fromCode('<?php '.implode($ending, $statements));
$importTokens->clearAt(0);
$importTokens->clearEmptyTokens();
$tokens->insertAt($index, $importTokens);
}
private function fixMultipleUse(Tokens $tokens, int $index, int $endIndex): void
{
$nextTokenIndex = $tokens->getNextMeaningfulToken($index);
if ($tokens[$nextTokenIndex]->isGivenKind(CT::T_FUNCTION_IMPORT)) {
$leadingTokens = [
new Token([CT::T_FUNCTION_IMPORT, 'function']),
new Token([\T_WHITESPACE, ' ']),
];
} elseif ($tokens[$nextTokenIndex]->isGivenKind(CT::T_CONST_IMPORT)) {
$leadingTokens = [
new Token([CT::T_CONST_IMPORT, 'const']),
new Token([\T_WHITESPACE, ' ']),
];
} else {
$leadingTokens = [];
}
$ending = $this->whitespacesConfig->getLineEnding();
for ($i = $endIndex - 1; $i > $index; --$i) {
if (!$tokens[$i]->equals(',')) {
continue;
}
$tokens[$i] = new Token(';');
$i = $tokens->getNextMeaningfulToken($i);
$tokens->insertAt($i, new Token([\T_USE, 'use']));
$tokens->insertAt($i + 1, new Token([\T_WHITESPACE, ' ']));
foreach ($leadingTokens as $offset => $leadingToken) {
$tokens->insertAt($i + 2 + $offset, clone $leadingToken);
}
$indent = WhitespacesAnalyzer::detectIndent($tokens, $index);
if ($tokens[$i - 1]->isWhitespace()) {
$tokens[$i - 1] = new Token([\T_WHITESPACE, $ending.$indent]);
} elseif (!str_contains($tokens[$i - 1]->getContent(), "\n")) {
$tokens->insertAt($i, new Token([\T_WHITESPACE, $ending.$indent]));
}
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/PhpTag/BlankLineAfterOpeningTagFixer.php | src/Fixer/PhpTag/BlankLineAfterOpeningTagFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\PhpTag;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Ceeram <ceeram@cakephp.org>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class BlankLineAfterOpeningTagFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Ensure there is no code on the same line as the PHP open tag and it is followed by a blank line.',
[new CodeSample("<?php \$a = 1;\n\$b = 1;\n")],
);
}
/**
* {@inheritdoc}
*
* Must run before BlankLinesBeforeNamespaceFixer, NoBlankLinesBeforeNamespaceFixer.
* Must run after DeclareStrictTypesFixer.
*/
public function getPriority(): int
{
return 1;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isMonolithicPhp() && !$tokens->isTokenKindFound(\T_OPEN_TAG_WITH_ECHO);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$lineEnding = $this->whitespacesConfig->getLineEnding();
$newlineFound = false;
foreach ($tokens as $token) {
if (($token->isWhitespace() || $token->isGivenKind(\T_OPEN_TAG)) && str_contains($token->getContent(), "\n")) {
$newlineFound = true;
break;
}
}
// ignore one-line files
if (!$newlineFound) {
return;
}
$openTagIndex = $tokens[0]->isGivenKind(\T_INLINE_HTML) ? 1 : 0;
$token = $tokens[$openTagIndex];
if (!str_contains($token->getContent(), "\n")) {
$tokens[$openTagIndex] = new Token([$token->getId(), rtrim($token->getContent()).$lineEnding]);
}
$newLineIndex = $openTagIndex + 1;
if (!$tokens->offsetExists($newLineIndex)) {
return;
}
if ($tokens[$newLineIndex]->isWhitespace()) {
if (!str_contains($tokens[$newLineIndex]->getContent(), "\n")) {
$tokens[$newLineIndex] = new Token([\T_WHITESPACE, $lineEnding.$tokens[$newLineIndex]->getContent()]);
}
} else {
$tokens->insertAt($newLineIndex, new Token([\T_WHITESPACE, $lineEnding]));
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/PhpTag/FullOpeningTagFixer.php | src/Fixer/PhpTag/FullOpeningTagFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\PhpTag;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* Fixer for rules defined in PSR1 ¶2.1.
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class FullOpeningTagFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'PHP code must use the long `<?php` tags or short-echo `<?=` tags and not other tag variations.',
[
new CodeSample(
<<<'PHP'
<?
echo "Hello!";
PHP,
),
new CodeSample(
<<<'PHP'
<?PHP
echo "Hello!";
PHP,
),
],
);
}
public function getPriority(): int
{
// must run before all Token-based fixers
return 98;
}
public function isCandidate(Tokens $tokens): bool
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$content = $tokens->generateCode();
// replace all <? with <?php to replace all short open tags even without short_open_tag option enabled
$newContent = Preg::replace('/<\?(?:phP|pHp|pHP|Php|PhP|PHp|PHP)?(\s|$)/', '<?php$1', $content, -1, $count);
if (0 === $count) {
return;
}
/* the following code is magic to revert previous replacements which should NOT be replaced, for example incorrectly replacing
* > echo '<? ';
* with
* > echo '<?php ';
*/
$newTokens = Tokens::fromCode($newContent);
$tokensOldContentLength = 0;
foreach ($newTokens as $index => $token) {
if ($token->isGivenKind(\T_OPEN_TAG)) {
$tokenContent = $token->getContent();
$possibleOpenContent = substr($content, $tokensOldContentLength, 5);
if (false === $possibleOpenContent || '<?php' !== strtolower($possibleOpenContent)) { /** @phpstan-ignore-line as pre PHP 8.0 `false` might be returned by substr @TODO clean up when PHP8+ is required */
$tokenContent = '<? ';
}
$tokensOldContentLength += \strlen($tokenContent);
continue;
}
if ($token->isGivenKind([\T_COMMENT, \T_DOC_COMMENT, \T_CONSTANT_ENCAPSED_STRING, \T_ENCAPSED_AND_WHITESPACE, \T_STRING])) {
$tokenContent = '';
$tokenContentLength = 0;
$parts = explode('<?php', $token->getContent());
$iLast = \count($parts) - 1;
foreach ($parts as $i => $part) {
$tokenContent .= $part;
$tokenContentLength += \strlen($part);
if ($i !== $iLast) {
$originalTokenContent = substr($content, $tokensOldContentLength + $tokenContentLength, 5);
if ('<?php' === strtolower($originalTokenContent)) {
$tokenContent .= $originalTokenContent;
$tokenContentLength += 5;
} else {
$tokenContent .= '<?';
$tokenContentLength += 2;
}
}
}
$newTokens[$index] = new Token([$token->getId(), $tokenContent]);
$token = $newTokens[$index];
}
$tokensOldContentLength += \strlen($token->getContent());
}
$tokens->overrideRange(0, $tokens->count() - 1, $newTokens);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/PhpTag/EchoTagSyntaxFixer.php | src/Fixer/PhpTag/EchoTagSyntaxFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\PhpTag;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* format?: 'long'|'short',
* long_function?: 'echo'|'print',
* shorten_simple_statements_only?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* format: 'long'|'short',
* long_function: 'echo'|'print',
* shorten_simple_statements_only: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Michele Locati <michele@locati.it>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class EchoTagSyntaxFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/** @internal */
public const OPTION_FORMAT = 'format';
/** @internal */
public const OPTION_SHORTEN_SIMPLE_STATEMENTS_ONLY = 'shorten_simple_statements_only';
/** @internal */
public const OPTION_LONG_FUNCTION = 'long_function';
/** @internal */
public const FORMAT_SHORT = 'short';
/** @internal */
public const FORMAT_LONG = 'long';
/** @internal */
public const LONG_FUNCTION_ECHO = 'echo';
/** @internal */
public const LONG_FUNCTION_PRINT = 'print';
private const SUPPORTED_FORMAT_OPTIONS = [
self::FORMAT_LONG,
self::FORMAT_SHORT,
];
private const SUPPORTED_LONGFUNCTION_OPTIONS = [
self::LONG_FUNCTION_ECHO,
self::LONG_FUNCTION_PRINT,
];
public function getDefinition(): FixerDefinitionInterface
{
$sample = <<<'EOT'
<?=1?>
<?php print '2' . '3'; ?>
<?php /* comment */ echo '2' . '3'; ?>
<?php print '2' . '3'; someFunction(); ?>
EOT;
return new FixerDefinition(
'Replaces short-echo `<?=` with long format `<?php echo`/`<?php print` syntax, or vice-versa.',
[
new CodeSample($sample),
new CodeSample($sample, [self::OPTION_FORMAT => self::FORMAT_LONG]),
new CodeSample($sample, [self::OPTION_FORMAT => self::FORMAT_LONG, self::OPTION_LONG_FUNCTION => self::LONG_FUNCTION_PRINT]),
new CodeSample($sample, [self::OPTION_FORMAT => self::FORMAT_SHORT]),
new CodeSample($sample, [self::OPTION_FORMAT => self::FORMAT_SHORT, self::OPTION_SHORTEN_SIMPLE_STATEMENTS_ONLY => false]),
],
null,
);
}
/**
* {@inheritdoc}
*
* Must run before NoMixedEchoPrintFixer.
* Must run after NoUselessPrintfFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
if (self::FORMAT_SHORT === $this->configuration[self::OPTION_FORMAT]) {
return $tokens->isAnyTokenKindsFound([\T_ECHO, \T_PRINT]);
}
return $tokens->isTokenKindFound(\T_OPEN_TAG_WITH_ECHO);
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder(self::OPTION_FORMAT, 'The desired language construct.'))
->setAllowedValues(self::SUPPORTED_FORMAT_OPTIONS)
->setDefault(self::FORMAT_LONG)
->getOption(),
(new FixerOptionBuilder(self::OPTION_LONG_FUNCTION, 'The function to be used to expand the short echo tags.'))
->setAllowedValues(self::SUPPORTED_LONGFUNCTION_OPTIONS)
->setDefault(self::LONG_FUNCTION_ECHO)
->getOption(),
(new FixerOptionBuilder(self::OPTION_SHORTEN_SIMPLE_STATEMENTS_ONLY, 'Render short-echo tags only in case of simple code.'))
->setAllowedTypes(['bool'])
->setDefault(true)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
if (self::FORMAT_SHORT === $this->configuration[self::OPTION_FORMAT]) {
$this->longToShort($tokens);
} else {
$this->shortToLong($tokens);
}
}
private function longToShort(Tokens $tokens): void
{
$count = $tokens->count();
for ($index = 0; $index < $count; ++$index) {
if (!$tokens[$index]->isGivenKind(\T_OPEN_TAG)) {
continue;
}
$nextMeaningful = $tokens->getNextMeaningfulToken($index);
if (null === $nextMeaningful) {
return;
}
if (!$tokens[$nextMeaningful]->isGivenKind([\T_ECHO, \T_PRINT])) {
$index = $nextMeaningful;
continue;
}
if (true === $this->configuration[self::OPTION_SHORTEN_SIMPLE_STATEMENTS_ONLY] && $this->isComplexCode($tokens, $nextMeaningful + 1)) {
$index = $nextMeaningful;
continue;
}
$newTokens = $this->buildLongToShortTokens($tokens, $index, $nextMeaningful);
$tokens->overrideRange($index, $nextMeaningful, $newTokens);
$count = $tokens->count();
}
}
private function shortToLong(Tokens $tokens): void
{
if (self::LONG_FUNCTION_PRINT === $this->configuration[self::OPTION_LONG_FUNCTION]) {
$echoToken = [\T_PRINT, 'print'];
} else {
$echoToken = [\T_ECHO, 'echo'];
}
$index = -1;
while (true) {
$index = $tokens->getNextTokenOfKind($index, [[\T_OPEN_TAG_WITH_ECHO]]);
if (null === $index) {
return;
}
$replace = [new Token([\T_OPEN_TAG, '<?php ']), new Token($echoToken)];
if (!$tokens[$index + 1]->isWhitespace()) {
$replace[] = new Token([\T_WHITESPACE, ' ']);
}
$tokens->overrideRange($index, $index, $replace);
++$index;
}
}
/**
* Check if $tokens, starting at $index, contains "complex code", that is, the content
* of the echo tag contains more than a simple "echo something".
*
* This is done by a very quick test: if the tag contains non-whitespace tokens after
* a semicolon, we consider it as "complex".
*
* @example `<?php echo 1 ?>` is false (not complex)
* @example `<?php echo 'hello' . 'world'; ?>` is false (not "complex")
* @example `<?php echo 2; $set = 3 ?>` is true ("complex")
*/
private function isComplexCode(Tokens $tokens, int $index): bool
{
$semicolonFound = false;
for ($count = $tokens->count(); $index < $count; ++$index) {
$token = $tokens[$index];
if ($token->isGivenKind(\T_CLOSE_TAG)) {
return false;
}
if (';' === $token->getContent()) {
$semicolonFound = true;
} elseif ($semicolonFound && !$token->isWhitespace()) {
return true;
}
}
return false;
}
/**
* Builds the list of tokens that replace a long echo sequence.
*
* @return non-empty-list<Token>
*/
private function buildLongToShortTokens(Tokens $tokens, int $openTagIndex, int $echoTagIndex): array
{
$result = [new Token([\T_OPEN_TAG_WITH_ECHO, '<?='])];
$start = $tokens->getNextNonWhitespace($openTagIndex);
if ($start === $echoTagIndex) {
// No non-whitespace tokens between $openTagIndex and $echoTagIndex
return $result;
}
// Find the last non-whitespace index before $echoTagIndex
$end = $echoTagIndex - 1;
while ($tokens[$end]->isWhitespace()) {
--$end;
}
// Copy the non-whitespace tokens between $openTagIndex and $echoTagIndex
for ($index = $start; $index <= $end; ++$index) {
$result[] = clone $tokens[$index];
}
return $result;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/PhpTag/NoClosingTagFixer.php | src/Fixer/PhpTag/NoClosingTagFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\PhpTag;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* Fixer for rules defined in PSR2 ¶2.2.
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoClosingTagFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'The closing `?>` tag MUST be omitted from files containing only PHP.',
[new CodeSample("<?php\nclass Sample\n{\n}\n?>\n")],
);
}
public function isCandidate(Tokens $tokens): bool
{
return \count($tokens) >= 2 && $tokens->isMonolithicPhp() && $tokens->isTokenKindFound(\T_CLOSE_TAG);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$closeTags = $tokens->findGivenKind(\T_CLOSE_TAG);
$index = array_key_first($closeTags);
if (isset($tokens[$index - 1]) && $tokens[$index - 1]->isWhitespace()) {
$tokens->clearAt($index - 1);
}
$tokens->clearAt($index);
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if (!$tokens[$prevIndex]->equalsAny([';', '}', [\T_OPEN_TAG]])) {
$tokens->insertAt($prevIndex + 1, new Token(';'));
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/PhpTag/LinebreakAfterOpeningTagFixer.php | src/Fixer/PhpTag/LinebreakAfterOpeningTagFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\PhpTag;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Ceeram <ceeram@cakephp.org>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class LinebreakAfterOpeningTagFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Ensure there is no code on the same line as the PHP open tag.',
[new CodeSample("<?php \$a = 1;\n\$b = 3;\n")],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isMonolithicPhp() && !$tokens->isTokenKindFound(\T_OPEN_TAG_WITH_ECHO);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$openTagIndex = $tokens[0]->isGivenKind(\T_INLINE_HTML) ? 1 : 0;
// ignore if linebreak already present
if (str_contains($tokens[$openTagIndex]->getContent(), "\n")) {
return;
}
$newlineFound = false;
foreach ($tokens as $token) {
if (($token->isWhitespace() || $token->isGivenKind(\T_OPEN_TAG)) && str_contains($token->getContent(), "\n")) {
$newlineFound = true;
break;
}
}
// ignore one-line files
if (!$newlineFound) {
return;
}
$tokens[$openTagIndex] = new Token([\T_OPEN_TAG, rtrim($tokens[$openTagIndex]->getContent()).$this->whitespacesConfig->getLineEnding()]);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixer.php | src/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Semicolon;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* strategy?: 'new_line_for_chained_calls'|'no_multi_line',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* strategy: 'new_line_for_chained_calls'|'no_multi_line',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Graham Campbell <hello@gjcampbell.co.uk>
* @author Egidijus Girčys <e.gircys@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class MultilineWhitespaceBeforeSemicolonsFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @internal
*/
public const STRATEGY_NO_MULTI_LINE = 'no_multi_line';
/**
* @internal
*/
public const STRATEGY_NEW_LINE_FOR_CHAINED_CALLS = 'new_line_for_chained_calls';
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Forbid multi-line whitespace before the closing semicolon or move the semicolon to the new line for chained calls.',
[
new CodeSample(
<<<'PHP'
<?php
function foo() {
return 1 + 2
;
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
$object->method1()
->method2()
->method(3);
PHP,
['strategy' => self::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before SpaceAfterSemicolonFixer.
* Must run after CombineConsecutiveIssetsFixer, GetClassToClassKeywordFixer, NoEmptyStatementFixer, SimplifiedIfReturnFixer, SingleImportPerStatementFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(';');
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder(
'strategy',
'Forbid multi-line whitespace or move the semicolon to the new line for chained calls.',
))
->setAllowedValues([self::STRATEGY_NO_MULTI_LINE, self::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS])
->setDefault(self::STRATEGY_NO_MULTI_LINE)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$lineEnding = $this->whitespacesConfig->getLineEnding();
for ($index = 0, $count = \count($tokens); $index < $count; ++$index) {
if ($tokens[$index]->isGivenKind(\T_CONST)) {
$index = $tokens->getNextTokenOfKind($index, [';']);
continue;
}
if (!$tokens[$index]->equals(';')) {
continue;
}
$previousIndex = $index - 1;
$previous = $tokens[$previousIndex];
$indent = $this->findWhitespaceBeforeFirstCall($index, $tokens);
if (self::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS === $this->configuration['strategy'] && null !== $indent) {
if ($previous->isWhitespace() && $previous->getContent() === $lineEnding.$indent) {
continue;
}
// unset whitespace and semicolon
if ($previous->isWhitespace()) {
$tokens->clearAt($previousIndex);
}
$tokens->clearAt($index);
// find the line ending token index after the semicolon
$index = $this->getNewLineIndex($index, $tokens);
// appended new line to the last method call
$newline = new Token([\T_WHITESPACE, $lineEnding.$indent]);
// insert the new line with indented semicolon
$tokens->insertAt($index++, [$newline, new Token(';')]);
} else {
if (!$previous->isWhitespace() || !str_contains($previous->getContent(), "\n")) {
continue;
}
$content = $previous->getContent();
if (str_starts_with($content, $lineEnding) && $tokens[$index - 2]->isComment()) {
// if there is comment between closing parenthesis and semicolon
// unset whitespace and semicolon
$tokens->clearAt($previousIndex);
$tokens->clearAt($index);
// find the significant token index before the semicolon
$significantTokenIndex = $this->getPreviousSignificantTokenIndex($index, $tokens);
// insert the semicolon
$tokens->insertAt($significantTokenIndex + 1, [new Token(';')]);
} else {
// if there is whitespace between closing bracket and semicolon, just remove it
$tokens->clearAt($previousIndex);
}
}
}
}
/**
* Find the index for the next new line. Return the given index when there's no new line.
*/
private function getNewLineIndex(int $index, Tokens $tokens): int
{
$lineEnding = $this->whitespacesConfig->getLineEnding();
for ($index, $count = \count($tokens); $index < $count; ++$index) {
if (!$tokens[$index]->isWhitespace() && !$tokens[$index]->isComment()) {
break;
}
if (false !== strstr($tokens[$index]->getContent(), $lineEnding)) {
return $index;
}
}
return $index;
}
/**
* Find the index for the previous significant token. Return the given index when there's no significant token.
*/
private function getPreviousSignificantTokenIndex(int $index, Tokens $tokens): int
{
$stopTokens = [
\T_LNUMBER,
\T_DNUMBER,
\T_STRING,
\T_VARIABLE,
\T_CONSTANT_ENCAPSED_STRING,
];
for ($index; $index > 0; --$index) {
if ($tokens[$index]->isGivenKind($stopTokens) || $tokens[$index]->equals(')')) {
return $index;
}
}
return $index;
}
/**
* Checks if the semicolon closes a multiline call and returns the whitespace of the first call at $index.
* i.e. it will return the whitespace marked with '____' in the example underneath.
*
* ..
* ____$this->methodCall()
* ->anotherCall();
* ..
*/
private function findWhitespaceBeforeFirstCall(int $index, Tokens $tokens): ?string
{
$isMultilineCall = false;
$prevIndex = $tokens->getPrevMeaningfulToken($index);
while (!$tokens[$prevIndex]->equalsAny([';', ':', '{', '}', [\T_OPEN_TAG], [\T_OPEN_TAG_WITH_ECHO], [\T_ELSE]])) {
$index = $prevIndex;
$prevIndex = $tokens->getPrevMeaningfulToken($index);
$blockType = Tokens::detectBlockType($tokens[$index]);
if (null !== $blockType && !$blockType['isStart']) {
$prevIndex = $tokens->findBlockStart($blockType['type'], $index);
continue;
}
if ($tokens[$index]->isObjectOperator() || $tokens[$index]->isGivenKind(\T_DOUBLE_COLON)) {
$prevIndex = $tokens->getPrevMeaningfulToken($index);
$isMultilineCall = $isMultilineCall || $tokens->isPartialCodeMultiline($prevIndex, $index);
}
}
return $isMultilineCall ? WhitespacesAnalyzer::detectIndent($tokens, $index) : null;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Semicolon/NoEmptyStatementFixer.php | src/Fixer/Semicolon/NoEmptyStatementFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Semicolon;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoEmptyStatementFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Remove useless (semicolon) statements.',
[
new CodeSample("<?php \$a = 1;;\n"),
new CodeSample("<?php echo 1;2;\n"),
new CodeSample("<?php while(foo()){\n continue 1;\n}\n"),
],
);
}
/**
* {@inheritdoc}
*
* Must run before BracesFixer, CombineConsecutiveUnsetsFixer, EmptyLoopBodyFixer, MultilineWhitespaceBeforeSemicolonsFixer, NoExtraBlankLinesFixer, NoMultipleStatementsPerLineFixer, NoSinglelineWhitespaceBeforeSemicolonsFixer, NoTrailingWhitespaceFixer, NoUselessElseFixer, NoUselessReturnFixer, NoWhitespaceInBlankLineFixer, ReturnAssignmentFixer, SpaceAfterSemicolonFixer, SwitchCaseSemicolonToColonFixer.
* Must run after NoUselessSprintfFixer.
*/
public function getPriority(): int
{
return 40;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(';');
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) {
if ($tokens[$index]->isGivenKind([\T_BREAK, \T_CONTINUE])) {
$index = $tokens->getNextMeaningfulToken($index);
if ($tokens[$index]->equals([\T_LNUMBER, '1'])) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
continue;
}
// skip T_FOR parenthesis to ignore double `;` like `for ($i = 1; ; ++$i) {...}`
if ($tokens[$index]->isGivenKind(\T_FOR)) {
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextMeaningfulToken($index)) + 1;
continue;
}
if (!$tokens[$index]->equals(';')) {
continue;
}
$previousMeaningfulIndex = $tokens->getPrevMeaningfulToken($index);
// A semicolon can always be removed if it follows a semicolon, '{' or opening tag.
if ($tokens[$previousMeaningfulIndex]->equalsAny(['{', ';', [\T_OPEN_TAG]])) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
continue;
}
// A semicolon might be removed if it follows a '}' but only if the brace is part of certain structures.
if ($tokens[$previousMeaningfulIndex]->equals('}')) {
$this->fixSemicolonAfterCurlyBraceClose($tokens, $index, $previousMeaningfulIndex);
continue;
}
$nextIndex = $tokens->getNextMeaningfulToken($index);
if (null !== $nextIndex && $tokens[$nextIndex]->isGivenKind(CT::T_PROPERTY_HOOK_BRACE_CLOSE)) {
continue;
}
// A semicolon might be removed together with its noop statement, for example "<?php 1;"
$prePreviousMeaningfulIndex = $tokens->getPrevMeaningfulToken($previousMeaningfulIndex);
if (
$tokens[$prePreviousMeaningfulIndex]->equalsAny([';', '{', '}', [\T_OPEN_TAG]])
&& $tokens[$previousMeaningfulIndex]->isGivenKind([\T_CONSTANT_ENCAPSED_STRING, \T_DNUMBER, \T_LNUMBER, \T_STRING, \T_VARIABLE])
) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
$tokens->clearTokenAndMergeSurroundingWhitespace($previousMeaningfulIndex);
}
}
}
/**
* Fix semicolon after closing curly brace if needed.
*
* Test for the following cases
* - just '{' '}' block (following open tag or ';')
* - if, else, elseif
* - interface, trait, class (but not anonymous)
* - catch, finally (but not try)
* - for, foreach, while (but not 'do - while')
* - switch
* - function (declaration, but not lambda)
* - declare (with '{' '}')
* - namespace (with '{' '}')
*
* @param int $index Semicolon index
*/
private function fixSemicolonAfterCurlyBraceClose(Tokens $tokens, int $index, int $curlyCloseIndex): void
{
$curlyOpeningIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $curlyCloseIndex);
$beforeCurlyOpeningIndex = $tokens->getPrevMeaningfulToken($curlyOpeningIndex);
if ($tokens[$beforeCurlyOpeningIndex]->isGivenKind([\T_ELSE, \T_FINALLY, \T_NAMESPACE, \T_OPEN_TAG]) || $tokens[$beforeCurlyOpeningIndex]->equalsAny([';', '{', '}'])) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
return;
}
// check for namespaces and class, interface and trait definitions
if ($tokens[$beforeCurlyOpeningIndex]->isGivenKind(\T_STRING)) {
$classyTestIndex = $tokens->getPrevMeaningfulToken($beforeCurlyOpeningIndex);
while ($tokens[$classyTestIndex]->equals(',') || $tokens[$classyTestIndex]->isGivenKind([\T_STRING, \T_NS_SEPARATOR, \T_EXTENDS, \T_IMPLEMENTS])) {
$classyTestIndex = $tokens->getPrevMeaningfulToken($classyTestIndex);
}
$tokensAnalyzer = new TokensAnalyzer($tokens);
if (
$tokens[$classyTestIndex]->isGivenKind(\T_NAMESPACE)
|| ($tokens[$classyTestIndex]->isClassy() && !$tokensAnalyzer->isAnonymousClass($classyTestIndex))
) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
return;
}
// early return check, below only control structures with conditions are fixed
if (!$tokens[$beforeCurlyOpeningIndex]->equals(')')) {
return;
}
$openingBraceIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $beforeCurlyOpeningIndex);
$beforeOpeningBraceIndex = $tokens->getPrevMeaningfulToken($openingBraceIndex);
if ($tokens[$beforeOpeningBraceIndex]->isGivenKind([\T_IF, \T_ELSEIF, \T_FOR, \T_FOREACH, \T_WHILE, \T_SWITCH, \T_CATCH, \T_DECLARE])) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
return;
}
// check for function definition
if ($tokens[$beforeOpeningBraceIndex]->isGivenKind(\T_STRING)) {
$beforeStringIndex = $tokens->getPrevMeaningfulToken($beforeOpeningBraceIndex);
if ($tokens[$beforeStringIndex]->isGivenKind(\T_FUNCTION)) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index); // implicit return
}
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Semicolon/SemicolonAfterInstructionFixer.php | src/Fixer/Semicolon/SemicolonAfterInstructionFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Semicolon;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class SemicolonAfterInstructionFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Instructions must be terminated with a semicolon.',
[new CodeSample("<?php echo 1 ?>\n")],
);
}
/**
* {@inheritdoc}
*
* Must run before SimplifiedIfReturnFixer.
*/
public function getPriority(): int
{
return 2;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_CLOSE_TAG);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = \count($tokens) - 1; $index > 1; --$index) {
if (!$tokens[$index]->isGivenKind(\T_CLOSE_TAG)) {
continue;
}
$prev = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prev]->equalsAny([';', '{', '}', ':', [\T_OPEN_TAG]])) {
continue;
}
$tokens->insertAt($prev + 1, new Token(';'));
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Semicolon/SpaceAfterSemicolonFixer.php | src/Fixer/Semicolon/SpaceAfterSemicolonFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Semicolon;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* remove_in_empty_for_expressions?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* remove_in_empty_for_expressions: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class SpaceAfterSemicolonFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Fix whitespace after a semicolon.',
[
new CodeSample(
<<<'PHP'
<?php
sample(); $test = 1;
sample();$test = 2;
for ( ;;++$sample) {
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
for ($i = 0; ; ++$i) {
}
PHP,
[
'remove_in_empty_for_expressions' => true,
],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after CombineConsecutiveUnsetsFixer, MultilineWhitespaceBeforeSemicolonsFixer, NoEmptyStatementFixer, OrderedClassElementsFixer, SingleImportPerStatementFixer, SingleTraitInsertPerStatementFixer.
*/
public function getPriority(): int
{
return -1;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(';');
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('remove_in_empty_for_expressions', 'Whether spaces should be removed for empty `for` expressions.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$insideForParenthesesUntil = null;
for ($index = 0, $max = \count($tokens) - 1; $index < $max; ++$index) {
if (true === $this->configuration['remove_in_empty_for_expressions']) {
if ($tokens[$index]->isGivenKind(\T_FOR)) {
$index = $tokens->getNextMeaningfulToken($index);
$insideForParenthesesUntil = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
continue;
}
if ($index === $insideForParenthesesUntil) {
$insideForParenthesesUntil = null;
continue;
}
}
if (!$tokens[$index]->equals(';')) {
continue;
}
if (!$tokens[$index + 1]->isWhitespace()) {
if (
!$tokens[$index + 1]->equalsAny([')', [\T_INLINE_HTML]]) && (
false === $this->configuration['remove_in_empty_for_expressions']
|| !$tokens[$index + 1]->equals(';')
)
) {
$tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' ']));
++$max;
}
continue;
}
if (
null !== $insideForParenthesesUntil
&& ($tokens[$index + 2]->equals(';') || $index + 2 === $insideForParenthesesUntil)
&& !Preg::match('/\R/', $tokens[$index + 1]->getContent())
) {
$tokens->clearAt($index + 1);
continue;
}
if (
isset($tokens[$index + 2])
&& !$tokens[$index + 1]->equals([\T_WHITESPACE, ' '])
&& $tokens[$index + 1]->isWhitespace(" \t")
&& !$tokens[$index + 2]->isComment()
&& !$tokens[$index + 2]->equals(')')
) {
$tokens[$index + 1] = new Token([\T_WHITESPACE, ' ']);
}
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Semicolon/NoSinglelineWhitespaceBeforeSemicolonsFixer.php | src/Fixer/Semicolon/NoSinglelineWhitespaceBeforeSemicolonsFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Semicolon;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Graham Campbell <hello@gjcampbell.co.uk>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoSinglelineWhitespaceBeforeSemicolonsFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Single-line whitespace before closing semicolon are prohibited.',
[new CodeSample("<?php \$this->foo() ;\n")],
);
}
/**
* {@inheritdoc}
*
* Must run after CombineConsecutiveIssetsFixer, FunctionToConstantFixer, LongToShorthandOperatorFixer, NoEmptyStatementFixer, NoUnneededImportAliasFixer, SimplifiedIfReturnFixer, SingleImportPerStatementFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(';');
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if (!$token->equals(';') || !$tokens[$index - 1]->isWhitespace(" \t")) {
continue;
}
if ($tokens[$index - 2]->equals(';')) {
// do not remove all whitespace before the semicolon because it is also whitespace after another semicolon
$tokens->ensureWhitespaceAtIndex($index - 1, 0, ' ');
} elseif (!$tokens[$index - 2]->isComment()) {
$tokens->clearAt($index - 1);
}
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixer.php | src/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\NamespaceNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* Fixer for rules defined in PSR2 ¶3.
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class BlankLineAfterNamespaceFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There MUST be one blank line after the namespace declaration.',
[
new CodeSample("<?php\nnamespace Sample\\Sample;\n\n\n\$a;\n"),
new CodeSample("<?php\nnamespace Sample\\Sample;\nClass Test{}\n"),
],
);
}
/**
* {@inheritdoc}
*
* Must run after NoUnusedImportsFixer.
*/
public function getPriority(): int
{
return -20;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_NAMESPACE);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$lastIndex = $tokens->count() - 1;
for ($index = $lastIndex; $index >= 0; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(\T_NAMESPACE)) {
continue;
}
$semicolonIndex = $tokens->getNextTokenOfKind($index, [';', '{', [\T_CLOSE_TAG]]);
$semicolonToken = $tokens[$semicolonIndex];
if (!$semicolonToken->equals(';')) {
continue;
}
$indexToEnsureBlankLineAfter = $this->getIndexToEnsureBlankLineAfter($tokens, $semicolonIndex);
$indexToEnsureBlankLine = $tokens->getNonEmptySibling($indexToEnsureBlankLineAfter, 1);
if (null !== $indexToEnsureBlankLine && $tokens[$indexToEnsureBlankLine]->isWhitespace()) {
$tokens[$indexToEnsureBlankLine] = $this->getTokenToInsert($tokens[$indexToEnsureBlankLine]->getContent(), $indexToEnsureBlankLine === $lastIndex);
} else {
$tokens->insertAt($indexToEnsureBlankLineAfter + 1, $this->getTokenToInsert('', $indexToEnsureBlankLineAfter === $lastIndex));
}
}
}
private function getIndexToEnsureBlankLineAfter(Tokens $tokens, int $index): int
{
$indexToEnsureBlankLine = $index;
$nextIndex = $tokens->getNonEmptySibling($indexToEnsureBlankLine, 1);
while (null !== $nextIndex) {
$token = $tokens[$nextIndex];
if ($token->isWhitespace()) {
if (Preg::match('/\R/', $token->getContent())) {
break;
}
$nextNextIndex = $tokens->getNonEmptySibling($nextIndex, 1);
if (!$tokens[$nextNextIndex]->isComment()) {
break;
}
}
if (!$token->isWhitespace() && !$token->isComment()) {
break;
}
$indexToEnsureBlankLine = $nextIndex;
$nextIndex = $tokens->getNonEmptySibling($indexToEnsureBlankLine, 1);
}
return $indexToEnsureBlankLine;
}
private function getTokenToInsert(string $currentContent, bool $isLastIndex): Token
{
$ending = $this->whitespacesConfig->getLineEnding();
$emptyLines = $isLastIndex ? $ending : $ending.$ending;
$indent = Preg::match('/^.*\R( *)$/s', $currentContent, $matches) ? $matches[1] : '';
return new Token([\T_WHITESPACE, $emptyLines.$indent]);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/NamespaceNotation/CleanNamespaceFixer.php | src/Fixer/NamespaceNotation/CleanNamespaceFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\NamespaceNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class CleanNamespaceFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
$samples = [];
foreach (['namespace Foo \ Bar;', 'echo foo /* comment */ \ bar();'] as $sample) {
$samples[] = new VersionSpecificCodeSample(
"<?php\n".$sample."\n",
new VersionSpecification(null, 8_00_00 - 1),
);
}
return new FixerDefinition(
'Namespace must not contain spacing, comments or PHPDoc.',
$samples,
);
}
public function isCandidate(Tokens $tokens): bool
{
return \PHP_VERSION_ID < 8_00_00 && $tokens->isTokenKindFound(\T_NS_SEPARATOR);
}
/**
* {@inheritdoc}
*
* Must run before PhpUnitDataProviderReturnTypeFixer.
*/
public function getPriority(): int
{
return 10;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$count = $tokens->count();
for ($index = 0; $index < $count; ++$index) {
if ($tokens[$index]->isGivenKind(\T_NS_SEPARATOR)) {
$previousIndex = $tokens->getPrevMeaningfulToken($index);
$index = $this->fixNamespace(
$tokens,
$tokens[$previousIndex]->isGivenKind(\T_STRING) ? $previousIndex : $index,
);
}
}
}
/**
* @param int $index start of namespace
*/
private function fixNamespace(Tokens $tokens, int $index): int
{
$tillIndex = $index;
// go to the end of the namespace
while ($tokens[$tillIndex]->isGivenKind([\T_NS_SEPARATOR, \T_STRING])) {
$tillIndex = $tokens->getNextMeaningfulToken($tillIndex);
}
$tillIndex = $tokens->getPrevMeaningfulToken($tillIndex);
$spaceIndices = [];
for (; $index <= $tillIndex; ++$index) {
if ($tokens[$index]->isGivenKind(\T_WHITESPACE)) {
$spaceIndices[] = $index;
} elseif ($tokens[$index]->isComment()) {
$tokens->clearAt($index);
}
}
if ($tokens[$index - 1]->isWhitespace()) {
array_pop($spaceIndices);
}
foreach ($spaceIndices as $i) {
$tokens->clearAt($i);
}
return $index;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixer.php | src/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\NamespaceNotation;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Graham Campbell <hello@gjcampbell.co.uk>
*
* @deprecated Use `blank_lines_before_namespace` with config: ['min_line_breaks' => 2, 'max_line_breaks' => 2] (default)
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class SingleBlankLineBeforeNamespaceFixer extends AbstractProxyFixer implements WhitespacesAwareFixerInterface, DeprecatedFixerInterface
{
public function getSuccessorsNames(): array
{
return array_keys($this->proxyFixers);
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There should be exactly one blank line before a namespace declaration.',
[
new CodeSample("<?php namespace A {}\n"),
new CodeSample("<?php\n\n\nnamespace A{}\n"),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_NAMESPACE);
}
/**
* {@inheritdoc}
*
* Must run after HeaderCommentFixer.
*/
public function getPriority(): int
{
return parent::getPriority();
}
protected function createProxyFixers(): array
{
$blankLineBeforeNamespace = new BlankLinesBeforeNamespaceFixer();
$blankLineBeforeNamespace->configure([
'min_line_breaks' => 2,
'max_line_breaks' => 2,
]);
return [
$blankLineBeforeNamespace,
];
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixer.php | src/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\NamespaceNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Bram Gotink <bram@gotink.me>
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoLeadingNamespaceWhitespaceFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_NAMESPACE);
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'The namespace declaration line shouldn\'t contain leading whitespace.',
[
new CodeSample(
<<<'PHP'
<?php
namespace Test8a;
namespace Test8b;
PHP,
),
],
);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = \count($tokens) - 1; 0 <= $index; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(\T_NAMESPACE)) {
continue;
}
$beforeNamespaceIndex = $index - 1;
$beforeNamespace = $tokens[$beforeNamespaceIndex];
if (!$beforeNamespace->isWhitespace()) {
if (!self::endsWithWhitespace($beforeNamespace->getContent())) {
$tokens->insertAt($index, new Token([\T_WHITESPACE, $this->whitespacesConfig->getLineEnding()]));
}
continue;
}
$lastNewline = strrpos($beforeNamespace->getContent(), "\n");
if (false === $lastNewline) {
$beforeBeforeNamespace = $tokens[$index - 2];
if (self::endsWithWhitespace($beforeBeforeNamespace->getContent())) {
$tokens->clearAt($beforeNamespaceIndex);
} else {
$tokens[$beforeNamespaceIndex] = new Token([\T_WHITESPACE, ' ']);
}
} else {
$tokens[$beforeNamespaceIndex] = new Token([\T_WHITESPACE, substr($beforeNamespace->getContent(), 0, $lastNewline + 1)]);
}
}
}
private static function endsWithWhitespace(string $str): bool
{
if ('' === $str) {
return false;
}
return '' === trim(substr($str, -1));
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixer.php | src/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\NamespaceNotation;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Graham Campbell <hello@gjcampbell.co.uk>
*
* @deprecated Use `blank_lines_before_namespace` with config: ['min_line_breaks' => 0, 'max_line_breaks' => 1]
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoBlankLinesBeforeNamespaceFixer extends AbstractProxyFixer implements WhitespacesAwareFixerInterface, DeprecatedFixerInterface
{
public function getSuccessorsNames(): array
{
return array_keys($this->proxyFixers);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_NAMESPACE);
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There should be no blank lines before a namespace declaration.',
[
new CodeSample(
"<?php\n\n\n\nnamespace Example;\n",
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after BlankLineAfterOpeningTagFixer.
*/
public function getPriority(): int
{
return 0;
}
protected function createProxyFixers(): array
{
$blankLineBeforeNamespace = new BlankLinesBeforeNamespaceFixer();
$blankLineBeforeNamespace->configure([
'min_line_breaks' => 0,
'max_line_breaks' => 1,
]);
return [
$blankLineBeforeNamespace,
];
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/NamespaceNotation/BlankLinesBeforeNamespaceFixer.php | src/Fixer/NamespaceNotation/BlankLinesBeforeNamespaceFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\NamespaceNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Options;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* max_line_breaks?: int,
* min_line_breaks?: int,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* max_line_breaks: int,
* min_line_breaks: int,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Graham Campbell <hello@gjcampbell.co.uk>
* @author Greg Korba <greg@codito.dev>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class BlankLinesBeforeNamespaceFixer extends AbstractFixer implements WhitespacesAwareFixerInterface, ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Controls blank lines before a namespace declaration.',
[
new CodeSample("<?php namespace A {}\n"),
new CodeSample("<?php namespace A {}\n", ['min_line_breaks' => 1]),
new CodeSample("<?php\n\ndeclare(strict_types=1);\n\n\n\nnamespace A{}\n", ['max_line_breaks' => 2]),
new CodeSample("<?php\n\n/** Some comment */\nnamespace A{}\n", ['min_line_breaks' => 2]),
new CodeSample("<?php\n\nnamespace A{}\n", ['min_line_breaks' => 0, 'max_line_breaks' => 0]),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_NAMESPACE);
}
/**
* {@inheritdoc}
*
* Must run after BlankLineAfterOpeningTagFixer, HeaderCommentFixer.
*/
public function getPriority(): int
{
return -31;
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('min_line_breaks', 'Minimum line breaks that should exist before namespace declaration.'))
->setAllowedTypes(['int'])
->setDefault(2)
->setNormalizer(static function (Options $options, int $value): int {
if ($value < 0) {
throw new InvalidFixerConfigurationException(
(new self())->getName(),
'Option `min_line_breaks` cannot be lower than 0.',
);
}
return $value;
})
->getOption(),
(new FixerOptionBuilder('max_line_breaks', 'Maximum line breaks that should exist before namespace declaration.'))
->setAllowedTypes(['int'])
->setDefault(2)
->setNormalizer(static function (Options $options, int $value): int {
if ($value < 0) {
throw new InvalidFixerConfigurationException(
(new self())->getName(),
'Option `max_line_breaks` cannot be lower than 0.',
);
}
if ($value < $options['min_line_breaks']) {
throw new InvalidFixerConfigurationException(
(new self())->getName(),
'Option `max_line_breaks` cannot have lower value than `min_line_breaks`.',
);
}
return $value;
})
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if ($token->isGivenKind(\T_NAMESPACE)) {
$this->fixLinesBeforeNamespace(
$tokens,
$index,
$this->configuration['min_line_breaks'],
$this->configuration['max_line_breaks'],
);
}
}
}
/**
* Make sure # of line breaks prefixing namespace is within given range.
*
* @param int $expectedMin min. # of line breaks
* @param int $expectedMax max. # of line breaks
*/
protected function fixLinesBeforeNamespace(Tokens $tokens, int $index, int $expectedMin, int $expectedMax): void
{
// Let's determine the total numbers of new lines before the namespace
// and the opening token
$openingTokenIndex = null;
$precedingNewlines = 0;
$newlineInOpening = false;
$openingToken = null;
for ($i = 1; $i <= 2; ++$i) {
if (isset($tokens[$index - $i])) {
$token = $tokens[$index - $i];
if ($token->isGivenKind(\T_OPEN_TAG)) {
$openingToken = $token;
$openingTokenIndex = $index - $i;
$newlineInOpening = str_contains($token->getContent(), "\n");
if ($newlineInOpening) {
++$precedingNewlines;
}
break;
}
if (false === $token->isGivenKind(\T_WHITESPACE)) {
break;
}
$precedingNewlines += substr_count($token->getContent(), "\n");
}
}
if ($precedingNewlines >= $expectedMin && $precedingNewlines <= $expectedMax) {
return;
}
$previousIndex = $index - 1;
$previous = $tokens[$previousIndex];
if (0 === $expectedMax) {
// Remove all the previous new lines
if ($previous->isWhitespace()) {
$tokens->clearAt($previousIndex);
}
// Remove new lines in opening token
if ($newlineInOpening) {
$tokens[$openingTokenIndex] = new Token([\T_OPEN_TAG, rtrim($openingToken->getContent()).' ']);
}
return;
}
$lineEnding = $this->whitespacesConfig->getLineEnding();
// Allow only as many line breaks as configured:
// - keep as-is when current preceding line breaks are within configured range
// - use configured max line breaks if currently there is more preceding line breaks
// - use configured min line breaks if currently there is less preceding line breaks
$newlinesForWhitespaceToken = $precedingNewlines >= $expectedMax
? $expectedMax
: max($precedingNewlines, $expectedMin);
if (null !== $openingToken) {
// Use the configured line ending for the PHP opening tag
$content = rtrim($openingToken->getContent());
$newContent = $content.$lineEnding;
$tokens[$openingTokenIndex] = new Token([\T_OPEN_TAG, $newContent]);
--$newlinesForWhitespaceToken;
}
if (0 === $newlinesForWhitespaceToken) {
// We have all the needed new lines in the opening tag
if ($previous->isWhitespace()) {
// Let's remove the previous token containing extra new lines
$tokens->clearAt($previousIndex);
}
return;
}
if ($previous->isWhitespace()) {
// Fix the previous whitespace token
$content = $previous->getContent();
$pos = strrpos($content, "\n");
$content = false === $pos ? '' : substr($content, $pos + 1);
$tokens[$previousIndex] = new Token([\T_WHITESPACE, str_repeat($lineEnding, $newlinesForWhitespaceToken).$content]);
} else {
// Add a new whitespace token
$tokens->insertAt($index, new Token([\T_WHITESPACE, str_repeat($lineEnding, $newlinesForWhitespaceToken)]));
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Cache/Signature.php | src/Cache/Signature.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Cache;
/**
* @author Andreas Möller <am@localheinz.com>
*
* @readonly
*
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class Signature implements SignatureInterface
{
private string $phpVersion;
private string $fixerVersion;
private string $indent;
private string $lineEnding;
/**
* @var array<string, array<string, mixed>|bool>
*/
private array $rules;
private string $ruleCustomisationPolicyVersion;
/**
* @param array<string, array<string, mixed>|bool> $rules
*/
public function __construct(string $phpVersion, string $fixerVersion, string $indent, string $lineEnding, array $rules, string $ruleCustomisationPolicyVersion)
{
$this->phpVersion = $phpVersion;
$this->fixerVersion = $fixerVersion;
$this->indent = $indent;
$this->lineEnding = $lineEnding;
$this->rules = self::makeJsonEncodable($rules);
$this->ruleCustomisationPolicyVersion = $ruleCustomisationPolicyVersion;
}
public function getPhpVersion(): string
{
return $this->phpVersion;
}
public function getFixerVersion(): string
{
return $this->fixerVersion;
}
public function getIndent(): string
{
return $this->indent;
}
public function getLineEnding(): string
{
return $this->lineEnding;
}
public function getRules(): array
{
return $this->rules;
}
public function getRuleCustomisationPolicyVersion(): string
{
return $this->ruleCustomisationPolicyVersion;
}
public function equals(SignatureInterface $signature): bool
{
return $this->phpVersion === $signature->getPhpVersion()
&& $this->fixerVersion === $signature->getFixerVersion()
&& $this->indent === $signature->getIndent()
&& $this->lineEnding === $signature->getLineEnding()
&& $this->rules === $signature->getRules()
&& $this->ruleCustomisationPolicyVersion === $signature->getRuleCustomisationPolicyVersion();
}
/**
* @param array<string, array<string, mixed>|bool> $data
*
* @return array<string, array<string, mixed>|bool>
*/
private static function makeJsonEncodable(array $data): array
{
array_walk_recursive($data, static function (&$item): void {
if (\is_string($item) && false === mb_detect_encoding($item, 'utf-8', true)) {
$item = base64_encode($item);
}
});
return $data;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Cache/DirectoryInterface.php | src/Cache/DirectoryInterface.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Cache;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
interface DirectoryInterface
{
public function getRelativePathTo(string $file): string;
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.