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/ConfigurableFixerInterface.php
src/Fixer/ConfigurableFixerInterface.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; use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; /** * @template TFixerInputConfig of array<string, mixed> * @template TFixerComputedConfig of array<string, mixed> * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ interface ConfigurableFixerInterface extends FixerInterface { /** * Set configuration. * * New configuration must override current one, not patch it. * Using empty array makes fixer to use default configuration * (or reset configuration from previously configured back to default one). * * Some fixers may have no configuration, then - simply don't implement this interface. * Other ones may have configuration that will change behaviour of fixer, * eg `php_unit_strict` fixer allows to configure which methods should be fixed. * Finally, some fixers need configuration to work, eg `header_comment`. * * @param TFixerInputConfig $configuration configuration depends on Fixer * * @throws InvalidFixerConfigurationException */ public function configure(array $configuration): void; /** * Defines the available configuration options of the fixer. */ public function getConfigurationDefinition(): FixerConfigurationResolverInterface; }
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/DeprecatedFixerInterface.php
src/Fixer/DeprecatedFixerInterface.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; /** * @author Kuba Werłos <werlos@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ interface DeprecatedFixerInterface extends FixerInterface { /** * Returns names of fixers to use instead, if any. * * @return list<string> */ public function getSuccessorsNames(): array; }
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/ControlStructure/NoUnneededCurlyBracesFixer.php
src/Fixer/ControlStructure/NoUnneededCurlyBracesFixer.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\ControlStructure; use PhpCsFixer\AbstractProxyFixer; use PhpCsFixer\Fixer\ConfigurableFixerInterface; use PhpCsFixer\Fixer\ConfigurableFixerTrait; use PhpCsFixer\Fixer\DeprecatedFixerInterface; use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; /** * @deprecated * * @phpstan-type _AutogeneratedInputConfiguration array{ * namespaces?: bool, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * namespaces: bool, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NoUnneededCurlyBracesFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, DeprecatedFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; private NoUnneededBracesFixer $noUnneededBracesFixer; public function __construct() { $this->noUnneededBracesFixer = new NoUnneededBracesFixer(); parent::__construct(); } public function getDefinition(): FixerDefinitionInterface { $fixerDefinition = $this->noUnneededBracesFixer->getDefinition(); return new FixerDefinition( 'Removes unneeded curly braces that are superfluous and aren\'t part of a control structure\'s body.', $fixerDefinition->getCodeSamples(), $fixerDefinition->getDescription(), $fixerDefinition->getRiskyDescription(), ); } /** * {@inheritdoc} * * Must run before NoUselessElseFixer, NoUselessReturnFixer, ReturnAssignmentFixer, SimplifiedIfReturnFixer. */ public function getPriority(): int { return $this->noUnneededBracesFixer->getPriority(); } public function getSuccessorsNames(): array { return [ $this->noUnneededBracesFixer->getName(), ]; } /** * @param _AutogeneratedInputConfiguration $configuration */ protected function configurePreNormalisation(array $configuration): void { $this->noUnneededBracesFixer->configure($configuration); } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('namespaces', 'Remove unneeded curly braces from bracketed namespaces.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), ]); } protected function createProxyFixers(): array { return [ $this->noUnneededBracesFixer, ]; } }
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/ControlStructure/EmptyLoopConditionFixer.php
src/Fixer/ControlStructure/EmptyLoopConditionFixer.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\ControlStructure; 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{ * style?: 'for'|'while', * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * style: 'for'|'while', * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class EmptyLoopConditionFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; private const STYLE_FOR = 'for'; private const STYLE_WHILE = 'while'; private const TOKEN_LOOP_KINDS = [\T_FOR, \T_WHILE]; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Empty loop-condition must be in configured style.', [ new CodeSample("<?php\nfor(;;) {\n foo();\n}\n\ndo {\n foo();\n} while(true); // do while\n"), new CodeSample("<?php\nwhile(true) {\n foo();\n}\n", ['style' => self::STYLE_FOR]), ], ); } /** * {@inheritdoc} * * Must run before NoExtraBlankLinesFixer, NoTrailingWhitespaceFixer. */ public function getPriority(): int { return 1; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound(self::TOKEN_LOOP_KINDS); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { if (self::STYLE_WHILE === $this->configuration['style']) { $candidateLoopKinds = [\T_FOR, \T_WHILE]; $replacement = [new Token([\T_WHILE, 'while']), new Token([\T_WHITESPACE, ' ']), new Token('('), new Token([\T_STRING, 'true']), new Token(')')]; $fixLoop = static function (int $index, int $openIndex, int $endIndex) use ($tokens, $replacement): void { if (self::isForLoopWithEmptyCondition($tokens, $index, $openIndex, $endIndex)) { self::clearNotCommentsInRange($tokens, $index, $endIndex); self::cloneAndInsert($tokens, $index, $replacement); } elseif (self::isWhileLoopWithEmptyCondition($tokens, $index, $openIndex, $endIndex)) { $doIndex = self::getDoIndex($tokens, $index); if (null !== $doIndex) { self::clearNotCommentsInRange($tokens, $index, $tokens->getNextMeaningfulToken($endIndex)); // clear including `;` $tokens->clearAt($doIndex); self::cloneAndInsert($tokens, $doIndex, $replacement); } } }; } else { // self::STYLE_FOR $candidateLoopKinds = [\T_WHILE]; $replacement = [new Token([\T_FOR, 'for']), new Token('('), new Token(';'), new Token(';'), new Token(')')]; $fixLoop = static function (int $index, int $openIndex, int $endIndex) use ($tokens, $replacement): void { if (!self::isWhileLoopWithEmptyCondition($tokens, $index, $openIndex, $endIndex)) { return; } $doIndex = self::getDoIndex($tokens, $index); if (null === $doIndex) { self::clearNotCommentsInRange($tokens, $index, $endIndex); self::cloneAndInsert($tokens, $index, $replacement); } else { self::clearNotCommentsInRange($tokens, $index, $tokens->getNextMeaningfulToken($endIndex)); // clear including `;` $tokens->clearAt($doIndex); self::cloneAndInsert($tokens, $doIndex, $replacement); } }; } for ($index = $tokens->count() - 1; $index > 0; --$index) { if ($tokens[$index]->isGivenKind($candidateLoopKinds)) { $openIndex = $tokens->getNextTokenOfKind($index, ['(']); // proceed to open '(' $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); // proceed to close ')' $fixLoop($index, $openIndex, $endIndex); // fix loop if needed } } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('style', 'Style of empty loop-condition.')) ->setAllowedTypes(['string']) ->setAllowedValues([self::STYLE_WHILE, self::STYLE_FOR]) ->setDefault(self::STYLE_WHILE) ->getOption(), ]); } private static function clearNotCommentsInRange(Tokens $tokens, int $indexStart, int $indexEnd): void { for ($i = $indexStart; $i <= $indexEnd; ++$i) { if (!$tokens[$i]->isComment()) { $tokens->clearTokenAndMergeSurroundingWhitespace($i); } } } /** * @param list<Token> $replacement */ private static function cloneAndInsert(Tokens $tokens, int $index, array $replacement): void { $replacementClones = []; foreach ($replacement as $token) { $replacementClones[] = clone $token; } $tokens->insertAt($index, $replacementClones); } private static function getDoIndex(Tokens $tokens, int $index): ?int { $endIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$endIndex]->equals('}')) { return null; } $startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $endIndex); $index = $tokens->getPrevMeaningfulToken($startIndex); return null === $index || !$tokens[$index]->isGivenKind(\T_DO) ? null : $index; } private static function isForLoopWithEmptyCondition(Tokens $tokens, int $index, int $openIndex, int $endIndex): bool { if (!$tokens[$index]->isGivenKind(\T_FOR)) { return false; } $index = $tokens->getNextMeaningfulToken($openIndex); if (null === $index || !$tokens[$index]->equals(';')) { return false; } $index = $tokens->getNextMeaningfulToken($index); return null !== $index && $tokens[$index]->equals(';') && $endIndex === $tokens->getNextMeaningfulToken($index); } private static function isWhileLoopWithEmptyCondition(Tokens $tokens, int $index, int $openIndex, int $endIndex): bool { if (!$tokens[$index]->isGivenKind(\T_WHILE)) { return false; } $index = $tokens->getNextMeaningfulToken($openIndex); return null !== $index && $tokens[$index]->equals([\T_STRING, 'true']) && $endIndex === $tokens->getNextMeaningfulToken($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/ControlStructure/TrailingCommaInMultilineFixer.php
src/Fixer/ControlStructure/TrailingCommaInMultilineFixer.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\ControlStructure; 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\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; use PhpCsFixer\Tokenizer\TokensAnalyzer; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * after_heredoc?: bool, * elements?: list<'arguments'|'array_destructuring'|'arrays'|'match'|'parameters'>, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * after_heredoc: bool, * elements: list<'arguments'|'array_destructuring'|'arrays'|'match'|'parameters'>, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @author Sebastiaan Stok <s.stok@rollerscapes.net> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * @author Kuba Werłos <werlos@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class TrailingCommaInMultilineFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; /** * @internal */ public const ELEMENTS_ARRAYS = 'arrays'; /** * @internal */ public const ELEMENTS_ARGUMENTS = 'arguments'; /** * @internal */ public const ELEMENTS_PARAMETERS = 'parameters'; private const MATCH_EXPRESSIONS = 'match'; private const ARRAY_DESTRUCTURING = 'array_destructuring'; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Arguments lists, array destructuring lists, arrays that are multi-line, `match`-lines and parameters lists must have a trailing comma.', [ new CodeSample("<?php\narray(\n 1,\n 2\n);\n"), new CodeSample( <<<'SAMPLE' <?php $x = [ 'foo', <<<EOD bar EOD ]; SAMPLE, ['after_heredoc' => true], ), new CodeSample("<?php\nfoo(\n 1,\n 2\n);\n", ['elements' => [self::ELEMENTS_ARGUMENTS]]), new VersionSpecificCodeSample("<?php\nfunction foo(\n \$x,\n \$y\n)\n{\n}\n", new VersionSpecification(8_00_00), ['elements' => [self::ELEMENTS_PARAMETERS]]), ], ); } /** * {@inheritdoc} * * Must run after MultilinePromotedPropertiesFixer. */ public function getPriority(): int { return 0; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN, '(', CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN]); } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('after_heredoc', 'Whether a trailing comma should also be placed after heredoc end.')) ->setAllowedTypes(['bool']) ->setDefault(Future::getV4OrV3(true, false)) ->getOption(), (new FixerOptionBuilder('elements', \sprintf('Where to fix multiline trailing comma (PHP >= 8.0 for `%s` and `%s`).', self::ELEMENTS_PARAMETERS, self::MATCH_EXPRESSIONS))) // @TODO: remove text when PHP 8.0+ is required ->setAllowedTypes(['string[]']) ->setAllowedValues([ new AllowedValueSubset([ self::ARRAY_DESTRUCTURING, self::ELEMENTS_ARGUMENTS, self::ELEMENTS_ARRAYS, self::ELEMENTS_PARAMETERS, self::MATCH_EXPRESSIONS, ]), ]) ->setDefault([self::ELEMENTS_ARRAYS]) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $configuredElements = $this->configuration['elements']; $fixArrays = \in_array(self::ELEMENTS_ARRAYS, $configuredElements, true); $fixArguments = \in_array(self::ELEMENTS_ARGUMENTS, $configuredElements, true); $fixParameters = \PHP_VERSION_ID >= 8_00_00 && \in_array(self::ELEMENTS_PARAMETERS, $configuredElements, true); // @TODO: drop condition when PHP 8.0+ is required $fixMatch = \PHP_VERSION_ID >= 8_00_00 && \in_array(self::MATCH_EXPRESSIONS, $configuredElements, true); // @TODO: drop condition when PHP 8.0+ is required $fixDestructuring = \in_array(self::ARRAY_DESTRUCTURING, $configuredElements, true); for ($index = $tokens->count() - 1; $index >= 0; --$index) { if ($tokens[$index]->isGivenKind(CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN)) { if ($fixDestructuring) { // array destructing short syntax $this->fixBlock($tokens, $index); } continue; } if ($tokens[$index]->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { if ($fixArrays) { // array short syntax $this->fixBlock($tokens, $index); } continue; } if (!$tokens[$index]->equals('(')) { continue; } $prevIndex = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prevIndex]->isGivenKind(\T_ARRAY)) { if ($fixArrays) { // array long syntax $this->fixBlock($tokens, $index); } continue; } if ($tokens[$prevIndex]->isGivenKind(\T_LIST)) { if ($fixDestructuring || $fixArguments) { // array destructing long syntax $this->fixBlock($tokens, $index); } continue; } if ($fixMatch && $tokens[$prevIndex]->isGivenKind(\T_MATCH)) { $this->fixBlock($tokens, $tokens->getNextTokenOfKind($index, ['{'])); continue; } $prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex); if ($fixArguments && $tokens[$prevIndex]->equalsAny([']', [\T_CLASS], [\T_STRING], [\T_VARIABLE], [\T_STATIC], [\T_ISSET], [\T_UNSET], [\T_LIST]]) && !$tokens[$prevPrevIndex]->isGivenKind(\T_FUNCTION) ) { $this->fixBlock($tokens, $index); continue; } if ( $fixParameters && ( $tokens[$prevIndex]->isGivenKind(\T_STRING) && $tokens[$prevPrevIndex]->isGivenKind(\T_FUNCTION) || $tokens[$prevIndex]->isGivenKind([\T_FN, \T_FUNCTION]) ) ) { $this->fixBlock($tokens, $index); } } } private function fixBlock(Tokens $tokens, int $startIndex): void { $tokensAnalyzer = new TokensAnalyzer($tokens); if (!$tokensAnalyzer->isBlockMultiline($tokens, $startIndex)) { return; } $blockType = Tokens::detectBlockType($tokens[$startIndex]); $endIndex = $tokens->findBlockEnd($blockType['type'], $startIndex); $beforeEndIndex = $tokens->getPrevMeaningfulToken($endIndex); if (!$tokens->isPartialCodeMultiline($beforeEndIndex, $endIndex)) { return; } $beforeEndToken = $tokens[$beforeEndIndex]; // if there is some item between braces then add `,` after it if ( $startIndex !== $beforeEndIndex && !$beforeEndToken->equals(',') && (true === $this->configuration['after_heredoc'] || !$beforeEndToken->isGivenKind(\T_END_HEREDOC)) ) { $tokens->insertAt($beforeEndIndex + 1, new Token(',')); $endToken = $tokens[$endIndex]; if (!$endToken->isComment() && !$endToken->isWhitespace()) { $tokens->ensureWhitespaceAtIndex($endIndex, 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/ControlStructure/NoBreakCommentFixer.php
src/Fixer/ControlStructure/NoBreakCommentFixer.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\ControlStructure; 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\FCT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; use Symfony\Component\OptionsResolver\Options; /** * Fixer for rule defined in PSR2 ¶5.2. * * @phpstan-type _AutogeneratedInputConfiguration array{ * comment_text?: string, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * comment_text: string, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NoBreakCommentFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; private const STRUCTURE_KINDS = [\T_FOR, \T_FOREACH, \T_WHILE, \T_IF, \T_ELSEIF, \T_SWITCH, \T_FUNCTION, FCT::T_MATCH]; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'There must be a comment when fall-through is intentional in a non-empty case body.', [ new CodeSample( <<<'PHP' <?php switch ($foo) { case 1: foo(); case 2: bar(); // no break break; case 3: baz(); } PHP, ), new CodeSample( <<<'PHP' <?php switch ($foo) { case 1: foo(); case 2: foo(); } PHP, ['comment_text' => 'some comment'], ), ], 'Adds a "no break" comment before fall-through cases, and removes it if there is no fall-through.', ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_SWITCH); } /** * {@inheritdoc} * * Must run after NoUselessElseFixer. */ public function getPriority(): int { return 0; } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('comment_text', 'The text to use in the added comment and to detect it.')) ->setAllowedTypes(['string']) ->setAllowedValues([ static function (string $value): bool { if (Preg::match('/\R/', $value)) { throw new InvalidOptionsException('The comment text must not contain new lines.'); } return true; }, ]) ->setNormalizer(static fn (Options $options, string $value): string => rtrim($value)) ->setDefault('no break') ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { for ($index = \count($tokens) - 1; $index >= 0; --$index) { if ($tokens[$index]->isGivenKind(\T_DEFAULT)) { if ($tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(\T_DOUBLE_ARROW)) { continue; // this is "default" from "match" } } elseif (!$tokens[$index]->isGivenKind(\T_CASE)) { continue; } $this->fixCase($tokens, $tokens->getNextTokenOfKind($index, [':', ';'])); } } private function fixCase(Tokens $tokens, int $casePosition): void { $empty = true; $fallThrough = true; $commentPosition = null; for ($i = $casePosition + 1, $max = \count($tokens); $i < $max; ++$i) { if ($tokens[$i]->isGivenKind([...self::STRUCTURE_KINDS, \T_ELSE, \T_DO, \T_CLASS])) { $empty = false; $i = $this->getStructureEnd($tokens, $i); continue; } if ($tokens[$i]->isGivenKind([\T_BREAK, \T_CONTINUE, \T_RETURN, \T_EXIT, \T_GOTO])) { $fallThrough = false; continue; } if ($tokens[$i]->isGivenKind(\T_THROW)) { $previousIndex = $tokens->getPrevMeaningfulToken($i); if ($previousIndex === $casePosition || $tokens[$previousIndex]->equalsAny(['{', ';', '}', [\T_OPEN_TAG]])) { $fallThrough = false; } continue; } if ($tokens[$i]->equals('}') || $tokens[$i]->isGivenKind(\T_ENDSWITCH)) { if (null !== $commentPosition) { $this->removeComment($tokens, $commentPosition); } break; } if ($this->isNoBreakComment($tokens[$i])) { $commentPosition = $i; continue; } if ($tokens[$i]->isGivenKind([\T_CASE, \T_DEFAULT])) { if (!$empty && $fallThrough) { if (null !== $commentPosition && $tokens->getPrevNonWhitespace($i) !== $commentPosition) { $this->removeComment($tokens, $commentPosition); $commentPosition = null; } if (null === $commentPosition) { $this->insertCommentAt($tokens, $i); } else { $text = $this->configuration['comment_text']; $tokens[$commentPosition] = new Token([ $tokens[$commentPosition]->getId(), str_ireplace($text, $text, $tokens[$commentPosition]->getContent()), ]); $this->ensureNewLineAt($tokens, $commentPosition); } } elseif (null !== $commentPosition) { $this->removeComment($tokens, $commentPosition); } break; } if (!$tokens[$i]->isGivenKind([\T_COMMENT, \T_WHITESPACE])) { $empty = false; } } } private function isNoBreakComment(Token $token): bool { if (!$token->isComment()) { return false; } $text = preg_quote($this->configuration['comment_text'], '~'); return Preg::match("~^((//|#)\\s*{$text}\\s*)|(/\\*\\*?\\s*{$text}(\\s+.*)*\\*/)$~i", $token->getContent()); } private function insertCommentAt(Tokens $tokens, int $casePosition): void { $lineEnding = $this->whitespacesConfig->getLineEnding(); $newlinePosition = $this->ensureNewLineAt($tokens, $casePosition); $newlineToken = $tokens[$newlinePosition]; $nbNewlines = substr_count($newlineToken->getContent(), $lineEnding); if ($newlineToken->isGivenKind(\T_OPEN_TAG) && Preg::match('/\R/', $newlineToken->getContent())) { ++$nbNewlines; } elseif ($tokens[$newlinePosition - 1]->isGivenKind(\T_OPEN_TAG) && Preg::match('/\R/', $tokens[$newlinePosition - 1]->getContent())) { ++$nbNewlines; if (!Preg::match('/\R/', $newlineToken->getContent())) { $tokens[$newlinePosition] = new Token([$newlineToken->getId(), $lineEnding.$newlineToken->getContent()]); } } if ($nbNewlines > 1) { Preg::match('/^(.*?)(\R\h*)$/s', $newlineToken->getContent(), $matches); $indent = WhitespacesAnalyzer::detectIndent($tokens, $newlinePosition - 1); $tokens[$newlinePosition] = new Token([$newlineToken->getId(), $matches[1].$lineEnding.$indent]); $tokens->insertAt(++$newlinePosition, new Token([\T_WHITESPACE, $matches[2]])); } $tokens->insertAt($newlinePosition, new Token([\T_COMMENT, '// '.$this->configuration['comment_text']])); $this->ensureNewLineAt($tokens, $newlinePosition); } /** * @return int The newline token position */ private function ensureNewLineAt(Tokens $tokens, int $position): int { $lineEnding = $this->whitespacesConfig->getLineEnding(); $content = $lineEnding.WhitespacesAnalyzer::detectIndent($tokens, $position); $whitespaceToken = $tokens[$position - 1]; if (!$whitespaceToken->isGivenKind(\T_WHITESPACE)) { if ($whitespaceToken->isGivenKind(\T_OPEN_TAG)) { $content = Preg::replace('/\R/', '', $content); if (!Preg::match('/\R/', $whitespaceToken->getContent())) { $tokens[$position - 1] = new Token([\T_OPEN_TAG, Preg::replace('/\s+$/', $lineEnding, $whitespaceToken->getContent())]); } } if ('' !== $content) { $tokens->insertAt($position, new Token([\T_WHITESPACE, $content])); return $position; } return $position - 1; } if ($tokens[$position - 2]->isGivenKind(\T_OPEN_TAG) && Preg::match('/\R/', $tokens[$position - 2]->getContent())) { $content = Preg::replace('/^\R/', '', $content); } if (!Preg::match('/\R/', $whitespaceToken->getContent())) { $tokens[$position - 1] = new Token([\T_WHITESPACE, $content]); } return $position - 1; } private function removeComment(Tokens $tokens, int $commentPosition): void { if ($tokens[$tokens->getPrevNonWhitespace($commentPosition)]->isGivenKind(\T_OPEN_TAG)) { $whitespacePosition = $commentPosition + 1; $regex = '/^\R\h*/'; } else { $whitespacePosition = $commentPosition - 1; $regex = '/\R\h*$/'; } $whitespaceToken = $tokens[$whitespacePosition]; if ($whitespaceToken->isGivenKind(\T_WHITESPACE)) { $content = Preg::replace($regex, '', $whitespaceToken->getContent()); $tokens->ensureWhitespaceAtIndex($whitespacePosition, 0, $content); } $tokens->clearTokenAndMergeSurroundingWhitespace($commentPosition); } private function getStructureEnd(Tokens $tokens, int $position): int { $initialToken = $tokens[$position]; if ($initialToken->isGivenKind(self::STRUCTURE_KINDS)) { $position = $tokens->findBlockEnd( Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextTokenOfKind($position, ['(']), ); } elseif ($initialToken->isGivenKind(\T_CLASS)) { $openParenthesisPosition = $tokens->getNextMeaningfulToken($position); if ('(' === $tokens[$openParenthesisPosition]->getContent()) { $position = $tokens->findBlockEnd( Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesisPosition, ); } } if ($initialToken->isGivenKind(\T_FUNCTION)) { $position = $tokens->getNextTokenOfKind($position, ['{']); } else { $position = $tokens->getNextMeaningfulToken($position); } if ('{' !== $tokens[$position]->getContent()) { return $tokens->getNextTokenOfKind($position, [';']); } $position = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $position); if ($initialToken->isGivenKind(\T_DO)) { $position = $tokens->findBlockEnd( Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextTokenOfKind($position, ['(']), ); return $tokens->getNextTokenOfKind($position, [';']); } return $position; } }
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/ControlStructure/NoUnneededControlParenthesesFixer.php
src/Fixer/ControlStructure/NoUnneededControlParenthesesFixer.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\ControlStructure; 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\FCT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; use PhpCsFixer\Tokenizer\TokensAnalyzer; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * statements?: list<'break'|'clone'|'continue'|'echo_print'|'negative_instanceof'|'others'|'return'|'switch_case'|'yield'|'yield_from'>, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * statements: list<'break'|'clone'|'continue'|'echo_print'|'negative_instanceof'|'others'|'return'|'switch_case'|'yield'|'yield_from'>, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @phpstan-import-type _PhpTokenPrototypePartial from Token * * @author Sullivan Senechal <soullivaneuh@gmail.com> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * @author Gregor Harlan <gharlan@web.de> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NoUnneededControlParenthesesFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; /** * @var non-empty-list<int> */ private const BLOCK_TYPES = [ Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE, Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, Tokens::BLOCK_TYPE_CURLY_BRACE, Tokens::BLOCK_TYPE_DESTRUCTURING_SQUARE_BRACE, Tokens::BLOCK_TYPE_DYNAMIC_PROP_BRACE, Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE, Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, ]; private const BEFORE_TYPES = [ ';', '{', [\T_OPEN_TAG], [\T_OPEN_TAG_WITH_ECHO], [\T_ECHO], [\T_PRINT], [\T_RETURN], [\T_THROW], [\T_YIELD], [\T_YIELD_FROM], [\T_BREAK], [\T_CONTINUE], // won't be fixed, but true in concept, helpful for fast check [\T_REQUIRE], [\T_REQUIRE_ONCE], [\T_INCLUDE], [\T_INCLUDE_ONCE], ]; private const CONFIG_OPTIONS = [ 'break', 'clone', 'continue', 'echo_print', 'negative_instanceof', 'others', 'return', 'switch_case', 'yield', 'yield_from', ]; private const TOKEN_TYPE_CONFIG_MAP = [ \T_BREAK => 'break', \T_CASE => 'switch_case', \T_CONTINUE => 'continue', \T_ECHO => 'echo_print', \T_PRINT => 'echo_print', \T_RETURN => 'return', \T_YIELD => 'yield', \T_YIELD_FROM => 'yield_from', ]; // handled by the `include` rule private const TOKEN_TYPE_NO_CONFIG = [ \T_REQUIRE, \T_REQUIRE_ONCE, \T_INCLUDE, \T_INCLUDE_ONCE, ]; private const KNOWN_NEGATIVE_PRE_TYPES = [ [CT::T_CLASS_CONSTANT], [CT::T_DYNAMIC_VAR_BRACE_CLOSE], [CT::T_RETURN_REF], [CT::T_USE_LAMBDA], [\T_ARRAY], [\T_CATCH], [\T_CLASS], [\T_DECLARE], [\T_ELSEIF], [\T_EMPTY], [\T_EXIT], [\T_EVAL], [\T_FN], [\T_FOREACH], [\T_FOR], [\T_FUNCTION], [\T_HALT_COMPILER], [\T_IF], [\T_ISSET], [\T_LIST], [\T_STRING], [\T_SWITCH], [\T_STATIC], [\T_UNSET], [\T_VARIABLE], [\T_WHILE], // handled by the `include` rule [\T_REQUIRE], [\T_REQUIRE_ONCE], [\T_INCLUDE], [\T_INCLUDE_ONCE], [FCT::T_MATCH], ]; /** * @var list<_PhpTokenPrototypePartial> */ private array $noopTypes; private TokensAnalyzer $tokensAnalyzer; public function __construct() { parent::__construct(); $this->noopTypes = [ '$', [\T_CONSTANT_ENCAPSED_STRING], [\T_DNUMBER], [\T_DOUBLE_COLON], [\T_LNUMBER], [\T_NS_SEPARATOR], [\T_STRING], [\T_VARIABLE], [\T_STATIC], // magic constants [\T_CLASS_C], [\T_DIR], [\T_FILE], [\T_FUNC_C], [\T_LINE], [\T_METHOD_C], [\T_NS_C], [\T_TRAIT_C], ]; foreach (Token::getObjectOperatorKinds() as $kind) { $this->noopTypes[] = [$kind]; } } public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Removes unneeded parentheses around control statements.', [ new CodeSample( <<<'PHP' <?php while ($x) { while ($y) { break (2); } } clone($a); while ($y) { continue (2); } echo("foo"); print("foo"); return (1 + 2); switch ($a) { case($x); } yield(2); PHP, ), new CodeSample( <<<'PHP' <?php while ($x) { while ($y) { break (2); } } clone($a); while ($y) { continue (2); } PHP, ['statements' => ['break', 'continue']], ), ], ); } /** * {@inheritdoc} * * Must run before ConcatSpaceFixer, NewExpressionParenthesesFixer, NoTrailingWhitespaceFixer. * Must run after ModernizeTypesCastingFixer, NoAlternativeSyntaxFixer. */ public function getPriority(): int { return 30; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound(['(', CT::T_BRACE_CLASS_INSTANTIATION_OPEN]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $this->tokensAnalyzer = new TokensAnalyzer($tokens); foreach ($tokens as $openIndex => $token) { if ($token->equals('(')) { $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); } elseif ($token->isGivenKind(CT::T_BRACE_CLASS_INSTANTIATION_OPEN)) { $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE_CLASS_INSTANTIATION, $openIndex); } else { continue; } $beforeOpenIndex = $tokens->getPrevMeaningfulToken($openIndex); $afterCloseIndex = $tokens->getNextMeaningfulToken($closeIndex); // do a cheap check for negative case: `X()` if ($tokens->getNextMeaningfulToken($openIndex) === $closeIndex) { if ($tokens[$beforeOpenIndex]->isGivenKind(\T_EXIT)) { $this->removeUselessParenthesisPair($tokens, $beforeOpenIndex, $afterCloseIndex, $openIndex, $closeIndex, 'others'); } continue; } // do a cheap check for negative case: `foo(1,2)` if ($tokens[$beforeOpenIndex]->equalsAny(self::KNOWN_NEGATIVE_PRE_TYPES)) { continue; } // check for the simple useless wrapped cases if ($this->isUselessWrapped($tokens, $beforeOpenIndex, $afterCloseIndex)) { $this->removeUselessParenthesisPair($tokens, $beforeOpenIndex, $afterCloseIndex, $openIndex, $closeIndex, $this->getConfigType($tokens, $beforeOpenIndex)); continue; } // handle `clone` statements if ($tokens[$beforeOpenIndex]->isGivenKind(\T_CLONE)) { if ($this->isWrappedCloneArgument($tokens, $beforeOpenIndex, $openIndex, $closeIndex, $afterCloseIndex)) { $this->removeUselessParenthesisPair($tokens, $beforeOpenIndex, $afterCloseIndex, $openIndex, $closeIndex, 'clone'); } continue; } // handle `instance of` statements $instanceOfIndex = $this->getIndexOfInstanceOfStatement($tokens, $openIndex, $closeIndex); if (null !== $instanceOfIndex) { if ($this->isWrappedInstanceOf($tokens, $instanceOfIndex, $beforeOpenIndex, $openIndex, $closeIndex, $afterCloseIndex)) { $this->removeUselessParenthesisPair( $tokens, $beforeOpenIndex, $afterCloseIndex, $openIndex, $closeIndex, $tokens[$beforeOpenIndex]->equals('!') ? 'negative_instanceof' : 'others', ); } continue; } // last checks deal with operators, do not swap around if ($this->isWrappedPartOfOperation($tokens, $beforeOpenIndex, $openIndex, $closeIndex, $afterCloseIndex)) { $this->removeUselessParenthesisPair($tokens, $beforeOpenIndex, $afterCloseIndex, $openIndex, $closeIndex, $this->getConfigType($tokens, $beforeOpenIndex)); } } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { $defaults = array_filter( self::CONFIG_OPTIONS, static fn (string $option): bool => 'negative_instanceof' !== $option && 'others' !== $option && 'yield_from' !== $option, ); return new FixerConfigurationResolver([ (new FixerOptionBuilder('statements', 'List of control statements to fix.')) ->setAllowedTypes(['string[]']) ->setAllowedValues([new AllowedValueSubset(self::CONFIG_OPTIONS)]) ->setDefault(array_values($defaults)) ->getOption(), ]); } private function isUselessWrapped(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex): bool { return $this->isSingleStatement($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedFnBody($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedForElement($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedLanguageConstructArgument($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedSequenceElement($tokens, $beforeOpenIndex, $afterCloseIndex); } private function isWrappedCloneArgument(Tokens $tokens, int $beforeOpenIndex, int $openIndex, int $closeIndex, int $afterCloseIndex): bool { $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); if ( !( $tokens[$beforeOpenIndex]->equals('?') // For BC reasons || $this->isSimpleAssignment($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isSingleStatement($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedFnBody($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedForElement($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedSequenceElement($tokens, $beforeOpenIndex, $afterCloseIndex) ) ) { return false; } $newCandidateIndex = $tokens->getNextMeaningfulToken($openIndex); if ($tokens[$newCandidateIndex]->isGivenKind(\T_NEW)) { $openIndex = $newCandidateIndex; // `clone (new X)`, `clone (new X())`, clone (new X(Y))` } return !$this->containsOperation($tokens, $openIndex, $closeIndex); } private function getIndexOfInstanceOfStatement(Tokens $tokens, int $openIndex, int $closeIndex): ?int { $instanceOfIndex = $tokens->findGivenKind(\T_INSTANCEOF, $openIndex, $closeIndex); return 1 === \count($instanceOfIndex) ? array_key_first($instanceOfIndex) : null; } private function isWrappedInstanceOf(Tokens $tokens, int $instanceOfIndex, int $beforeOpenIndex, int $openIndex, int $closeIndex, int $afterCloseIndex): bool { if ( $this->containsOperation($tokens, $openIndex, $instanceOfIndex) || $this->containsOperation($tokens, $instanceOfIndex, $closeIndex) ) { return false; } if ($tokens[$beforeOpenIndex]->equals('!')) { $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); } return $this->isSimpleAssignment($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isSingleStatement($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedFnBody($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedForElement($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedSequenceElement($tokens, $beforeOpenIndex, $afterCloseIndex); } private function isWrappedPartOfOperation(Tokens $tokens, int $beforeOpenIndex, int $openIndex, int $closeIndex, int $afterCloseIndex): bool { if ($this->containsOperation($tokens, $openIndex, $closeIndex)) { return false; } $boundariesMoved = false; if ($this->isPreUnaryOperation($tokens, $beforeOpenIndex)) { $beforeOpenIndex = $this->getBeforePreUnaryOperation($tokens, $beforeOpenIndex); $boundariesMoved = true; } if ($this->isAccess($tokens, $afterCloseIndex)) { $afterCloseIndex = $this->getAfterAccess($tokens, $afterCloseIndex); $boundariesMoved = true; if ($this->tokensAnalyzer->isUnarySuccessorOperator($afterCloseIndex)) { // post unary operation are only valid here $afterCloseIndex = $tokens->getNextMeaningfulToken($afterCloseIndex); } } if ($boundariesMoved) { if ($tokens[$beforeOpenIndex]->equalsAny(self::KNOWN_NEGATIVE_PRE_TYPES)) { return false; } if ($this->isUselessWrapped($tokens, $beforeOpenIndex, $afterCloseIndex)) { return true; } } // check if part of some operation sequence $beforeIsBinaryOperation = $this->tokensAnalyzer->isBinaryOperator($beforeOpenIndex); $afterIsBinaryOperation = $this->tokensAnalyzer->isBinaryOperator($afterCloseIndex); if ($beforeIsBinaryOperation && $afterIsBinaryOperation) { return true; // `+ (x) +` } $beforeToken = $tokens[$beforeOpenIndex]; $afterToken = $tokens[$afterCloseIndex]; $beforeIsBlockOpenOrComma = $beforeToken->equals(',') || null !== $this->getBlock($tokens, $beforeOpenIndex, true); $afterIsBlockEndOrComma = $afterToken->equals(',') || null !== $this->getBlock($tokens, $afterCloseIndex, false); if (($beforeIsBlockOpenOrComma && $afterIsBinaryOperation) || ($beforeIsBinaryOperation && $afterIsBlockEndOrComma)) { // $beforeIsBlockOpenOrComma && $afterIsBlockEndOrComma is covered by `isWrappedSequenceElement` // `[ (x) +` or `+ (X) ]` or `, (X) +` or `+ (X) ,` return true; } if ($tokens[$beforeOpenIndex]->equals('}')) { $beforeIsStatementOpen = !$this->closeCurlyBelongsToDynamicElement($tokens, $beforeOpenIndex); } else { $beforeIsStatementOpen = $beforeToken->equalsAny(self::BEFORE_TYPES) || $beforeToken->isGivenKind(\T_CASE); } $afterIsStatementEnd = $afterToken->equalsAny([';', [\T_CLOSE_TAG]]); return ($beforeIsStatementOpen && $afterIsBinaryOperation) // `<?php (X) +` || ($beforeIsBinaryOperation && $afterIsStatementEnd); // `+ (X);` } // bounded `print|yield|yield from|require|require_once|include|include_once (X)` private function isWrappedLanguageConstructArgument(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex): bool { if (!$tokens[$beforeOpenIndex]->isGivenKind([\T_PRINT, \T_YIELD, \T_YIELD_FROM, \T_REQUIRE, \T_REQUIRE_ONCE, \T_INCLUDE, \T_INCLUDE_ONCE])) { return false; } $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); return $this->isWrappedSequenceElement($tokens, $beforeOpenIndex, $afterCloseIndex); } // any of `<?php|<?|<?=|;|throw|return|... (X) ;|T_CLOSE` private function isSingleStatement(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex): bool { if ($tokens[$beforeOpenIndex]->isGivenKind(\T_CASE)) { return $tokens[$afterCloseIndex]->equalsAny([':', ';']); // `switch case` } if (!$tokens[$afterCloseIndex]->equalsAny([';', [\T_CLOSE_TAG]])) { return false; } if ($tokens[$beforeOpenIndex]->equals('}')) { return !$this->closeCurlyBelongsToDynamicElement($tokens, $beforeOpenIndex); } return $tokens[$beforeOpenIndex]->equalsAny(self::BEFORE_TYPES); } private function isSimpleAssignment(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex): bool { return $tokens[$beforeOpenIndex]->equals('=') && $tokens[$afterCloseIndex]->equalsAny([';', [\T_CLOSE_TAG]]); // `= (X) ;` } private function isWrappedSequenceElement(Tokens $tokens, int $startIndex, int $endIndex): bool { $startIsComma = $tokens[$startIndex]->equals(','); $endIsComma = $tokens[$endIndex]->equals(','); if ($startIsComma && $endIsComma) { return true; // `,(X),` } $blockTypeStart = $this->getBlock($tokens, $startIndex, true); $blockTypeEnd = $this->getBlock($tokens, $endIndex, false); return ($startIsComma && null !== $blockTypeEnd) // `,(X)]` || ($endIsComma && null !== $blockTypeStart) // `[(X),` || (null !== $blockTypeEnd && null !== $blockTypeStart); // any type of `{(X)}`, `[(X)]` and `((X))` } // any of `for( (X); ;(X)) ;` note that the middle element is covered as 'single statement' as it is `; (X) ;` private function isWrappedForElement(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex): bool { $forCandidateIndex = null; if ($tokens[$beforeOpenIndex]->equals('(') && $tokens[$afterCloseIndex]->equals(';')) { $forCandidateIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); } elseif ($tokens[$afterCloseIndex]->equals(')') && $tokens[$beforeOpenIndex]->equals(';')) { $forCandidateIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $afterCloseIndex); $forCandidateIndex = $tokens->getPrevMeaningfulToken($forCandidateIndex); } return null !== $forCandidateIndex && $tokens[$forCandidateIndex]->isGivenKind(\T_FOR); } // `fn() => (X);` private function isWrappedFnBody(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex): bool { if (!$tokens[$beforeOpenIndex]->isGivenKind(\T_DOUBLE_ARROW)) { return false; } $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); if ($tokens[$beforeOpenIndex]->isGivenKind(\T_STRING)) { while (true) { $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); if (!$tokens[$beforeOpenIndex]->isGivenKind([\T_STRING, CT::T_TYPE_INTERSECTION, CT::T_TYPE_ALTERNATION])) { break; } } if (!$tokens[$beforeOpenIndex]->isGivenKind(CT::T_TYPE_COLON)) { return false; } $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); } if (!$tokens[$beforeOpenIndex]->equals(')')) { return false; } $beforeOpenIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $beforeOpenIndex); $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); if ($tokens[$beforeOpenIndex]->isGivenKind(CT::T_RETURN_REF)) { $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); } if (!$tokens[$beforeOpenIndex]->isGivenKind(\T_FN)) { return false; } return $tokens[$afterCloseIndex]->equalsAny([';', ',', [\T_CLOSE_TAG]]); } private function isPreUnaryOperation(Tokens $tokens, int $index): bool { return $this->tokensAnalyzer->isUnaryPredecessorOperator($index) || $tokens[$index]->isCast(); } private function getBeforePreUnaryOperation(Tokens $tokens, int $index): int { do { $index = $tokens->getPrevMeaningfulToken($index); } while ($this->isPreUnaryOperation($tokens, $index)); return $index; } // array access `(X)[` or `(X){` or object access `(X)->` or `(X)?->` private function isAccess(Tokens $tokens, int $index): bool { $token = $tokens[$index]; return $token->isObjectOperator() || $token->equals('[') || $token->isGivenKind(CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN); } private function getAfterAccess(Tokens $tokens, int $index): int { while (true) { $block = $this->getBlock($tokens, $index, true); if (null !== $block) { $index = $tokens->findBlockEnd($block['type'], $index); $index = $tokens->getNextMeaningfulToken($index); continue; } if ( $tokens[$index]->isObjectOperator() || $tokens[$index]->equalsAny(['$', [\T_PAAMAYIM_NEKUDOTAYIM], [\T_STRING], [\T_VARIABLE]]) ) { $index = $tokens->getNextMeaningfulToken($index); continue; } break; } return $index; } /** * @return null|array{type: Tokens::BLOCK_TYPE_*, isStart: bool} */ private function getBlock(Tokens $tokens, int $index, bool $isStart): ?array { $block = Tokens::detectBlockType($tokens[$index]); return null !== $block && $isStart === $block['isStart'] && \in_array($block['type'], self::BLOCK_TYPES, true) ? $block : null; } private function containsOperation(Tokens $tokens, int $startIndex, int $endIndex): bool { while (true) { $startIndex = $tokens->getNextMeaningfulToken($startIndex); if ($startIndex === $endIndex) { break; } $block = Tokens::detectBlockType($tokens[$startIndex]); if (null !== $block && $block['isStart']) { $startIndex = $tokens->findBlockEnd($block['type'], $startIndex); continue; } if (!$tokens[$startIndex]->equalsAny($this->noopTypes)) { return true; } } return false; } private function getConfigType(Tokens $tokens, int $beforeOpenIndex): ?string { if ($tokens[$beforeOpenIndex]->isGivenKind(self::TOKEN_TYPE_NO_CONFIG)) { return null; } foreach (self::TOKEN_TYPE_CONFIG_MAP as $type => $configItem) { if ($tokens[$beforeOpenIndex]->isGivenKind($type)) { return $configItem; } } return 'others'; } private function removeUselessParenthesisPair( Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex, int $openIndex, int $closeIndex, ?string $configType ): void { $statements = $this->configuration['statements']; if (null === $configType || !\in_array($configType, $statements, true)) { return; } $needsSpaceAfter = !$this->isAccess($tokens, $afterCloseIndex) && !$tokens[$afterCloseIndex]->equalsAny([';', ',', [\T_CLOSE_TAG]]) && null === $this->getBlock($tokens, $afterCloseIndex, false) && !($tokens[$afterCloseIndex]->equalsAny([':', ';']) && $tokens[$beforeOpenIndex]->isGivenKind(\T_CASE)); $needsSpaceBefore = !$this->isPreUnaryOperation($tokens, $beforeOpenIndex) && !$tokens[$beforeOpenIndex]->equalsAny(['}', [\T_EXIT], [\T_OPEN_TAG]]) && null === $this->getBlock($tokens, $beforeOpenIndex, true); $this->removeBrace($tokens, $closeIndex, $needsSpaceAfter); $this->removeBrace($tokens, $openIndex, $needsSpaceBefore); } private function removeBrace(Tokens $tokens, int $index, bool $needsSpace): void { if ($needsSpace) { foreach ([-1, 1] as $direction) { $siblingIndex = $tokens->getNonEmptySibling($index, $direction); if ($tokens[$siblingIndex]->isWhitespace() || $tokens[$siblingIndex]->isComment()) { $needsSpace = false; break; } } } if ($needsSpace) { $tokens[$index] = new Token([\T_WHITESPACE, ' ']); } else { $tokens->clearTokenAndMergeSurroundingWhitespace($index); } } private function closeCurlyBelongsToDynamicElement(Tokens $tokens, int $beforeOpenIndex): bool { $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $beforeOpenIndex); $index = $tokens->getPrevMeaningfulToken($index); if ($tokens[$index]->isGivenKind(\T_DOUBLE_COLON)) { return true; } if ($tokens[$index]->equals(':')) { $index = $tokens->getPrevTokenOfKind($index, [[\T_CASE], '?']); return !$tokens[$index]->isGivenKind(\T_CASE); } 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/ControlStructure/EmptyLoopBodyFixer.php
src/Fixer/ControlStructure/EmptyLoopBodyFixer.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\ControlStructure; 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; use PhpCsFixer\Tokenizer\TokensAnalyzer; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * style?: 'braces'|'semicolon', * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * style: 'braces'|'semicolon', * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class EmptyLoopBodyFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; private const STYLE_BRACES = 'braces'; private const STYLE_SEMICOLON = 'semicolon'; private const TOKEN_LOOP_KINDS = [\T_FOR, \T_FOREACH, \T_WHILE]; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Empty loop-body must be in configured style.', [ new CodeSample("<?php while(foo()){}\n"), new CodeSample( "<?php while(foo());\n", [ 'style' => self::STYLE_BRACES, ], ), ], ); } /** * {@inheritdoc} * * Must run before BracesFixer, NoExtraBlankLinesFixer, NoTrailingWhitespaceFixer. * Must run after NoEmptyStatementFixer. */ public function getPriority(): int { return 39; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound(self::TOKEN_LOOP_KINDS); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { if (self::STYLE_BRACES === $this->configuration['style']) { $analyzer = new TokensAnalyzer($tokens); $fixLoop = static function (int $index, int $endIndex) use ($tokens, $analyzer): void { if ($tokens[$index]->isGivenKind(\T_WHILE) && $analyzer->isWhilePartOfDoWhile($index)) { return; } $semiColonIndex = $tokens->getNextMeaningfulToken($endIndex); if (!$tokens[$semiColonIndex]->equals(';')) { return; } $tokens[$semiColonIndex] = new Token('{'); $tokens->insertAt($semiColonIndex + 1, new Token('}')); }; } else { $fixLoop = static function (int $index, int $endIndex) use ($tokens): void { $braceOpenIndex = $tokens->getNextMeaningfulToken($endIndex); if (!$tokens[$braceOpenIndex]->equals('{')) { return; } $braceCloseIndex = $tokens->getNextNonWhitespace($braceOpenIndex); if (!$tokens[$braceCloseIndex]->equals('}')) { return; } $tokens[$braceOpenIndex] = new Token(';'); $tokens->clearTokenAndMergeSurroundingWhitespace($braceCloseIndex); }; } for ($index = $tokens->count() - 1; $index > 0; --$index) { if ($tokens[$index]->isGivenKind(self::TOKEN_LOOP_KINDS)) { $endIndex = $tokens->getNextTokenOfKind($index, ['(']); // proceed to open '(' $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $endIndex); // proceed to close ')' $fixLoop($index, $endIndex); // fix loop if needs fixing } } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('style', 'Style of empty loop-bodies.')) ->setAllowedTypes(['string']) ->setAllowedValues([self::STYLE_BRACES, self::STYLE_SEMICOLON]) ->setDefault(self::STYLE_SEMICOLON) ->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/ControlStructure/ElseifFixer.php
src/Fixer/ControlStructure/ElseifFixer.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\ControlStructure; 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 ¶5.1. * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ElseifFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'The keyword `elseif` should be used instead of `else if` so that all control keywords look like single words.', [new CodeSample("<?php\nif (\$a) {\n} else if (\$b) {\n}\n")], ); } /** * {@inheritdoc} * * Must run after NoAlternativeSyntaxFixer. */ public function getPriority(): int { return 40; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAllTokenKindsFound([\T_IF, \T_ELSE]); } /** * Replace all `else if` (T_ELSE T_IF) with `elseif` (T_ELSEIF). * * {@inheritdoc} */ protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(\T_ELSE)) { continue; } $ifTokenIndex = $tokens->getNextMeaningfulToken($index); // if next meaningful token is not T_IF - continue searching, this is not the case for fixing if (!$tokens[$ifTokenIndex]->isGivenKind(\T_IF)) { continue; } // if next meaningful token is T_IF, but uses an alternative syntax - this is not the case for fixing neither $conditionEndBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextMeaningfulToken($ifTokenIndex)); $afterConditionIndex = $tokens->getNextMeaningfulToken($conditionEndBraceIndex); if ($tokens[$afterConditionIndex]->equals(':')) { continue; } // now we have T_ELSE following by T_IF with no alternative syntax so we could fix this // 1. clear whitespaces between T_ELSE and T_IF $tokens->clearAt($index + 1); // 2. change token from T_ELSE into T_ELSEIF $tokens[$index] = new Token([\T_ELSEIF, 'elseif']); // 3. clear succeeding T_IF $tokens->clearAt($ifTokenIndex); $beforeIfTokenIndex = $tokens->getPrevNonWhitespace($ifTokenIndex); // 4. clear extra whitespace after T_IF in T_COMMENT,T_WHITESPACE?,T_IF,T_WHITESPACE sequence if ($tokens[$beforeIfTokenIndex]->isComment() && $tokens[$ifTokenIndex + 1]->isWhitespace()) { $tokens->clearAt($ifTokenIndex + 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/ControlStructure/SwitchCaseSemicolonToColonFixer.php
src/Fixer/ControlStructure/SwitchCaseSemicolonToColonFixer.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\ControlStructure; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis; use PhpCsFixer\Tokenizer\Analyzer\ControlCaseStructuresAnalyzer; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Fixer for rules defined in PSR2 ¶5.2. * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class SwitchCaseSemicolonToColonFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'A case should be followed by a colon and not a semicolon.', [ new CodeSample( <<<'PHP' <?php switch ($a) { case 1; break; default; break; } PHP, ), ], ); } /** * {@inheritdoc} * * Must run after NoEmptyStatementFixer. */ public function getPriority(): int { return 0; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_SWITCH); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { /** @var SwitchAnalysis $analysis */ foreach (ControlCaseStructuresAnalyzer::findControlStructures($tokens, [\T_SWITCH]) as $analysis) { $default = $analysis->getDefaultAnalysis(); if (null !== $default) { $this->fixTokenIfNeeded($tokens, $default->getColonIndex()); } foreach ($analysis->getCases() as $caseAnalysis) { $this->fixTokenIfNeeded($tokens, $caseAnalysis->getColonIndex()); } } } private function fixTokenIfNeeded(Tokens $tokens, int $index): void { if ($tokens[$index]->equals(';')) { $tokens[$index] = 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/ControlStructure/IncludeFixer.php
src/Fixer/ControlStructure/IncludeFixer.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\ControlStructure; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Analyzer\BlocksAnalyzer; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @author Sebastiaan Stok <s.stok@rollerscapes.net> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * @author Kuba Werłos <werlos@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class IncludeFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Include/Require and file path should be divided with a single space. File path should not be placed within parentheses.', [ new CodeSample( <<<'PHP' <?php require ("sample1.php"); require_once "sample2.php"; include "sample3.php"; include_once("sample4.php"); PHP, ), ], ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound([\T_REQUIRE, \T_REQUIRE_ONCE, \T_INCLUDE, \T_INCLUDE_ONCE]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $this->clearIncludies($tokens, $this->findIncludies($tokens)); } /** * @param array<int, array{begin: int, braces: ?array{open: int, close: int}, end: int}> $includies */ private function clearIncludies(Tokens $tokens, array $includies): void { $blocksAnalyzer = new BlocksAnalyzer(); foreach ($includies as $includy) { if (!$tokens[$includy['end']]->isGivenKind(\T_CLOSE_TAG)) { $afterEndIndex = $tokens->getNextNonWhitespace($includy['end']); if (null === $afterEndIndex || !$tokens[$afterEndIndex]->isComment()) { $tokens->removeLeadingWhitespace($includy['end']); } } $braces = $includy['braces']; if (null !== $braces) { $prevIndex = $tokens->getPrevMeaningfulToken($includy['begin']); $nextIndex = $tokens->getNextMeaningfulToken($braces['close']); // Include is also legal as function parameter or condition statement but requires being wrapped then. if (!$tokens[$nextIndex]->equalsAny([';', [\T_CLOSE_TAG]]) && !$blocksAnalyzer->isBlock($tokens, $prevIndex, $nextIndex)) { continue; } $this->removeWhitespaceAroundIfPossible($tokens, $braces['open']); $this->removeWhitespaceAroundIfPossible($tokens, $braces['close']); $tokens->clearTokenAndMergeSurroundingWhitespace($braces['open']); $tokens->clearTokenAndMergeSurroundingWhitespace($braces['close']); } $nextIndex = $tokens->getNonEmptySibling($includy['begin'], 1); if ($tokens[$nextIndex]->isWhitespace()) { $tokens[$nextIndex] = new Token([\T_WHITESPACE, ' ']); } elseif (null !== $braces || $tokens[$nextIndex]->isGivenKind([\T_VARIABLE, \T_CONSTANT_ENCAPSED_STRING, \T_COMMENT])) { $tokens->insertAt($includy['begin'] + 1, new Token([\T_WHITESPACE, ' '])); } } } /** * @return array<int, array{begin: int, braces: ?array{open: int, close: int}, end: int}> */ private function findIncludies(Tokens $tokens): array { $includies = []; foreach ($tokens->findGivenKind([\T_REQUIRE, \T_REQUIRE_ONCE, \T_INCLUDE, \T_INCLUDE_ONCE]) as $includyTokens) { foreach ($includyTokens as $index => $token) { $includy = [ 'begin' => $index, 'braces' => null, 'end' => $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]), ]; $braceOpenIndex = $tokens->getNextMeaningfulToken($index); if ($tokens[$braceOpenIndex]->equals('(')) { $braceCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $braceOpenIndex); $includy['braces'] = [ 'open' => $braceOpenIndex, 'close' => $braceCloseIndex, ]; } $includies[$index] = $includy; } } krsort($includies); return $includies; } private function removeWhitespaceAroundIfPossible(Tokens $tokens, int $index): void { $nextIndex = $tokens->getNextNonWhitespace($index); if (null === $nextIndex || !$tokens[$nextIndex]->isComment()) { $tokens->removeLeadingWhitespace($index); } $prevIndex = $tokens->getPrevNonWhitespace($index); if (null === $prevIndex || !$tokens[$prevIndex]->isComment()) { $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/ControlStructure/SwitchContinueToBreakFixer.php
src/Fixer/ControlStructure/SwitchContinueToBreakFixer.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\ControlStructure; 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 SwitchContinueToBreakFixer extends AbstractFixer { /** * @var list<int> */ private array $switchLevels = []; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Switch case must not be ended with `continue` but with `break`.', [ new CodeSample( <<<'PHP' <?php switch ($foo) { case 1: continue; } PHP, ), new CodeSample( <<<'PHP' <?php switch ($foo) { case 1: while($bar) { do { continue 3; } while(false); if ($foo + 1 > 3) { continue; } continue 2; } } PHP, ), ], ); } /** * {@inheritdoc} * * Must run after NoAlternativeSyntaxFixer. */ public function getPriority(): int { return 0; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAllTokenKindsFound([\T_SWITCH, \T_CONTINUE]) && !$tokens->hasAlternativeSyntax(); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $count = \count($tokens); for ($index = 1; $index < $count - 1; ++$index) { $index = $this->doFix($tokens, $index, 0, false); } } /** * @param int $depth >= 0 */ private function doFix(Tokens $tokens, int $index, int $depth, bool $isInSwitch): int { $token = $tokens[$index]; if ($token->isGivenKind([\T_FOREACH, \T_FOR, \T_WHILE])) { // go to first `(`, go to its close ')', go to first of '{', ';', '? >' $index = $tokens->getNextTokenOfKind($index, ['(']); $index = $tokens->getNextTokenOfKind($index, [')']); $index = $tokens->getNextTokenOfKind($index, ['{', ';', [\T_CLOSE_TAG]]); if (!$tokens[$index]->equals('{')) { return $index; } return $this->fixInLoop($tokens, $index, $depth + 1); } if ($token->isGivenKind(\T_DO)) { return $this->fixInLoop($tokens, $tokens->getNextTokenOfKind($index, ['{']), $depth + 1); } if ($token->isGivenKind(\T_SWITCH)) { return $this->fixInSwitch($tokens, $index, $depth + 1); } if ($token->isGivenKind(\T_CONTINUE)) { return $this->fixContinueWhenActsAsBreak($tokens, $index, $isInSwitch, $depth); } return $index; } private function fixInSwitch(Tokens $tokens, int $switchIndex, int $depth): int { $this->switchLevels[] = $depth; // figure out where the switch starts $openIndex = $tokens->getNextTokenOfKind($switchIndex, ['{']); // figure out where the switch ends $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openIndex); for ($index = $openIndex + 1; $index < $closeIndex; ++$index) { $index = $this->doFix($tokens, $index, $depth, true); } array_pop($this->switchLevels); return $closeIndex; } private function fixInLoop(Tokens $tokens, int $openIndex, int $depth): int { $openCount = 1; while (true) { ++$openIndex; $token = $tokens[$openIndex]; if ($token->equals('{')) { ++$openCount; continue; } if ($token->equals('}')) { --$openCount; if (0 === $openCount) { break; } continue; } $openIndex = $this->doFix($tokens, $openIndex, $depth, false); } return $openIndex; } private function fixContinueWhenActsAsBreak(Tokens $tokens, int $continueIndex, bool $isInSwitch, int $depth): int { $followingContinueIndex = $tokens->getNextMeaningfulToken($continueIndex); $followingContinueToken = $tokens[$followingContinueIndex]; if ($isInSwitch && $followingContinueToken->equals(';')) { $this->replaceContinueWithBreakToken($tokens, $continueIndex); // short continue 1 notation return $followingContinueIndex; } if (!$followingContinueToken->isGivenKind(\T_LNUMBER)) { return $followingContinueIndex; } $afterFollowingContinueIndex = $tokens->getNextMeaningfulToken($followingContinueIndex); if (!$tokens[$afterFollowingContinueIndex]->equals(';')) { return $afterFollowingContinueIndex; // if next not is `;` return without fixing, for example `continue 1 ? ><?php + $a;` } // check if continue {jump} targets a switch statement and if so fix it $jump = $followingContinueToken->getContent(); $jump = str_replace('_', '', $jump); // support for numeric_literal_separator if (\strlen($jump) > 2 && 'x' === $jump[1]) { $jump = hexdec($jump); // hexadecimal - 0x1 } elseif (\strlen($jump) > 2 && 'b' === $jump[1]) { $jump = bindec($jump); // binary - 0b1 } elseif (\strlen($jump) > 1 && '0' === $jump[0]) { $jump = octdec($jump); // octal 01 } elseif (Preg::match('#^\d+$#', $jump)) { // positive int $jump = (float) $jump; // cast to float, might be a number bigger than PHP max. int value } else { return $afterFollowingContinueIndex; // cannot process value, ignore } if ($jump > \PHP_INT_MAX) { return $afterFollowingContinueIndex; // cannot process value, ignore } $jump = (int) $jump; if ($isInSwitch && (1 === $jump || 0 === $jump)) { $this->replaceContinueWithBreakToken($tokens, $continueIndex); // long continue 0/1 notation return $afterFollowingContinueIndex; } $jumpDestination = $depth - $jump + 1; if (\in_array($jumpDestination, $this->switchLevels, true)) { $this->replaceContinueWithBreakToken($tokens, $continueIndex); return $afterFollowingContinueIndex; } return $afterFollowingContinueIndex; } private function replaceContinueWithBreakToken(Tokens $tokens, int $index): void { $tokens[$index] = new Token([\T_BREAK, '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/ControlStructure/SwitchCaseSpaceFixer.php
src/Fixer/ControlStructure/SwitchCaseSpaceFixer.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\ControlStructure; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis; use PhpCsFixer\Tokenizer\Analyzer\ControlCaseStructuresAnalyzer; use PhpCsFixer\Tokenizer\Tokens; /** * Fixer for rules defined in PSR2 ¶5.2. * * @author Sullivan Senechal <soullivaneuh@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class SwitchCaseSpaceFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Removes extra spaces between colon and case value.', [ new CodeSample( <<<'PHP' <?php switch($a) { case 1 : break; default : return 2; } PHP, ), ], ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_SWITCH); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { /** @var SwitchAnalysis $analysis */ foreach (ControlCaseStructuresAnalyzer::findControlStructures($tokens, [\T_SWITCH]) as $analysis) { $default = $analysis->getDefaultAnalysis(); if (null !== $default) { $index = $default->getIndex(); if (!$tokens[$index + 1]->isWhitespace() || !$tokens[$index + 2]->equalsAny([':', ';'])) { continue; } $tokens->clearAt($index + 1); } foreach ($analysis->getCases() as $caseAnalysis) { $colonIndex = $caseAnalysis->getColonIndex(); $valueIndex = $tokens->getPrevNonWhitespace($colonIndex); // skip if there is no space between the colon and previous token or is space after comment if ($valueIndex === $colonIndex - 1 || $tokens[$valueIndex]->isComment()) { continue; } $tokens->clearAt($valueIndex + 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/ControlStructure/NoUselessElseFixer.php
src/Fixer/ControlStructure/NoUselessElseFixer.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\ControlStructure; use PhpCsFixer\AbstractNoUselessElseFixer; 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 NoUselessElseFixer extends AbstractNoUselessElseFixer { public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_ELSE); } public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'There should not be useless `else` cases.', [ new CodeSample("<?php\nif (\$a) {\n return 1;\n} else {\n return 2;\n}\n"), ], ); } /** * {@inheritdoc} * * Must run before BlankLineBeforeStatementFixer, BracesFixer, CombineConsecutiveUnsetsFixer, NoBreakCommentFixer, NoExtraBlankLinesFixer, NoTrailingWhitespaceFixer, NoUselessReturnFixer, NoWhitespaceInBlankLineFixer, SimplifiedIfReturnFixer, StatementIndentationFixer. * Must run after NoAlternativeSyntaxFixer, NoEmptyStatementFixer, NoUnneededBracesFixer, NoUnneededCurlyBracesFixer. */ public function getPriority(): int { return parent::getPriority(); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(\T_ELSE)) { continue; } // `else if` vs. `else` and alternative syntax `else:` checks if ($tokens[$tokens->getNextMeaningfulToken($index)]->equalsAny([':', [\T_IF]])) { continue; } // clean up `else` if it is an empty statement $this->fixEmptyElse($tokens, $index); if ($tokens->isEmptyAt($index)) { continue; } // clean up `else` if possible if ($this->isSuperfluousElse($tokens, $index)) { $this->clearElse($tokens, $index); } } } /** * Remove tokens part of an `else` statement if not empty (i.e. no meaningful tokens inside). * * @param int $index T_ELSE index */ private function fixEmptyElse(Tokens $tokens, int $index): void { $next = $tokens->getNextMeaningfulToken($index); if ($tokens[$next]->equals('{')) { $close = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $next); if (1 === $close - $next) { // '{}' $this->clearElse($tokens, $index); } elseif ($tokens->getNextMeaningfulToken($next) === $close) { // '{/**/}' $this->clearElse($tokens, $index); } return; } // short `else` $end = $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]); if ($next === $end) { $this->clearElse($tokens, $index); } } /** * @param int $index index of T_ELSE */ private function clearElse(Tokens $tokens, int $index): void { $tokens->clearTokenAndMergeSurroundingWhitespace($index); // clear T_ELSE and the '{' '}' if there are any $next = $tokens->getNextMeaningfulToken($index); if (!$tokens[$next]->equals('{')) { return; } $tokens->clearTokenAndMergeSurroundingWhitespace($tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $next)); $tokens->clearTokenAndMergeSurroundingWhitespace($next); } }
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/ControlStructure/NoAlternativeSyntaxFixer.php
src/Fixer/ControlStructure/NoAlternativeSyntaxFixer.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\ControlStructure; 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\Future; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * fix_non_monolithic_code?: bool, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * fix_non_monolithic_code: bool, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @author Eddilbert Macharia <edd.cowan@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NoAlternativeSyntaxFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Replace control structure alternative syntax to use braces.', [ new CodeSample( "<?php\nif(true):echo 't';else:echo 'f';endif;\n", ), new CodeSample( "<?php if (\$condition): ?>\nLorem ipsum.\n<?php endif; ?>\n", ['fix_non_monolithic_code' => true], ), ], ); } public function isCandidate(Tokens $tokens): bool { return $tokens->hasAlternativeSyntax() && (true === $this->configuration['fix_non_monolithic_code'] || $tokens->isMonolithicPhp()); } /** * {@inheritdoc} * * Must run before BracesFixer, ElseifFixer, NoSuperfluousElseifFixer, NoUnneededControlParenthesesFixer, NoUselessElseFixer, SwitchContinueToBreakFixer. */ public function getPriority(): int { return 42; } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('fix_non_monolithic_code', 'Whether to also fix code with inline HTML.')) ->setAllowedTypes(['bool']) ->setDefault(Future::getV4OrV3(false, true)) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { for ($index = \count($tokens) - 1; 0 <= $index; --$index) { $token = $tokens[$index]; $this->fixElseif($index, $token, $tokens); $this->fixElse($index, $token, $tokens); $this->fixOpenCloseControls($index, $token, $tokens); } } private function findParenthesisEnd(Tokens $tokens, int $structureTokenIndex): int { $nextIndex = $tokens->getNextMeaningfulToken($structureTokenIndex); $nextToken = $tokens[$nextIndex]; return $nextToken->equals('(') ? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex) : $structureTokenIndex; // return if next token is not opening parenthesis } /** * Handle both extremes of the control structures. * e.g. if(): or endif;. * * @param int $index the index of the token being processed * @param Token $token the token being processed * @param Tokens $tokens the collection of tokens */ private function fixOpenCloseControls(int $index, Token $token, Tokens $tokens): void { if ($token->isGivenKind([\T_IF, \T_FOREACH, \T_WHILE, \T_FOR, \T_SWITCH, \T_DECLARE])) { $openIndex = $tokens->getNextTokenOfKind($index, ['(']); $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); $afterParenthesisIndex = $tokens->getNextMeaningfulToken($closeIndex); $afterParenthesis = $tokens[$afterParenthesisIndex]; if (!$afterParenthesis->equals(':')) { return; } $items = []; if (!$tokens[$afterParenthesisIndex - 1]->isWhitespace()) { $items[] = new Token([\T_WHITESPACE, ' ']); } $items[] = new Token('{'); if (!$tokens[$afterParenthesisIndex + 1]->isWhitespace()) { $items[] = new Token([\T_WHITESPACE, ' ']); } $tokens->clearAt($afterParenthesisIndex); $tokens->insertAt($afterParenthesisIndex, $items); } if (!$token->isGivenKind([\T_ENDIF, \T_ENDFOREACH, \T_ENDWHILE, \T_ENDFOR, \T_ENDSWITCH, \T_ENDDECLARE])) { return; } $nextTokenIndex = $tokens->getNextMeaningfulToken($index); $nextToken = $tokens[$nextTokenIndex]; $tokens[$index] = new Token('}'); if ($nextToken->equals(';')) { $tokens->clearAt($nextTokenIndex); } } /** * Handle the else: cases. * * @param int $index the index of the token being processed * @param Token $token the token being processed * @param Tokens $tokens the collection of tokens */ private function fixElse(int $index, Token $token, Tokens $tokens): void { if (!$token->isGivenKind(\T_ELSE)) { return; } $tokenAfterElseIndex = $tokens->getNextMeaningfulToken($index); $tokenAfterElse = $tokens[$tokenAfterElseIndex]; if (!$tokenAfterElse->equals(':')) { return; } $this->addBraces($tokens, new Token([\T_ELSE, 'else']), $index, $tokenAfterElseIndex); } /** * Handle the elsif(): cases. * * @param int $index the index of the token being processed * @param Token $token the token being processed * @param Tokens $tokens the collection of tokens */ private function fixElseif(int $index, Token $token, Tokens $tokens): void { if (!$token->isGivenKind(\T_ELSEIF)) { return; } $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index); $tokenAfterParenthesisIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); $tokenAfterParenthesis = $tokens[$tokenAfterParenthesisIndex]; if (!$tokenAfterParenthesis->equals(':')) { return; } $this->addBraces($tokens, new Token([\T_ELSEIF, 'elseif']), $index, $tokenAfterParenthesisIndex); } /** * Add opening and closing braces to the else: and elseif: cases. * * @param Tokens $tokens the tokens collection * @param Token $token the current token * @param int $index the current token index * @param int $colonIndex the index of the colon */ private function addBraces(Tokens $tokens, Token $token, int $index, int $colonIndex): void { $items = [ new Token('}'), new Token([\T_WHITESPACE, ' ']), $token, ]; if (!$tokens[$index + 1]->isWhitespace()) { $items[] = new Token([\T_WHITESPACE, ' ']); } $tokens->clearAt($index); $tokens->insertAt( $index, $items, ); // increment the position of the colon by number of items inserted $colonIndex += \count($items); $items = [new Token('{')]; if (!$tokens[$colonIndex + 1]->isWhitespace()) { $items[] = new Token([\T_WHITESPACE, ' ']); } $tokens->clearAt($colonIndex); $tokens->insertAt( $colonIndex, $items, ); } }
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/ControlStructure/ControlStructureContinuationPositionFixer.php
src/Fixer/ControlStructure/ControlStructureContinuationPositionFixer.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\ControlStructure; 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\Tokens; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * position?: 'next_line'|'same_line', * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * position: 'next_line'|'same_line', * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ControlStructureContinuationPositionFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; /** * @internal */ public const NEXT_LINE = 'next_line'; /** * @internal */ public const SAME_LINE = 'same_line'; private const CONTROL_CONTINUATION_TOKENS = [ \T_CATCH, \T_ELSE, \T_ELSEIF, \T_FINALLY, \T_WHILE, ]; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Control structure continuation keyword must be on the configured line.', [ new CodeSample( <<<'PHP' <?php if ($baz == true) { echo "foo"; } else { echo "bar"; } PHP, ), new CodeSample( <<<'PHP' <?php if ($baz == true) { echo "foo"; } else { echo "bar"; } PHP, ['position' => self::NEXT_LINE], ), ], ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound(self::CONTROL_CONTINUATION_TOKENS); } /** * {@inheritdoc} * * Must run after ControlStructureBracesFixer. */ public function getPriority(): int { return parent::getPriority(); } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('position', 'The position of the keyword that continues the control structure.')) ->setAllowedValues([self::NEXT_LINE, self::SAME_LINE]) ->setDefault(self::SAME_LINE) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $this->fixControlContinuationBraces($tokens); } private function fixControlContinuationBraces(Tokens $tokens): void { for ($index = \count($tokens) - 1; 0 < $index; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind(self::CONTROL_CONTINUATION_TOKENS)) { continue; } $prevIndex = $tokens->getPrevNonWhitespace($index); $prevToken = $tokens[$prevIndex]; if (!$prevToken->equals('}')) { continue; } if ($token->isGivenKind(\T_WHILE)) { $prevIndex = $tokens->getPrevMeaningfulToken( $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $prevIndex), ); if (!$tokens[$prevIndex]->isGivenKind(\T_DO)) { continue; } } $tokens->ensureWhitespaceAtIndex( $index - 1, 1, self::NEXT_LINE === $this->configuration['position'] ? $this->whitespacesConfig->getLineEnding().WhitespacesAnalyzer::detectIndent($tokens, $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/ControlStructure/SimplifiedIfReturnFixer.php
src/Fixer/ControlStructure/SimplifiedIfReturnFixer.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\ControlStructure; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @phpstan-import-type _PhpTokenPrototypePartial from Token * * @author Filippo Tessarotto <zoeslam@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class SimplifiedIfReturnFixer extends AbstractFixer { /** * @var list<array{isNegative: bool, sequence: non-empty-list<_PhpTokenPrototypePartial>}> */ private array $sequences = [ [ 'isNegative' => false, 'sequence' => [ '{', [\T_RETURN], [\T_STRING, 'true'], ';', '}', [\T_RETURN], [\T_STRING, 'false'], ';', ], ], [ 'isNegative' => true, 'sequence' => [ '{', [\T_RETURN], [\T_STRING, 'false'], ';', '}', [\T_RETURN], [\T_STRING, 'true'], ';', ], ], [ 'isNegative' => false, 'sequence' => [ [\T_RETURN], [\T_STRING, 'true'], ';', [\T_RETURN], [\T_STRING, 'false'], ';', ], ], [ 'isNegative' => true, 'sequence' => [ [\T_RETURN], [\T_STRING, 'false'], ';', [\T_RETURN], [\T_STRING, 'true'], ';', ], ], ]; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Simplify `if` control structures that return the boolean result of their condition.', [new CodeSample("<?php\nif (\$foo) { return true; } return false;\n")], ); } /** * {@inheritdoc} * * Must run before MultilineWhitespaceBeforeSemicolonsFixer, NoSinglelineWhitespaceBeforeSemicolonsFixer. * Must run after NoSuperfluousElseifFixer, NoUnneededBracesFixer, NoUnneededCurlyBracesFixer, NoUselessElseFixer, SemicolonAfterInstructionFixer. */ public function getPriority(): int { return 1; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAllTokenKindsFound([\T_IF, \T_RETURN, \T_STRING]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { for ($ifIndex = $tokens->count() - 1; 0 <= $ifIndex; --$ifIndex) { if (!$tokens[$ifIndex]->isGivenKind([\T_IF, \T_ELSEIF])) { continue; } if ($tokens[$tokens->getPrevMeaningfulToken($ifIndex)]->equals(')')) { continue; // in a loop without braces } $startParenthesisIndex = $tokens->getNextTokenOfKind($ifIndex, ['(']); $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex); $firstCandidateIndex = $tokens->getNextMeaningfulToken($endParenthesisIndex); foreach ($this->sequences as $sequenceSpec) { $sequenceFound = $tokens->findSequence($sequenceSpec['sequence'], $firstCandidateIndex); if (null === $sequenceFound) { continue; } $firstSequenceIndex = array_key_first($sequenceFound); if ($firstSequenceIndex !== $firstCandidateIndex) { continue; } $indicesToClear = array_keys($sequenceFound); array_pop($indicesToClear); // Preserve last semicolon rsort($indicesToClear); foreach ($indicesToClear as $index) { $tokens->clearTokenAndMergeSurroundingWhitespace($index); } $newTokens = [ new Token([\T_RETURN, 'return']), new Token([\T_WHITESPACE, ' ']), ]; if ($sequenceSpec['isNegative']) { $newTokens[] = new Token('!'); } else { $newTokens[] = new Token([\T_BOOL_CAST, '(bool)']); } $tokens->overrideRange($ifIndex, $ifIndex, $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/ControlStructure/ControlStructureBracesFixer.php
src/Fixer/ControlStructure/ControlStructureBracesFixer.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\ControlStructure; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ControlStructureBracesFixer extends AbstractFixer { private const CONTROL_TOKENS = [ \T_DECLARE, \T_DO, \T_ELSE, \T_ELSEIF, \T_FINALLY, \T_FOR, \T_FOREACH, \T_IF, \T_WHILE, \T_TRY, \T_CATCH, \T_SWITCH, ]; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'The body of each control structure MUST be enclosed within braces.', [new CodeSample("<?php\nif (foo()) echo 'Hello!';\n")], ); } public function isCandidate(Tokens $tokens): bool { return true; } /** * {@inheritdoc} * * Must run before BracesPositionFixer, ControlStructureContinuationPositionFixer, CurlyBracesPositionFixer, NoMultipleStatementsPerLineFixer. */ public function getPriority(): int { return 1; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $alternativeSyntaxAnalyzer = new AlternativeSyntaxAnalyzer(); for ($index = $tokens->count() - 1; 0 <= $index; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind(self::CONTROL_TOKENS)) { continue; } if ( $token->isGivenKind(\T_ELSE) && $tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(\T_IF) ) { continue; } $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index); $nextAfterParenthesisEndIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); $tokenAfterParenthesis = $tokens[$nextAfterParenthesisEndIndex]; if ($tokenAfterParenthesis->equalsAny([';', '{', ':', [\T_CLOSE_TAG]])) { continue; } $statementEndIndex = null; if ($tokenAfterParenthesis->isGivenKind([\T_IF, \T_FOR, \T_FOREACH, \T_SWITCH, \T_WHILE])) { $tokenAfterParenthesisBlockEnd = $tokens->findBlockEnd( // go to ')' Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextMeaningfulToken($nextAfterParenthesisEndIndex), ); if ($tokens[$tokens->getNextMeaningfulToken($tokenAfterParenthesisBlockEnd)]->equals(':')) { $statementEndIndex = $alternativeSyntaxAnalyzer->findAlternativeSyntaxBlockEnd($tokens, $nextAfterParenthesisEndIndex); $tokenAfterStatementEndIndex = $tokens->getNextMeaningfulToken($statementEndIndex); if ($tokens[$tokenAfterStatementEndIndex]->equals(';')) { $statementEndIndex = $tokenAfterStatementEndIndex; } } } if (null === $statementEndIndex) { $statementEndIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex); } $tokensToInsertAfterStatement = [ new Token([\T_WHITESPACE, ' ']), new Token('}'), ]; if (!$tokens[$statementEndIndex]->equalsAny([';', '}'])) { array_unshift($tokensToInsertAfterStatement, new Token(';')); } $tokens->insertSlices([$statementEndIndex + 1 => $tokensToInsertAfterStatement]); // insert opening brace $tokens->insertSlices([$parenthesisEndIndex + 1 => [ new Token([\T_WHITESPACE, ' ']), new Token('{'), ]]); } } private function findParenthesisEnd(Tokens $tokens, int $structureTokenIndex): int { $nextIndex = $tokens->getNextMeaningfulToken($structureTokenIndex); $nextToken = $tokens[$nextIndex]; if (!$nextToken->equals('(')) { return $structureTokenIndex; } return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex); } private function findStatementEnd(Tokens $tokens, int $parenthesisEndIndex): int { $nextIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); if (null === $nextIndex) { return $parenthesisEndIndex; } $nextToken = $tokens[$nextIndex]; if ($nextToken->equals('{')) { return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nextIndex); } if ($nextToken->isGivenKind(self::CONTROL_TOKENS)) { $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $nextIndex); $endIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex); if ($nextToken->isGivenKind([\T_IF, \T_TRY, \T_DO])) { $openingTokenKind = $nextToken->getId(); while (true) { $nextIndex = $tokens->getNextMeaningfulToken($endIndex); if (null !== $nextIndex && $tokens[$nextIndex]->isGivenKind($this->getControlContinuationTokensForOpeningToken($openingTokenKind))) { $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $nextIndex); $endIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex); if ($tokens[$nextIndex]->isGivenKind($this->getFinalControlContinuationTokensForOpeningToken($openingTokenKind))) { return $endIndex; } } else { break; } } } return $endIndex; } $index = $parenthesisEndIndex; while (true) { $token = $tokens[++$index]; // if there is some block in statement (eg lambda function) we need to skip it if ($token->equals('{')) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); continue; } if ($token->equals(';')) { return $index; } if ($token->isGivenKind(\T_CLOSE_TAG)) { return $tokens->getPrevNonWhitespace($index); } } } /** * @return list<int> */ private function getControlContinuationTokensForOpeningToken(int $openingTokenKind): array { if (\T_IF === $openingTokenKind) { return [ \T_ELSE, \T_ELSEIF, ]; } if (\T_DO === $openingTokenKind) { return [\T_WHILE]; } if (\T_TRY === $openingTokenKind) { return [ \T_CATCH, \T_FINALLY, ]; } return []; } /** * @return list<int> */ private function getFinalControlContinuationTokensForOpeningToken(int $openingTokenKind): array { if (\T_IF === $openingTokenKind) { return [\T_ELSE]; } if (\T_TRY === $openingTokenKind) { return [\T_FINALLY]; } 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/ControlStructure/YodaStyleFixer.php
src/Fixer/ControlStructure/YodaStyleFixer.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\ControlStructure; 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; use PhpCsFixer\Tokenizer\TokensAnalyzer; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * always_move_variable?: bool, * equal?: bool|null, * identical?: bool|null, * less_and_greater?: bool|null, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * always_move_variable: bool, * equal: bool|null, * identical: bool|null, * less_and_greater: bool|null, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @phpstan-import-type _PhpTokenKind from Token * * @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 YodaStyleFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; /** * @var array<_PhpTokenKind, Token> */ private array $candidatesMap; /** * @var array<_PhpTokenKind, null|bool> */ private array $candidateTypesConfiguration; /** * @var list<_PhpTokenKind> */ private array $candidateTypes; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Write conditions in Yoda style (`true`), non-Yoda style (`[\'equal\' => false, \'identical\' => false, \'less_and_greater\' => false]`) or ignore those conditions (`null`) based on configuration.', [ new CodeSample( <<<'PHP' <?php if ($a === null) { echo "null"; } PHP, ), new CodeSample( <<<'PHP' <?php $b = $c != 1; // equal $a = 1 === $b; // identical $c = $c > 3; // less than PHP, [ 'equal' => true, 'identical' => false, 'less_and_greater' => null, ], ), new CodeSample( <<<'PHP' <?php return $foo === count($bar); PHP, [ 'always_move_variable' => true, ], ), new CodeSample( <<<'PHP' <?php // Enforce non-Yoda style. if (null === $a) { echo "null"; } PHP, [ 'equal' => false, 'identical' => false, 'less_and_greater' => false, ], ), ], ); } /** * {@inheritdoc} * * Must run after IsNullFixer. */ public function getPriority(): int { return 0; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound($this->candidateTypes); } protected function configurePostNormalisation(): void { $this->resolveConfiguration(); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $this->fixTokens($tokens); } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('equal', 'Style for equal (`==`, `!=`) statements.')) ->setAllowedTypes(['bool', 'null']) ->setDefault(true) ->getOption(), (new FixerOptionBuilder('identical', 'Style for identical (`===`, `!==`) statements.')) ->setAllowedTypes(['bool', 'null']) ->setDefault(true) ->getOption(), (new FixerOptionBuilder('less_and_greater', 'Style for less and greater than (`<`, `<=`, `>`, `>=`) statements.')) ->setAllowedTypes(['bool', 'null']) ->setDefault(null) ->getOption(), (new FixerOptionBuilder('always_move_variable', 'Whether variables should always be on non assignable side when applying Yoda style.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), ]); } /** * Finds the end of the right-hand side of the comparison at the given * index. * * The right-hand side ends when an operator with a lower precedence is * encountered or when the block level for `()`, `{}` or `[]` goes below * zero. * * @param Tokens $tokens The token list * @param int $index The index of the comparison * * @return int The last index of the right-hand side of the comparison */ private function findComparisonEnd(Tokens $tokens, int $index): int { ++$index; $count = \count($tokens); while ($index < $count) { $token = $tokens[$index]; if ($token->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { ++$index; continue; } if ($this->isOfLowerPrecedence($token)) { break; } $block = Tokens::detectBlockType($token); if (null === $block) { ++$index; continue; } if (!$block['isStart']) { break; } $index = $tokens->findBlockEnd($block['type'], $index) + 1; } $prev = $tokens->getPrevMeaningfulToken($index); return $tokens[$prev]->isGivenKind(\T_CLOSE_TAG) ? $tokens->getPrevMeaningfulToken($prev) : $prev; } /** * Finds the start of the left-hand side of the comparison at the given * index. * * The left-hand side ends when an operator with a lower precedence is * encountered or when the block level for `()`, `{}` or `[]` goes below * zero. * * @param Tokens $tokens The token list * @param int $index The index of the comparison * * @return int The first index of the left-hand side of the comparison */ private function findComparisonStart(Tokens $tokens, int $index): int { --$index; $nonBlockFound = false; while (0 <= $index) { $token = $tokens[$index]; if ($token->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { --$index; continue; } if ($token->isGivenKind(CT::T_NAMED_ARGUMENT_COLON)) { break; } if ($this->isOfLowerPrecedence($token)) { break; } $block = Tokens::detectBlockType($token); if (null === $block) { --$index; $nonBlockFound = true; continue; } if ( $block['isStart'] || ($nonBlockFound && Tokens::BLOCK_TYPE_CURLY_BRACE === $block['type']) // closing of structure not related to the comparison ) { break; } $index = $tokens->findBlockStart($block['type'], $index) - 1; } return $tokens->getNextMeaningfulToken($index); } private function fixTokens(Tokens $tokens): Tokens { for ($i = \count($tokens) - 1; $i > 1; --$i) { if ($tokens[$i]->isGivenKind($this->candidateTypes)) { $yoda = $this->candidateTypesConfiguration[$tokens[$i]->getId()]; } elseif ( ($tokens[$i]->equals('<') && \in_array('<', $this->candidateTypes, true)) || ($tokens[$i]->equals('>') && \in_array('>', $this->candidateTypes, true)) ) { $yoda = $this->candidateTypesConfiguration[$tokens[$i]->getContent()]; } else { continue; } $fixableCompareInfo = $this->getCompareFixableInfo($tokens, $i, $yoda); if (null === $fixableCompareInfo) { continue; } $i = $this->fixTokensCompare( $tokens, $fixableCompareInfo['left']['start'], $fixableCompareInfo['left']['end'], $i, $fixableCompareInfo['right']['start'], $fixableCompareInfo['right']['end'], ); } return $tokens; } /** * Fixes the comparison at the given index. * * A comparison is considered fixed when * - both sides are a variable (e.g. $a === $b) * - neither side is a variable (e.g. self::CONST === 3) * - only the right-hand side is a variable (e.g. 3 === self::$var) * * If the left-hand side and right-hand side of the given comparison are * swapped, this function runs recursively on the previous left-hand-side. * * @return int an upper bound for all non-fixed comparisons */ private function fixTokensCompare( Tokens $tokens, int $startLeft, int $endLeft, int $compareOperatorIndex, int $startRight, int $endRight ): int { $type = $tokens[$compareOperatorIndex]->getId(); $content = $tokens[$compareOperatorIndex]->getContent(); if (\array_key_exists($type, $this->candidatesMap)) { $tokens[$compareOperatorIndex] = clone $this->candidatesMap[$type]; } elseif (\array_key_exists($content, $this->candidatesMap)) { $tokens[$compareOperatorIndex] = clone $this->candidatesMap[$content]; } $right = $this->fixTokensComparePart($tokens, $startRight, $endRight); $left = $this->fixTokensComparePart($tokens, $startLeft, $endLeft); for ($i = $startRight; $i <= $endRight; ++$i) { $tokens->clearAt($i); } for ($i = $startLeft; $i <= $endLeft; ++$i) { $tokens->clearAt($i); } $tokens->insertAt($startRight, $left); $tokens->insertAt($startLeft, $right); return $startLeft; } private function fixTokensComparePart(Tokens $tokens, int $start, int $end): Tokens { $newTokens = $tokens->generatePartialCode($start, $end); $newTokens = $this->fixTokens(Tokens::fromCode(\sprintf('<?php %s;', $newTokens))); $newTokens->clearAt(\count($newTokens) - 1); $newTokens->clearAt(0); $newTokens->clearEmptyTokens(); return $newTokens; } /** * @return null|array{left: array{start: int, end: int}, right: array{start: int, end: int}} */ private function getCompareFixableInfo(Tokens $tokens, int $index, bool $yoda): ?array { $right = $this->getRightSideCompareFixableInfo($tokens, $index); if (!$yoda && $this->isOfLowerPrecedenceAssignment($tokens[$tokens->getNextMeaningfulToken($right['end'])])) { return null; } $left = $this->getLeftSideCompareFixableInfo($tokens, $index); if ($this->isListStatement($tokens, $left['start'], $left['end']) || $this->isListStatement($tokens, $right['start'], $right['end'])) { return null; // do not fix lists assignment inside statements } /** @var bool $strict */ $strict = $this->configuration['always_move_variable']; $leftSideIsVariable = $this->isVariable($tokens, $left['start'], $left['end'], $strict); $rightSideIsVariable = $this->isVariable($tokens, $right['start'], $right['end'], $strict); if (!($leftSideIsVariable xor $rightSideIsVariable)) { return null; // both are (not) variables, do not touch } if (!$strict) { // special handling for braces with not "always_move_variable" $leftSideIsVariable = $leftSideIsVariable && !$tokens[$left['start']]->equals('('); $rightSideIsVariable = $rightSideIsVariable && !$tokens[$right['start']]->equals('('); } return ($yoda && !$leftSideIsVariable) || (!$yoda && !$rightSideIsVariable) ? null : ['left' => $left, 'right' => $right]; } /** * @return array{start: int, end: int} */ private function getLeftSideCompareFixableInfo(Tokens $tokens, int $index): array { return [ 'start' => $this->findComparisonStart($tokens, $index), 'end' => $tokens->getPrevMeaningfulToken($index), ]; } /** * @return array{start: int, end: int} */ private function getRightSideCompareFixableInfo(Tokens $tokens, int $index): array { return [ 'start' => $tokens->getNextMeaningfulToken($index), 'end' => $this->findComparisonEnd($tokens, $index), ]; } private function isListStatement(Tokens $tokens, int $index, int $end): bool { for ($i = $index; $i <= $end; ++$i) { if ($tokens[$i]->isGivenKind([\T_LIST, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE])) { return true; } } return false; } /** * Checks whether the given token has a lower precedence than `T_IS_EQUAL` * or `T_IS_IDENTICAL`. * * @param Token $token The token to check * * @return bool Whether the token has a lower precedence */ private function isOfLowerPrecedence(Token $token): bool { return $this->isOfLowerPrecedenceAssignment($token) || $token->isGivenKind([ \T_BOOLEAN_AND, // && \T_BOOLEAN_OR, // || \T_CASE, // case \T_DOUBLE_ARROW, // => \T_ECHO, // echo \T_GOTO, // goto \T_LOGICAL_AND, // and \T_LOGICAL_OR, // or \T_LOGICAL_XOR, // xor \T_OPEN_TAG, // <?php \T_OPEN_TAG_WITH_ECHO, \T_PRINT, // print \T_RETURN, // return \T_THROW, // throw \T_COALESCE, \T_YIELD, // yield \T_YIELD_FROM, \T_REQUIRE, \T_REQUIRE_ONCE, \T_INCLUDE, \T_INCLUDE_ONCE, ]) || $token->equalsAny([ // bitwise and, or, xor '&', '|', '^', // ternary operators '?', ':', // end of PHP statement ',', ';', ]); } /** * Checks whether the given assignment token has a lower precedence than `T_IS_EQUAL` * or `T_IS_IDENTICAL`. */ private function isOfLowerPrecedenceAssignment(Token $token): bool { return $token->equals('=') || $token->isGivenKind([ \T_AND_EQUAL, // &= \T_CONCAT_EQUAL, // .= \T_DIV_EQUAL, // /= \T_MINUS_EQUAL, // -= \T_MOD_EQUAL, // %= \T_MUL_EQUAL, // *= \T_OR_EQUAL, // |= \T_PLUS_EQUAL, // += \T_POW_EQUAL, // **= \T_SL_EQUAL, // <<= \T_SR_EQUAL, // >>= \T_XOR_EQUAL, // ^= \T_COALESCE_EQUAL, // ??= ]); } /** * Checks whether the tokens between the given start and end describe a * variable. * * @param Tokens $tokens The token list * @param int $start The first index of the possible variable * @param int $end The last index of the possible variable * @param bool $strict Enable strict variable detection * * @return bool Whether the tokens describe a variable */ private function isVariable(Tokens $tokens, int $start, int $end, bool $strict): bool { $tokenAnalyzer = new TokensAnalyzer($tokens); if ($start === $end) { return $tokens[$start]->isGivenKind(\T_VARIABLE); } if ($tokens[$start]->equals('(')) { return true; } if ($strict) { for ($index = $start; $index <= $end; ++$index) { if ( $tokens[$index]->isCast() || $tokens[$index]->isGivenKind(\T_INSTANCEOF) || $tokens[$index]->equals('!') || $tokenAnalyzer->isBinaryOperator($index) ) { return false; } } } $index = $start; // handle multiple braces around statement ((($a === 1))) while ( $tokens[$index]->equals('(') && $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index) === $end ) { $index = $tokens->getNextMeaningfulToken($index); $end = $tokens->getPrevMeaningfulToken($end); } $expectString = false; while ($index <= $end) { $current = $tokens[$index]; if ($current->isComment() || $current->isWhitespace() || $tokens->isEmptyAt($index)) { ++$index; continue; } // check if this is the last token if ($index === $end) { return $current->isGivenKind($expectString ? \T_STRING : \T_VARIABLE); } if ($current->isGivenKind([\T_LIST, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE])) { return false; } $nextIndex = $tokens->getNextMeaningfulToken($index); $next = $tokens[$nextIndex]; // self:: or ClassName:: if ($current->isGivenKind(\T_STRING) && $next->isGivenKind(\T_DOUBLE_COLON)) { $index = $tokens->getNextMeaningfulToken($nextIndex); continue; } // \ClassName if ($current->isGivenKind(\T_NS_SEPARATOR) && $next->isGivenKind(\T_STRING)) { $index = $nextIndex; continue; } // ClassName\ if ($current->isGivenKind(\T_STRING) && $next->isGivenKind(\T_NS_SEPARATOR)) { $index = $nextIndex; continue; } // $a-> or a-> (as in $b->a->c) if ($current->isGivenKind([\T_STRING, \T_VARIABLE]) && $next->isObjectOperator()) { $index = $tokens->getNextMeaningfulToken($nextIndex); $expectString = true; continue; } // $a[...], a[...] (as in $c->a[$b]), $a{...} or a{...} (as in $c->a{$b}) if ( $current->isGivenKind($expectString ? \T_STRING : \T_VARIABLE) && $next->equalsAny(['[', [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, '{']]) ) { $index = $tokens->findBlockEnd( $next->equals('[') ? Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE : Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE, $nextIndex, ); if ($index === $end) { return true; } $index = $tokens->getNextMeaningfulToken($index); if (!$tokens[$index]->equalsAny(['[', [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, '{']]) && !$tokens[$index]->isObjectOperator()) { return false; } $index = $tokens->getNextMeaningfulToken($index); $expectString = true; continue; } // $a(...) or $a->b(...) if ($strict && $current->isGivenKind([\T_STRING, \T_VARIABLE]) && $next->equals('(')) { return false; } // {...} (as in $a->{$b}) if ($expectString && $current->isGivenKind(CT::T_DYNAMIC_PROP_BRACE_OPEN)) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_DYNAMIC_PROP_BRACE, $index); if ($index === $end) { return true; } $index = $tokens->getNextMeaningfulToken($index); if (!$tokens[$index]->isObjectOperator()) { return false; } $index = $tokens->getNextMeaningfulToken($index); $expectString = true; continue; } break; } return !$this->isConstant($tokens, $start, $end); } private function isConstant(Tokens $tokens, int $index, int $end): bool { $expectArrayOnly = false; $expectNumberOnly = false; $expectNothing = false; for (; $index <= $end; ++$index) { $token = $tokens[$index]; if ($token->isComment() || $token->isWhitespace()) { continue; } if ($expectNothing) { return false; } if ($expectArrayOnly) { if ($token->equalsAny(['(', ')', [CT::T_ARRAY_SQUARE_BRACE_CLOSE]])) { continue; } return false; } if ($token->isGivenKind([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) { $expectArrayOnly = true; continue; } if ($expectNumberOnly && !$token->isGivenKind([\T_LNUMBER, \T_DNUMBER])) { return false; } if ($token->equals('-')) { $expectNumberOnly = true; continue; } if ( $token->isGivenKind([\T_LNUMBER, \T_DNUMBER, \T_CONSTANT_ENCAPSED_STRING]) || $token->equalsAny([[\T_STRING, 'true'], [\T_STRING, 'false'], [\T_STRING, 'null']]) ) { $expectNothing = true; continue; } return false; } return true; } private function resolveConfiguration(): void { $candidateTypes = []; $this->candidatesMap = []; if (null !== $this->configuration['equal']) { // `==`, `!=` and `<>` $candidateTypes[\T_IS_EQUAL] = $this->configuration['equal']; $candidateTypes[\T_IS_NOT_EQUAL] = $this->configuration['equal']; } if (null !== $this->configuration['identical']) { // `===` and `!==` $candidateTypes[\T_IS_IDENTICAL] = $this->configuration['identical']; $candidateTypes[\T_IS_NOT_IDENTICAL] = $this->configuration['identical']; } if (null !== $this->configuration['less_and_greater']) { // `<`, `<=`, `>` and `>=` $candidateTypes[\T_IS_SMALLER_OR_EQUAL] = $this->configuration['less_and_greater']; $this->candidatesMap[\T_IS_SMALLER_OR_EQUAL] = new Token([\T_IS_GREATER_OR_EQUAL, '>=']); $candidateTypes[\T_IS_GREATER_OR_EQUAL] = $this->configuration['less_and_greater']; $this->candidatesMap[\T_IS_GREATER_OR_EQUAL] = new Token([\T_IS_SMALLER_OR_EQUAL, '<=']); $candidateTypes['<'] = $this->configuration['less_and_greater']; $this->candidatesMap['<'] = new Token('>'); $candidateTypes['>'] = $this->configuration['less_and_greater']; $this->candidatesMap['>'] = new Token('<'); } $this->candidateTypesConfiguration = $candidateTypes; $this->candidateTypes = array_keys($candidateTypes); } }
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/ControlStructure/NoUnneededBracesFixer.php
src/Fixer/ControlStructure/NoUnneededBracesFixer.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\ControlStructure; 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; use PhpCsFixer\Tokenizer\TokensAnalyzer; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * namespaces?: bool, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * namespaces: bool, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NoUnneededBracesFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Removes unneeded braces that are superfluous and aren\'t part of a control structure\'s body.', [ new CodeSample( <<<'PHP' <?php { echo 1; } switch ($b) { case 1: { break; } } PHP, ), new CodeSample( <<<'PHP' <?php namespace Foo { function Bar(){} } PHP, ['namespaces' => true], ), ], ); } /** * {@inheritdoc} * * Must run before NoUselessElseFixer, NoUselessReturnFixer, ReturnAssignmentFixer, SimplifiedIfReturnFixer. */ public function getPriority(): int { return 40; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound(['}', CT::T_GROUP_IMPORT_BRACE_CLOSE]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ($this->findBraceOpen($tokens) as $index) { if ($this->isOverComplete($tokens, $index)) { $this->clearOverCompleteBraces($tokens, $index); } } if (true === $this->configuration['namespaces']) { $this->clearIfIsOverCompleteNamespaceBlock($tokens); } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('namespaces', 'Remove unneeded braces from bracketed namespaces.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), ]); } /** * @param int $openIndex index of `{` token */ private function clearOverCompleteBraces(Tokens $tokens, int $openIndex): void { $blockType = Tokens::detectBlockType($tokens[$openIndex]); $closeIndex = $tokens->findBlockEnd($blockType['type'], $openIndex); $tokens->clearTokenAndMergeSurroundingWhitespace($closeIndex); $tokens->clearTokenAndMergeSurroundingWhitespace($openIndex); } /** * @return iterable<int> */ private function findBraceOpen(Tokens $tokens): iterable { for ($i = \count($tokens) - 1; $i > 0; --$i) { if ($tokens[$i]->equalsAny(['{', [CT::T_GROUP_IMPORT_BRACE_OPEN]])) { yield $i; } } } /** * @param int $index index of `{` token */ private function isOverComplete(Tokens $tokens, int $index): bool { if ($tokens[$index]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { $commaOrCloseBraceIndex = $tokens->getNextTokenOfKind($index, [',', [CT::T_GROUP_IMPORT_BRACE_CLOSE]]); $analyzer = new TokensAnalyzer($tokens); if ($analyzer->isBlockMultiline($tokens, $index)) { return false; } return $tokens[$commaOrCloseBraceIndex]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE); } return $tokens[$tokens->getPrevMeaningfulToken($index)]->equalsAny(['{', '}', [\T_OPEN_TAG], ':', ';']); } private function clearIfIsOverCompleteNamespaceBlock(Tokens $tokens): void { if (1 !== $tokens->countTokenKind(\T_NAMESPACE)) { return; // fast check, we never fix if multiple namespaces are defined } $index = $tokens->getNextTokenOfKind(0, [[\T_NAMESPACE]]); $namespaceIsNamed = false; $index = $tokens->getNextMeaningfulToken($index); while ($tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) { $index = $tokens->getNextMeaningfulToken($index); $namespaceIsNamed = true; } if (!$namespaceIsNamed) { return; } if (!$tokens[$index]->equals('{')) { return; // `;` } $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); $afterCloseIndex = $tokens->getNextMeaningfulToken($closeIndex); if (null !== $afterCloseIndex && (!$tokens[$afterCloseIndex]->isGivenKind(\T_CLOSE_TAG) || null !== $tokens->getNextMeaningfulToken($afterCloseIndex))) { return; } // clear up $tokens->clearTokenAndMergeSurroundingWhitespace($closeIndex); $tokens[$index] = new Token(';'); if ($tokens[$index - 1]->isWhitespace(" \t") && !$tokens[$index - 2]->isComment()) { $tokens->clearTokenAndMergeSurroundingWhitespace($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/ControlStructure/NoSuperfluousElseifFixer.php
src/Fixer/ControlStructure/NoSuperfluousElseifFixer.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\ControlStructure; use PhpCsFixer\AbstractNoUselessElseFixer; 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 NoSuperfluousElseifFixer extends AbstractNoUselessElseFixer { public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound([\T_ELSE, \T_ELSEIF]); } public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Replaces superfluous `elseif` with `if`.', [ new CodeSample("<?php\nif (\$a) {\n return 1;\n} elseif (\$b) {\n return 2;\n}\n"), ], ); } /** * {@inheritdoc} * * Must run before SimplifiedIfReturnFixer. * Must run after NoAlternativeSyntaxFixer. */ public function getPriority(): int { return parent::getPriority(); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ($tokens as $index => $token) { if ($this->isElseif($tokens, $index) && $this->isSuperfluousElse($tokens, $index)) { $this->convertElseifToIf($tokens, $index); } } } private function isElseif(Tokens $tokens, int $index): bool { return $tokens[$index]->isGivenKind(\T_ELSEIF) || ($tokens[$index]->isGivenKind(\T_ELSE) && $tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(\T_IF)); } private function convertElseifToIf(Tokens $tokens, int $index): void { if ($tokens[$index]->isGivenKind(\T_ELSE)) { $tokens->clearTokenAndMergeSurroundingWhitespace($index); } else { $tokens[$index] = new Token([\T_IF, 'if']); } $whitespace = ''; for ($previous = $index - 1; $previous > 0; --$previous) { $token = $tokens[$previous]; if ($token->isWhitespace() && Preg::match('/(\R\N*)$/', $token->getContent(), $matches)) { $whitespace = $matches[1]; break; } } if ('' === $whitespace) { return; } $previousToken = $tokens[$index - 1]; if (!$previousToken->isWhitespace()) { $tokens->insertAt($index, new Token([\T_WHITESPACE, $whitespace])); } elseif (!Preg::match('/\R/', $previousToken->getContent())) { $tokens[$index - 1] = new Token([\T_WHITESPACE, $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/ControlStructure/NoTrailingCommaInListCallFixer.php
src/Fixer/ControlStructure/NoTrailingCommaInListCallFixer.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\ControlStructure; use PhpCsFixer\AbstractProxyFixer; use PhpCsFixer\Fixer\Basic\NoTrailingCommaInSinglelineFixer; use PhpCsFixer\Fixer\DeprecatedFixerInterface; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; /** * @deprecated * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NoTrailingCommaInListCallFixer extends AbstractProxyFixer implements DeprecatedFixerInterface { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Remove trailing commas in list function calls.', [new CodeSample("<?php\nlist(\$a, \$b,) = foo();\n")], ); } public function getSuccessorsNames(): array { return array_keys($this->proxyFixers); } protected function createProxyFixers(): array { $fixer = new NoTrailingCommaInSinglelineFixer(); $fixer->configure(['elements' => ['array_destructuring']]); 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/Basic/CurlyBracesPositionFixer.php
src/Fixer/Basic/CurlyBracesPositionFixer.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\Basic; use PhpCsFixer\AbstractProxyFixer; use PhpCsFixer\Fixer\ConfigurableFixerInterface; use PhpCsFixer\Fixer\ConfigurableFixerTrait; use PhpCsFixer\Fixer\DeprecatedFixerInterface; use PhpCsFixer\Fixer\IndentationTrait; use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; /** * @deprecated * * @phpstan-type _AutogeneratedInputConfiguration array{ * allow_single_line_anonymous_functions?: bool, * allow_single_line_empty_anonymous_classes?: bool, * anonymous_classes_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', * anonymous_functions_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', * classes_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', * control_structures_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', * functions_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * allow_single_line_anonymous_functions: bool, * allow_single_line_empty_anonymous_classes: bool, * anonymous_classes_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', * anonymous_functions_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', * classes_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', * control_structures_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', * functions_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class CurlyBracesPositionFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, DeprecatedFixerInterface, WhitespacesAwareFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; use IndentationTrait; private BracesPositionFixer $bracesPositionFixer; public function __construct() { $this->bracesPositionFixer = new BracesPositionFixer(); parent::__construct(); } public function getDefinition(): FixerDefinitionInterface { $fixerDefinition = $this->bracesPositionFixer->getDefinition(); return new FixerDefinition( 'Curly braces must be placed as configured.', $fixerDefinition->getCodeSamples(), $fixerDefinition->getDescription(), $fixerDefinition->getRiskyDescription(), ); } /** * {@inheritdoc} * * Must run before SingleLineEmptyBodyFixer, StatementIndentationFixer. * Must run after ControlStructureBracesFixer, NoMultipleStatementsPerLineFixer. */ public function getPriority(): int { return $this->bracesPositionFixer->getPriority(); } public function getSuccessorsNames(): array { return [ $this->bracesPositionFixer->getName(), ]; } /** * @param _AutogeneratedInputConfiguration $configuration */ protected function configurePreNormalisation(array $configuration): void { $this->bracesPositionFixer->configure($configuration); } protected function createProxyFixers(): array { return [ $this->bracesPositionFixer, ]; } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return $this->bracesPositionFixer->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/Basic/BracesPositionFixer.php
src/Fixer/Basic/BracesPositionFixer.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\Basic; 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\CT; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; use PhpCsFixer\Tokenizer\TokensAnalyzer; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * allow_single_line_anonymous_functions?: bool, * allow_single_line_empty_anonymous_classes?: bool, * anonymous_classes_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', * anonymous_functions_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', * classes_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', * control_structures_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', * functions_opening_brace?: 'next_line_unless_newline_at_signature_end'|'same_line', * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * allow_single_line_anonymous_functions: bool, * allow_single_line_empty_anonymous_classes: bool, * anonymous_classes_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', * anonymous_functions_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', * classes_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', * control_structures_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', * functions_opening_brace: 'next_line_unless_newline_at_signature_end'|'same_line', * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class BracesPositionFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; use IndentationTrait; /** * @internal */ public const NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END = 'next_line_unless_newline_at_signature_end'; /** * @internal */ public const SAME_LINE = 'same_line'; private const CONTROL_STRUCTURE_TOKENS = [\T_DECLARE, \T_DO, \T_ELSE, \T_ELSEIF, \T_FINALLY, \T_FOR, \T_FOREACH, \T_IF, \T_WHILE, \T_TRY, \T_CATCH, \T_SWITCH, FCT::T_MATCH]; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Braces must be placed as configured.', [ new CodeSample( <<<'PHP' <?php class Foo { } function foo() { } $foo = function() { }; if (foo()) { bar(); } $foo = new class { }; PHP, ), new CodeSample( <<<'PHP' <?php if (foo()) { bar(); } PHP, ['control_structures_opening_brace' => self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END], ), new CodeSample( <<<'PHP' <?php function foo() { } PHP, ['functions_opening_brace' => self::SAME_LINE], ), new CodeSample( <<<'PHP' <?php $foo = function () { }; PHP, ['anonymous_functions_opening_brace' => self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END], ), new CodeSample( <<<'PHP' <?php class Foo { } PHP, ['classes_opening_brace' => self::SAME_LINE], ), new CodeSample( <<<'PHP' <?php $foo = new class { }; PHP, ['anonymous_classes_opening_brace' => self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END], ), new CodeSample( <<<'PHP' <?php $foo = new class { }; $bar = new class { private $baz; }; PHP, ['allow_single_line_empty_anonymous_classes' => true], ), new CodeSample( <<<'PHP' <?php $foo = function () { return true; }; $bar = function () { $result = true; return $result; }; PHP, ['allow_single_line_anonymous_functions' => true], ), ], ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound('{'); } /** * {@inheritdoc} * * Must run before SingleLineEmptyBodyFixer, StatementIndentationFixer. * Must run after ControlStructureBracesFixer, MultilinePromotedPropertiesFixer, NoMultipleStatementsPerLineFixer. */ public function getPriority(): int { return -2; } /** @protected */ public function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('control_structures_opening_brace', 'The position of the opening brace of control structures‘ body.')) ->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE]) ->setDefault(self::SAME_LINE) ->getOption(), (new FixerOptionBuilder('functions_opening_brace', 'The position of the opening brace of functions‘ body.')) ->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE]) ->setDefault(self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END) ->getOption(), (new FixerOptionBuilder('anonymous_functions_opening_brace', 'The position of the opening brace of anonymous functions‘ body.')) ->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE]) ->setDefault(self::SAME_LINE) ->getOption(), (new FixerOptionBuilder('classes_opening_brace', 'The position of the opening brace of classes‘ body.')) ->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE]) ->setDefault(self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END) ->getOption(), (new FixerOptionBuilder('anonymous_classes_opening_brace', 'The position of the opening brace of anonymous classes‘ body.')) ->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE]) ->setDefault(self::SAME_LINE) ->getOption(), (new FixerOptionBuilder('allow_single_line_empty_anonymous_classes', 'Allow anonymous classes to have opening and closing braces on the same line.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), (new FixerOptionBuilder('allow_single_line_anonymous_functions', 'Allow anonymous functions to have opening and closing braces on the same line.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $classyTokens = Token::getClassyTokenKinds(); $tokensAnalyzer = new TokensAnalyzer($tokens); $allowSingleLineUntil = null; foreach ($tokens as $index => $token) { $allowSingleLine = false; $allowSingleLineIfEmpty = false; if ($token->isGivenKind($classyTokens)) { $openBraceIndex = $tokens->getNextTokenOfKind($index, ['{']); if ($tokensAnalyzer->isAnonymousClass($index)) { $allowSingleLineIfEmpty = true === $this->configuration['allow_single_line_empty_anonymous_classes']; $positionOption = 'anonymous_classes_opening_brace'; } else { $positionOption = 'classes_opening_brace'; } } elseif ($token->isGivenKind(\T_FUNCTION)) { $openBraceIndex = $tokens->getNextTokenOfKind($index, ['{', ';', [CT::T_PROPERTY_HOOK_BRACE_OPEN]]); if (!$tokens[$openBraceIndex]->equals('{')) { continue; } if ($tokensAnalyzer->isLambda($index)) { $allowSingleLine = true === $this->configuration['allow_single_line_anonymous_functions']; $positionOption = 'anonymous_functions_opening_brace'; } else { $positionOption = 'functions_opening_brace'; } } elseif ($token->isGivenKind(self::CONTROL_STRUCTURE_TOKENS)) { $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index); $openBraceIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); if (!$tokens[$openBraceIndex]->equals('{')) { continue; } $positionOption = 'control_structures_opening_brace'; } elseif ($token->isGivenKind(\T_VARIABLE)) { // handle default value - explicitly skip array as default value $nextMeaningfulIndex = $tokens->getNextMeaningfulToken($index); if ($tokens[$nextMeaningfulIndex]->equals('=')) { $nextMeaningfulIndex = $tokens->getNextMeaningfulToken($nextMeaningfulIndex); if ($tokens[$nextMeaningfulIndex]->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $nextMeaningfulIndex); } elseif ($tokens[$nextMeaningfulIndex]->isGivenKind(\T_ARRAY)) { $nextMeaningfulIndex = $tokens->getNextMeaningfulToken($nextMeaningfulIndex); if ($tokens[$nextMeaningfulIndex]->equals('(')) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextMeaningfulIndex); } } } $openBraceIndex = $tokens->getNextTokenOfKind($index, ['{', ';', '.', [CT::T_CURLY_CLOSE], [CT::T_PROPERTY_HOOK_BRACE_OPEN], [\T_ENCAPSED_AND_WHITESPACE], [\T_CLOSE_TAG]]); if (!$tokens[$openBraceIndex]->isGivenKind(CT::T_PROPERTY_HOOK_BRACE_OPEN)) { continue; } $closeBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PROPERTY_HOOK, $openBraceIndex); if (!$tokens->isPartialCodeMultiline($openBraceIndex, $closeBraceIndex)) { continue; } $positionOption = 'control_structures_opening_brace'; } elseif ($token->isGivenKind(\T_STRING)) { $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index); $openBraceIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); if (!$tokens[$openBraceIndex]->equals('{')) { continue; } $prevIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$prevIndex]->equalsAny(['}', ';', [CT::T_ATTRIBUTE_CLOSE], [CT::T_PROPERTY_HOOK_BRACE_OPEN]])) { continue; } $allowSingleLine = true === $this->configuration['allow_single_line_anonymous_functions']; $positionOption = 'control_structures_opening_brace'; } else { continue; } $closeBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openBraceIndex); $addNewlinesInsideBraces = true; if ($allowSingleLine || $allowSingleLineIfEmpty || $index < $allowSingleLineUntil) { $addNewlinesInsideBraces = false; for ($indexInsideBraces = $openBraceIndex + 1; $indexInsideBraces < $closeBraceIndex; ++$indexInsideBraces) { $tokenInsideBraces = $tokens[$indexInsideBraces]; if ( ($allowSingleLineIfEmpty && !$tokenInsideBraces->isWhitespace() && !$tokenInsideBraces->isComment()) || ($tokenInsideBraces->isWhitespace() && Preg::match('/\R/', $tokenInsideBraces->getContent())) ) { $addNewlinesInsideBraces = true; break; } } if (!$addNewlinesInsideBraces && null === $allowSingleLineUntil) { $allowSingleLineUntil = $closeBraceIndex; } } if ( $addNewlinesInsideBraces && !$this->isFollowedByNewLine($tokens, $openBraceIndex) && !$this->hasCommentOnSameLine($tokens, $openBraceIndex) && !$tokens[$tokens->getNextMeaningfulToken($openBraceIndex)]->isGivenKind(\T_CLOSE_TAG) ) { $whitespace = $this->whitespacesConfig->getLineEnding().$this->getLineIndentation($tokens, $openBraceIndex); if ($tokens->ensureWhitespaceAtIndex($openBraceIndex + 1, 0, $whitespace)) { ++$closeBraceIndex; } } $whitespace = ' '; if (self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END === $this->configuration[$positionOption]) { $whitespace = $this->whitespacesConfig->getLineEnding().$this->getLineIndentation($tokens, $index); $previousTokenIndex = $openBraceIndex; do { $previousTokenIndex = $tokens->getPrevMeaningfulToken($previousTokenIndex); } while ($tokens[$previousTokenIndex]->isGivenKind([CT::T_TYPE_COLON, CT::T_NULLABLE_TYPE, \T_STRING, \T_NS_SEPARATOR, CT::T_ARRAY_TYPEHINT, \T_STATIC, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, \T_CALLABLE, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE])); if ($tokens[$previousTokenIndex]->equals(')')) { if ($tokens[--$previousTokenIndex]->isComment()) { --$previousTokenIndex; } if ( $tokens[$previousTokenIndex]->isWhitespace() && Preg::match('/\R/', $tokens[$previousTokenIndex]->getContent()) ) { $whitespace = ' '; } } } $moveBraceToIndex = null; if (' ' === $whitespace) { $previousMeaningfulIndex = $tokens->getPrevMeaningfulToken($openBraceIndex); for ($indexBeforeOpenBrace = $openBraceIndex - 1; $indexBeforeOpenBrace > $previousMeaningfulIndex; --$indexBeforeOpenBrace) { if (!$tokens[$indexBeforeOpenBrace]->isComment()) { continue; } $tokenBeforeOpenBrace = $tokens[--$indexBeforeOpenBrace]; if ($tokenBeforeOpenBrace->isWhitespace()) { $moveBraceToIndex = $indexBeforeOpenBrace; } elseif ($indexBeforeOpenBrace === $previousMeaningfulIndex) { $moveBraceToIndex = $previousMeaningfulIndex + 1; } } } elseif (!$tokens[$openBraceIndex - 1]->isWhitespace() || !Preg::match('/\R/', $tokens[$openBraceIndex - 1]->getContent())) { for ($indexAfterOpenBrace = $openBraceIndex + 1; $indexAfterOpenBrace < $closeBraceIndex; ++$indexAfterOpenBrace) { if ($tokens[$indexAfterOpenBrace]->isWhitespace() && Preg::match('/\R/', $tokens[$indexAfterOpenBrace]->getContent())) { break; } if ($tokens[$indexAfterOpenBrace]->isComment() && !str_starts_with($tokens[$indexAfterOpenBrace]->getContent(), '/*')) { $moveBraceToIndex = $indexAfterOpenBrace + 1; } } } if (null !== $moveBraceToIndex) { $movedToken = clone $tokens[$openBraceIndex]; $delta = $openBraceIndex < $moveBraceToIndex ? 1 : -1; if ($tokens[$openBraceIndex + $delta]->isWhitespace()) { if (-1 === $delta && Preg::match('/\R/', $tokens[$openBraceIndex - 1]->getContent())) { $content = Preg::replace('/^(\h*?\R)?\h*/', '', $tokens[$openBraceIndex + 1]->getContent()); if ('' !== $content) { $tokens[$openBraceIndex + 1] = new Token([\T_WHITESPACE, $content]); } else { $tokens->clearAt($openBraceIndex + 1); } } elseif ($tokens[$openBraceIndex - 1]->isWhitespace()) { $tokens->clearAt($openBraceIndex - 1); } } for ($i = $openBraceIndex; $i !== $moveBraceToIndex; $i += $delta) { $siblingToken = $tokens[$i + $delta]; $tokens[$i] = $siblingToken; } $tokens[$i] = $movedToken; if ($tokens[$openBraceIndex]->isWhitespace() && $tokens[$openBraceIndex + 1]->isWhitespace()) { $tokens[$openBraceIndex] = new Token([ \T_WHITESPACE, $tokens[$openBraceIndex]->getContent().$tokens[$openBraceIndex + 1]->getContent(), ]); $tokens->clearAt($openBraceIndex + 1); } $openBraceIndex = $moveBraceToIndex; } if ($tokens->ensureWhitespaceAtIndex($openBraceIndex - 1, 1, $whitespace)) { ++$closeBraceIndex; if (null !== $allowSingleLineUntil) { ++$allowSingleLineUntil; } } if ( !$addNewlinesInsideBraces || $tokens[$tokens->getPrevMeaningfulToken($closeBraceIndex)]->isGivenKind(\T_OPEN_TAG) ) { continue; } $prevIndex = $closeBraceIndex - 1; while ($tokens->isEmptyAt($prevIndex)) { --$prevIndex; } $prevToken = $tokens[$prevIndex]; if ($prevToken->isWhitespace() && Preg::match('/\R/', $prevToken->getContent())) { continue; } $whitespace = $this->whitespacesConfig->getLineEnding().$this->getLineIndentation($tokens, $openBraceIndex); $tokens->ensureWhitespaceAtIndex($prevIndex, 1, $whitespace); } } private function findParenthesisEnd(Tokens $tokens, int $structureTokenIndex): int { $nextIndex = $tokens->getNextMeaningfulToken($structureTokenIndex); $nextToken = $tokens[$nextIndex]; // return if next token is not opening parenthesis if (!$nextToken->equals('(')) { return $structureTokenIndex; } return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex); } private function isFollowedByNewLine(Tokens $tokens, int $index): bool { for (++$index, $max = \count($tokens) - 1; $index < $max; ++$index) { $token = $tokens[$index]; if (!$token->isComment()) { return $token->isWhitespace() && Preg::match('/\R/', $token->getContent()); } } return false; } private function hasCommentOnSameLine(Tokens $tokens, int $index): bool { $token = $tokens[$index + 1]; if ($token->isWhitespace() && !Preg::match('/\R/', $token->getContent())) { $token = $tokens[$index + 2]; } return $token->isComment(); } }
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/Basic/EncodingFixer.php
src/Fixer/Basic/EncodingFixer.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\Basic; 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 PSR1 ¶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 EncodingFixer extends AbstractFixer { private string $bom; public function __construct() { parent::__construct(); $this->bom = pack('CCC', 0xEF, 0xBB, 0xBF); } public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'PHP code MUST use only UTF-8 without BOM (remove BOM).', [ new CodeSample( <<<PHP {$this->bom}<?php echo "Hello!"; PHP, ), ], ); } public function getPriority(): int { // must run first (at least before Fixers that using Tokens) - for speed reason of whole fixing process return 100; } public function isCandidate(Tokens $tokens): bool { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $content = $tokens[0]->getContent(); if (str_starts_with($content, $this->bom)) { $newContent = substr($content, 3); if ('' === $newContent) { $tokens->clearAt(0); } else { $tokens[0] = new Token([$tokens[0]->getId(), $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/Basic/NoMultipleStatementsPerLineFixer.php
src/Fixer/Basic/NoMultipleStatementsPerLineFixer.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\Basic; 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\Tokens; /** * Fixer for rules defined in PSR2 ¶2.3 Lines: There must not be more than one statement per line. * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NoMultipleStatementsPerLineFixer extends AbstractFixer implements WhitespacesAwareFixerInterface { use IndentationTrait; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'There must not be more than one statement per line.', [new CodeSample("<?php\nfoo(); bar();\n")], ); } /** * {@inheritdoc} * * Must run before BracesPositionFixer, CurlyBracesPositionFixer. * Must run after ControlStructureBracesFixer, NoEmptyStatementFixer, YieldFromArrayToYieldsFixer. */ public function getPriority(): int { return -1; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(';'); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { for ($index = 1, $max = \count($tokens) - 1; $index < $max; ++$index) { if ($tokens[$index]->isGivenKind(\T_FOR)) { $index = $tokens->findBlockEnd( Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextTokenOfKind($index, ['(']), ); continue; } if ($tokens[$index]->isGivenKind(CT::T_PROPERTY_HOOK_BRACE_OPEN)) { $index = $tokens->findBlockEnd( Tokens::BLOCK_TYPE_PROPERTY_HOOK, $index, ); continue; } if (!$tokens[$index]->equals(';')) { continue; } for ($nextIndex = $index + 1; $nextIndex < $max; ++$nextIndex) { $token = $tokens[$nextIndex]; if ($token->isWhitespace() || $token->isComment()) { if (Preg::match('/\R/', $token->getContent())) { break; } continue; } if (!$token->equalsAny(['}', [\T_CLOSE_TAG], [\T_ENDIF], [\T_ENDFOR], [\T_ENDSWITCH], [\T_ENDWHILE], [\T_ENDFOREACH]])) { $whitespaceIndex = $index; do { $token = $tokens[++$whitespaceIndex]; } while ($token->isComment()); $newline = $this->whitespacesConfig->getLineEnding().$this->getLineIndentation($tokens, $index); if ($tokens->ensureWhitespaceAtIndex($whitespaceIndex, 0, $newline)) { ++$max; } } 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/Basic/NoTrailingCommaInSinglelineFixer.php
src/Fixer/Basic/NoTrailingCommaInSinglelineFixer.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\Basic; 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\Analyzer\AttributeAnalyzer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Tokens; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * elements?: list<'arguments'|'array'|'array_destructuring'|'group_import'>, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * elements: list<'arguments'|'array'|'array_destructuring'|'group_import'>, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NoTrailingCommaInSinglelineFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'If a list of values separated by a comma is contained on a single line, then the last item MUST NOT have a trailing comma.', [ new CodeSample("<?php\nfoo(\$a,);\n\$foo = array(1,);\n[\$foo, \$bar,] = \$array;\nuse a\\{ClassA, ClassB,};\n"), new CodeSample("<?php\nfoo(\$a,);\n[\$foo, \$bar,] = \$array;\n", ['elements' => ['array_destructuring']]), ], ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(',') && $tokens->isAnyTokenKindsFound([')', CT::T_ARRAY_SQUARE_BRACE_CLOSE, CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, CT::T_GROUP_IMPORT_BRACE_CLOSE]); } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { $elements = ['arguments', 'array', 'array_destructuring', 'group_import']; return new FixerConfigurationResolver([ (new FixerOptionBuilder('elements', 'Which elements to fix.')) ->setAllowedTypes(['string[]']) ->setAllowedValues([new AllowedValueSubset($elements)]) ->setDefault($elements) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { for ($index = $tokens->count() - 1; $index >= 0; --$index) { if (!$tokens[$index]->equals(')') && !$tokens[$index]->isGivenKind([CT::T_ARRAY_SQUARE_BRACE_CLOSE, CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, CT::T_GROUP_IMPORT_BRACE_CLOSE])) { continue; } $commaIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$commaIndex]->equals(',')) { continue; } $block = Tokens::detectBlockType($tokens[$index]); $blockOpenIndex = $tokens->findBlockStart($block['type'], $index); if ($tokens->isPartialCodeMultiline($blockOpenIndex, $index)) { continue; } if (!$this->shouldBeCleared($tokens, $blockOpenIndex)) { continue; } do { $tokens->clearTokenAndMergeSurroundingWhitespace($commaIndex); $commaIndex = $tokens->getPrevMeaningfulToken($commaIndex); } while ($tokens[$commaIndex]->equals(',')); $tokens->removeTrailingWhitespace($commaIndex); } } private function shouldBeCleared(Tokens $tokens, int $openIndex): bool { $elements = $this->configuration['elements']; if ($tokens[$openIndex]->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { return \in_array('array', $elements, true); } if ($tokens[$openIndex]->isGivenKind(CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN)) { return \in_array('array_destructuring', $elements, true); } if ($tokens[$openIndex]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { return \in_array('group_import', $elements, true); } if (!$tokens[$openIndex]->equals('(')) { return false; } $beforeOpen = $tokens->getPrevMeaningfulToken($openIndex); if ($tokens[$beforeOpen]->isGivenKind(\T_ARRAY)) { return \in_array('array', $elements, true); } if ($tokens[$beforeOpen]->isGivenKind(\T_LIST)) { return \in_array('array_destructuring', $elements, true); } if ($tokens[$beforeOpen]->isGivenKind([\T_UNSET, \T_ISSET, \T_VARIABLE, \T_CLASS])) { return \in_array('arguments', $elements, true); } if ($tokens[$beforeOpen]->isGivenKind(\T_STRING)) { return !AttributeAnalyzer::isAttribute($tokens, $beforeOpen) && \in_array('arguments', $elements, true); } if ($tokens[$beforeOpen]->equalsAny([')', ']', [CT::T_DYNAMIC_VAR_BRACE_CLOSE], [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE]])) { $block = Tokens::detectBlockType($tokens[$beforeOpen]); return ( Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE === $block['type'] || Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE === $block['type'] || Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE === $block['type'] || Tokens::BLOCK_TYPE_PARENTHESIS_BRACE === $block['type'] ) && \in_array('arguments', $elements, 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/Basic/NonPrintableCharacterFixer.php
src/Fixer/Basic/NonPrintableCharacterFixer.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\Basic; 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; /** * Removes Zero-width space (ZWSP), Non-breaking space (NBSP) and other invisible unicode symbols. * * @phpstan-type _AutogeneratedInputConfiguration array{ * use_escape_sequences_in_strings?: bool, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * use_escape_sequences_in_strings: bool, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @author Ivan Boprzenkov <ivan.borzenkov@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NonPrintableCharacterFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; /** * @var non-empty-list<int> */ private const TOKENS = [ \T_STRING_VARNAME, \T_INLINE_HTML, \T_VARIABLE, \T_COMMENT, \T_ENCAPSED_AND_WHITESPACE, \T_CONSTANT_ENCAPSED_STRING, \T_DOC_COMMENT, ]; /** * @var array<string, array{string, string}> */ private array $symbolsReplace; public function __construct() { parent::__construct(); $this->symbolsReplace = [ pack('H*', 'e2808b') => ['', '200b'], // ZWSP U+200B pack('H*', 'e28087') => [' ', '2007'], // FIGURE SPACE U+2007 pack('H*', 'e280af') => [' ', '202f'], // NBSP U+202F pack('H*', 'e281a0') => ['', '2060'], // WORD JOINER U+2060 pack('H*', 'c2a0') => [' ', 'a0'], // NO-BREAK SPACE U+A0 ]; } public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Remove Zero-width space (ZWSP), Non-breaking space (NBSP) and other invisible unicode symbols.', [ new CodeSample( '<?php echo "'.pack('H*', 'e2808b').'Hello'.pack('H*', 'e28087').'World'.pack('H*', 'c2a0')."!\";\n", ), new CodeSample( '<?php echo "'.pack('H*', 'e2808b').'Hello'.pack('H*', 'e28087').'World'.pack('H*', 'c2a0')."!\";\n", ['use_escape_sequences_in_strings' => false], ), ], null, 'Risky when strings contain intended invisible characters.', ); } public function isRisky(): bool { return true; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound(self::TOKENS); } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('use_escape_sequences_in_strings', 'Whether characters should be replaced with escape sequences in strings.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $replacements = []; $escapeSequences = []; foreach ($this->symbolsReplace as $character => [$replacement, $codepoint]) { $replacements[$character] = $replacement; $escapeSequences[$character] = '\u{'.$codepoint.'}'; } foreach ($tokens as $index => $token) { $content = $token->getContent(); if ( true === $this->configuration['use_escape_sequences_in_strings'] && $token->isGivenKind([\T_CONSTANT_ENCAPSED_STRING, \T_ENCAPSED_AND_WHITESPACE]) ) { if (!Preg::match('/'.implode('|', array_keys($escapeSequences)).'/', $content)) { continue; } $previousToken = $tokens[$index - 1]; $stringTypeChanged = false; $swapQuotes = false; if ($previousToken->isGivenKind(\T_START_HEREDOC)) { $previousTokenContent = $previousToken->getContent(); if (str_contains($previousTokenContent, '\'')) { $tokens[$index - 1] = new Token([\T_START_HEREDOC, str_replace('\'', '', $previousTokenContent)]); $stringTypeChanged = true; } } elseif (str_starts_with($content, "'")) { $stringTypeChanged = true; $swapQuotes = true; } if ($swapQuotes) { $content = str_replace("\\'", "'", $content); } if ($stringTypeChanged) { $content = Preg::replace('/(\\\{1,2})/', '\\\\\\\\', $content); $content = str_replace('$', '\$', $content); } if ($swapQuotes) { $content = str_replace('"', '\"', $content); $content = Preg::replace('/^\'(.*)\'$/s', '"$1"', $content); } $tokens[$index] = new Token([$token->getId(), strtr($content, $escapeSequences)]); continue; } if ($token->isGivenKind(self::TOKENS)) { $newContent = strtr($content, $replacements); // variable name cannot contain space if ($token->isGivenKind([\T_STRING_VARNAME, \T_VARIABLE]) && str_contains($newContent, ' ')) { continue; } // multiline comment must have "*/" only at the end if ($token->isGivenKind([\T_COMMENT, \T_DOC_COMMENT]) && str_starts_with($newContent, '/*') && strpos($newContent, '*/') !== \strlen($newContent) - 2) { continue; } $tokens[$index] = new Token([$token->getId(), $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/Basic/NumericLiteralSeparatorFixer.php
src/Fixer/Basic/NumericLiteralSeparatorFixer.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\Basic; 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; /** * Let's you add underscores to numeric literals. * * Inspired by: * - {@link https://github.com/kubawerlos/php-cs-fixer-custom-fixers/blob/main/src/Fixer/NumericLiteralSeparatorFixer.php} * - {@link https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/rules/numeric-separators-style.js} * * @phpstan-type _AutogeneratedInputConfiguration array{ * override_existing?: bool, * strategy?: 'no_separator'|'use_separator', * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * override_existing: bool, * strategy: 'no_separator'|'use_separator', * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @author Marvin Heilemann <marvin.heilemann+github@googlemail.com> * @author Greg Korba <greg@codito.dev> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NumericLiteralSeparatorFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; public const STRATEGY_USE_SEPARATOR = 'use_separator'; public const STRATEGY_NO_SEPARATOR = 'no_separator'; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Adds separators to numeric literals of any kind.', [ new CodeSample( <<<'PHP' <?php $integer = 1234567890; PHP, ), new CodeSample( <<<'PHP' <?php $integer = 1234_5678; $octal = 01_234_56; $binary = 0b00_10_01_00; $hexadecimal = 0x3D45_8F4F; PHP, ['strategy' => self::STRATEGY_NO_SEPARATOR], ), new CodeSample( <<<'PHP' <?php $integer = 12345678; $octal = 0123456; $binary = 0b0010010011011010; $hexadecimal = 0x3D458F4F; PHP, ['strategy' => self::STRATEGY_USE_SEPARATOR], ), new CodeSample( "<?php \$var = 24_40_21;\n", ['override_existing' => true], ), ], ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound([\T_DNUMBER, \T_LNUMBER]); } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder( 'override_existing', 'Whether literals already containing underscores should be reformatted.', )) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), (new FixerOptionBuilder( 'strategy', 'Whether numeric literal should be separated by underscores or not.', )) ->setAllowedValues([self::STRATEGY_USE_SEPARATOR, self::STRATEGY_NO_SEPARATOR]) ->setDefault(self::STRATEGY_USE_SEPARATOR) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ($tokens as $index => $token) { if (!$token->isGivenKind([\T_DNUMBER, \T_LNUMBER])) { continue; } $content = $token->getContent(); $newContent = $this->formatValue($content); if ($content === $newContent) { // Skip Token override if its the same content, like when it // already got a valid literal separator structure. continue; } $tokens[$index] = new Token([$token->getId(), $newContent]); } } private function formatValue(string $value): string { if (self::STRATEGY_NO_SEPARATOR === $this->configuration['strategy']) { return str_contains($value, '_') ? str_replace('_', '', $value) : $value; } if (true === $this->configuration['override_existing']) { $value = str_replace('_', '', $value); } elseif (str_contains($value, '_')) { // Keep already underscored literals untouched. return $value; } $lowerValue = strtolower($value); if (str_starts_with($lowerValue, '0b')) { // Binary return $this->insertEveryRight($value, 8, 2); } if (str_starts_with($lowerValue, '0x')) { // Hexadecimal return $this->insertEveryRight($value, 2, 2); } if (str_starts_with($lowerValue, '0o')) { // Octal return $this->insertEveryRight($value, 3, 2); } if (str_starts_with($lowerValue, '0') && !str_contains($lowerValue, '.')) { // Octal notation prior PHP 8.1 but still valid return $this->insertEveryRight($value, 3, 1); } // All other types /** If its a negative value we need an offset */ $negativeOffset = static fn (string $v): int => str_contains($v, '-') ? 1 : 0; Preg::matchAll('/([0-9-_]+)?((\.)([0-9_]*))?((e)([0-9-_]+))?/i', $value, $result); $integer = $result[1][0]; $joinedValue = $this->insertEveryRight($integer, 3, $negativeOffset($integer)); $dot = $result[3][0]; if ('' !== $dot) { $integer = $result[4][0]; $decimal = $this->insertEveryLeft($integer, 3, $negativeOffset($integer)); $joinedValue = $joinedValue.$dot.$decimal; } $tim = $result[6][0]; if ('' !== $tim) { $integer = $result[7][0]; $times = $this->insertEveryRight($integer, 3, $negativeOffset($integer)); $joinedValue = $joinedValue.$tim.$times; } return $joinedValue; } private function insertEveryRight(string $value, int $length, int $offset = 0): string { $position = $length * -1; while ($position > -(\strlen($value) - $offset)) { $value = substr_replace($value, '_', $position, 0); $position -= $length + 1; } return $value; } private function insertEveryLeft(string $value, int $length, int $offset = 0): string { $position = $length; while ($position < \strlen($value)) { $value = substr_replace($value, '_', $position, $offset); $position += $length + 1; } return $value; } }
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/Basic/PsrAutoloadingFixer.php
src/Fixer/Basic/PsrAutoloadingFixer.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\Basic; use PhpCsFixer\AbstractFixer; use PhpCsFixer\DocBlock\TypeExpression; use PhpCsFixer\Fixer\ConfigurableFixerInterface; use PhpCsFixer\Fixer\ConfigurableFixerTrait; use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; use PhpCsFixer\FixerDefinition\FileSpecificCodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Preg; use PhpCsFixer\StdinFileInfo; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; use PhpCsFixer\Tokenizer\TokensAnalyzer; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * dir?: null|string, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * dir: null|string, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @author Jordi Boggiano <j.boggiano@seld.be> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * @author Bram Gotink <bram@gotink.me> * @author Graham Campbell <hello@gjcampbell.co.uk> * @author Kuba Werłos <werlos@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PsrAutoloadingFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Classes must be in a path that matches their namespace, be at least one namespace deep and the class name should match the file name.', [ new FileSpecificCodeSample( <<<'PHP' <?php namespace PhpCsFixer\FIXER\Basic; class InvalidName {} PHP, new \SplFileInfo(__FILE__), ), new FileSpecificCodeSample( <<<'PHP' <?php namespace PhpCsFixer\FIXER\Basic; class InvalidName {} PHP, new \SplFileInfo(__FILE__), ['dir' => './src'], ), ], null, 'This fixer may change your class name, which will break the code that depends on the old name.', ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); } public function isRisky(): bool { return true; } /** * {@inheritdoc} * * Must run before SelfAccessorFixer. */ public function getPriority(): int { return -10; } public function supports(\SplFileInfo $file): bool { if ($file instanceof StdinFileInfo) { return false; } if ( // ignore file with extension other than php ('php' !== $file->getExtension()) // ignore file with name that cannot be a class name || !Preg::match('/^'.TypeExpression::REGEX_IDENTIFIER.'$/', $file->getBasename('.php')) ) { return false; } try { $tokens = Tokens::fromCode(\sprintf('<?php class %s {}', $file->getBasename('.php'))); if ($tokens[3]->isKeyword() || $tokens[3]->isMagicConstant()) { // name cannot be a class name - detected by PHP 5.x return false; } } catch (\ParseError $e) { // name cannot be a class name - detected by PHP 7.x return false; } // ignore stubs/fixtures, since they typically contain invalid files for various reasons return !Preg::match('{[/\\\](stub|fixture)s?[/\\\]}i', $file->getRealPath()); } protected function configurePostNormalisation(): void { if (null !== $this->configuration['dir']) { $realpath = realpath($this->configuration['dir']); if (false === $realpath) { throw new \InvalidArgumentException(\sprintf('Failed to resolve configured directory "%s".', $this->configuration['dir'])); } $this->configuration['dir'] = $realpath; } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('dir', 'If provided, the directory where the project code is placed.')) ->setAllowedTypes(['null', 'string']) ->setDefault(null) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $tokenAnalyzer = new TokensAnalyzer($tokens); if (null !== $this->configuration['dir'] && !str_starts_with($file->getRealPath(), $this->configuration['dir'])) { return; } $namespace = null; $namespaceStartIndex = null; $namespaceEndIndex = null; $classyName = null; $classyIndex = null; foreach ($tokens as $index => $token) { if ($token->isGivenKind(\T_NAMESPACE)) { if (null !== $namespace) { return; } $namespaceStartIndex = $tokens->getNextMeaningfulToken($index); $namespaceEndIndex = $tokens->getNextTokenOfKind($namespaceStartIndex, [';']); $namespace = trim($tokens->generatePartialCode($namespaceStartIndex, $namespaceEndIndex - 1)); } elseif ($token->isClassy()) { if ($tokenAnalyzer->isAnonymousClass($index)) { continue; } if (null !== $classyName) { return; } $classyIndex = $tokens->getNextMeaningfulToken($index); $classyName = $tokens[$classyIndex]->getContent(); } } if (null === $classyName) { return; } $expectedClassyName = $this->calculateClassyName($file, $namespace, $classyName); if ($classyName !== $expectedClassyName) { $tokens[$classyIndex] = new Token([\T_STRING, $expectedClassyName]); } if (null === $this->configuration['dir'] || null === $namespace) { return; } if (!is_dir($this->configuration['dir'])) { return; } $configuredDir = realpath($this->configuration['dir']); $fileDir = \dirname($file->getRealPath()); if (\strlen($configuredDir) >= \strlen($fileDir)) { return; } $newNamespace = substr(str_replace('/', '\\', $fileDir), \strlen($configuredDir) + 1); $originalNamespace = substr($namespace, -\strlen($newNamespace)); if ($originalNamespace !== $newNamespace && strtolower($originalNamespace) === strtolower($newNamespace)) { $tokens->clearRange($namespaceStartIndex, $namespaceEndIndex); $namespace = substr($namespace, 0, -\strlen($newNamespace)).$newNamespace; $newNamespace = Tokens::fromCode('<?php namespace '.$namespace.';'); $newNamespace->clearRange(0, 2); $newNamespace->clearEmptyTokens(); $tokens->insertAt($namespaceStartIndex, $newNamespace); } } private function calculateClassyName(\SplFileInfo $file, ?string $namespace, string $currentName): string { $name = $file->getBasename('.php'); $maxNamespace = $this->calculateMaxNamespace($file, $namespace); if (null !== $this->configuration['dir']) { return ('' !== $maxNamespace ? (str_replace('\\', '_', $maxNamespace).'_') : '').$name; } $namespaceParts = array_reverse(explode('\\', $maxNamespace)); foreach ($namespaceParts as $namespacePart) { $nameCandidate = \sprintf('%s_%s', $namespacePart, $name); if (strtolower($nameCandidate) !== strtolower(substr($currentName, -\strlen($nameCandidate)))) { break; } $name = $nameCandidate; } return $name; } private function calculateMaxNamespace(\SplFileInfo $file, ?string $namespace): string { if (null === $this->configuration['dir']) { $root = \dirname($file->getRealPath()); while ($root !== \dirname($root)) { $root = \dirname($root); } } else { $root = realpath($this->configuration['dir']); } $namespaceAccordingToFileLocation = trim(str_replace(\DIRECTORY_SEPARATOR, '\\', substr(\dirname($file->getRealPath()), \strlen($root))), '\\'); if (null === $namespace) { return $namespaceAccordingToFileLocation; } $namespaceAccordingToFileLocationPartsReversed = array_reverse(explode('\\', $namespaceAccordingToFileLocation)); $namespacePartsReversed = array_reverse(explode('\\', $namespace)); foreach ($namespacePartsReversed as $key => $namespaceParte) { if (!isset($namespaceAccordingToFileLocationPartsReversed[$key])) { break; } if (strtolower($namespaceParte) !== strtolower($namespaceAccordingToFileLocationPartsReversed[$key])) { break; } unset($namespaceAccordingToFileLocationPartsReversed[$key]); } return implode('\\', array_reverse($namespaceAccordingToFileLocationPartsReversed)); } }
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/Basic/OctalNotationFixer.php
src/Fixer/Basic/OctalNotationFixer.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\Basic; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\FixerDefinition\VersionSpecification; use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; 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 OctalNotationFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Literal octal must be in `0o` notation.', [ new VersionSpecificCodeSample( "<?php \$foo = 0123;\n", new VersionSpecification(8_01_00), ), ], ); } public function isCandidate(Tokens $tokens): bool { return \PHP_VERSION_ID >= 8_01_00 && $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::replace('#^0_*+([0-7_]+)$#', '0o$1', $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/Basic/SingleLineEmptyBodyFixer.php
src/Fixer/Basic/SingleLineEmptyBodyFixer.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\Basic; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; 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 SingleLineEmptyBodyFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Empty body of class, interface, trait, enum or function must be abbreviated as `{}` and placed on the same line as the previous symbol, separated by a single space.', [ new CodeSample( <<<'PHP' <?php function foo( int $x ) { } PHP, ), ], ); } /** * {@inheritdoc} * * Must run after BracesPositionFixer, ClassDefinitionFixer, CurlyBracesPositionFixer, NoUselessReturnFixer. */ public function getPriority(): int { return -19; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound([\T_INTERFACE, \T_CLASS, \T_FUNCTION, \T_TRAIT, FCT::T_ENUM]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { for ($index = $tokens->count() - 1; $index > 0; --$index) { if (!$tokens[$index]->isGivenKind([...Token::getClassyTokenKinds(), \T_FUNCTION])) { continue; } $openBraceIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); if (!$tokens[$openBraceIndex]->equals('{')) { continue; } $closeBraceIndex = $tokens->getNextNonWhitespace($openBraceIndex); if (!$tokens[$closeBraceIndex]->equals('}')) { continue; } $tokens->ensureWhitespaceAtIndex($openBraceIndex + 1, 0, ''); $beforeOpenBraceIndex = $tokens->getPrevNonWhitespace($openBraceIndex); if (!$tokens[$beforeOpenBraceIndex]->isGivenKind([\T_COMMENT, \T_DOC_COMMENT])) { $tokens->ensureWhitespaceAtIndex($openBraceIndex - 1, 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/Basic/BracesFixer.php
src/Fixer/Basic/BracesFixer.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\Basic; use PhpCsFixer\AbstractProxyFixer; use PhpCsFixer\Fixer\ConfigurableFixerInterface; use PhpCsFixer\Fixer\ConfigurableFixerTrait; use PhpCsFixer\Fixer\ControlStructure\ControlStructureBracesFixer; use PhpCsFixer\Fixer\ControlStructure\ControlStructureContinuationPositionFixer; use PhpCsFixer\Fixer\DeprecatedFixerInterface; use PhpCsFixer\Fixer\LanguageConstruct\DeclareParenthesesFixer; use PhpCsFixer\Fixer\LanguageConstruct\SingleSpaceAroundConstructFixer; use PhpCsFixer\Fixer\Whitespace\NoExtraBlankLinesFixer; use PhpCsFixer\Fixer\Whitespace\StatementIndentationFixer; 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; /** * Fixer for rules defined in PSR2 ¶4.1, ¶4.4, ¶5. * * @deprecated * * @phpstan-type _AutogeneratedInputConfiguration array{ * allow_single_line_anonymous_class_with_empty_body?: bool, * allow_single_line_closure?: bool, * position_after_anonymous_constructs?: 'next'|'same', * position_after_control_structures?: 'next'|'same', * position_after_functions_and_oop_constructs?: 'next'|'same', * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * allow_single_line_anonymous_class_with_empty_body: bool, * allow_single_line_closure: bool, * position_after_anonymous_constructs: 'next'|'same', * position_after_control_structures: 'next'|'same', * position_after_functions_and_oop_constructs: 'next'|'same', * } * * @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 BracesFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface, DeprecatedFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; /** * @internal */ public const LINE_NEXT = 'next'; /** * @internal */ public const LINE_SAME = 'same'; private ?BracesPositionFixer $bracesPositionFixer = null; private ?ControlStructureContinuationPositionFixer $controlStructureContinuationPositionFixer = null; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'The body of each structure MUST be enclosed by braces. Braces should be properly placed. Body of braces should be properly indented.', [ new CodeSample( <<<'PHP' <?php class Foo { public function bar($baz) { if ($baz = 900) echo "Hello!"; if ($baz = 9000) echo "Wait!"; if ($baz == true) { echo "Why?"; } else { echo "Ha?"; } if (is_array($baz)) foreach ($baz as $b) { echo $b; } } } PHP, ), new CodeSample( <<<'PHP' <?php $positive = function ($item) { return $item >= 0; }; $negative = function ($item) { return $item < 0; }; PHP, ['allow_single_line_closure' => true], ), new CodeSample( <<<'PHP' <?php class Foo { public function bar($baz) { if ($baz = 900) echo "Hello!"; if ($baz = 9000) echo "Wait!"; if ($baz == true) { echo "Why?"; } else { echo "Ha?"; } if (is_array($baz)) foreach ($baz as $b) { echo $b; } } } PHP, ['position_after_functions_and_oop_constructs' => self::LINE_SAME], ), ], ); } /** * {@inheritdoc} * * Must run before HeredocIndentationFixer. * Must run after ClassAttributesSeparationFixer, ClassDefinitionFixer, EmptyLoopBodyFixer, NoAlternativeSyntaxFixer, NoEmptyStatementFixer, NoUselessElseFixer, SingleLineThrowFixer, SingleSpaceAfterConstructFixer, SingleSpaceAroundConstructFixer, SingleTraitInsertPerStatementFixer. */ public function getPriority(): int { return 35; } public function getSuccessorsNames(): array { return array_keys($this->proxyFixers); } protected function configurePostNormalisation(): void { $this->getBracesPositionFixer()->configure([ 'control_structures_opening_brace' => $this->translatePositionOption($this->configuration['position_after_control_structures']), 'functions_opening_brace' => $this->translatePositionOption($this->configuration['position_after_functions_and_oop_constructs']), 'anonymous_functions_opening_brace' => $this->translatePositionOption($this->configuration['position_after_anonymous_constructs']), 'classes_opening_brace' => $this->translatePositionOption($this->configuration['position_after_functions_and_oop_constructs']), 'anonymous_classes_opening_brace' => $this->translatePositionOption($this->configuration['position_after_anonymous_constructs']), 'allow_single_line_empty_anonymous_classes' => $this->configuration['allow_single_line_anonymous_class_with_empty_body'], 'allow_single_line_anonymous_functions' => $this->configuration['allow_single_line_closure'], ]); $this->getControlStructureContinuationPositionFixer()->configure([ 'position' => self::LINE_NEXT === $this->configuration['position_after_control_structures'] ? ControlStructureContinuationPositionFixer::NEXT_LINE : ControlStructureContinuationPositionFixer::SAME_LINE, ]); } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('allow_single_line_anonymous_class_with_empty_body', 'Whether single line anonymous class with empty body notation should be allowed.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), (new FixerOptionBuilder('allow_single_line_closure', 'Whether single line lambda notation should be allowed.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), (new FixerOptionBuilder('position_after_functions_and_oop_constructs', 'Whether the opening brace should be placed on "next" or "same" line after classy constructs (non-anonymous classes, interfaces, traits, methods and non-lambda functions).')) ->setAllowedValues([self::LINE_NEXT, self::LINE_SAME]) ->setDefault(self::LINE_NEXT) ->getOption(), (new FixerOptionBuilder('position_after_control_structures', 'Whether the opening brace should be placed on "next" or "same" line after control structures.')) ->setAllowedValues([self::LINE_NEXT, self::LINE_SAME]) ->setDefault(self::LINE_SAME) ->getOption(), (new FixerOptionBuilder('position_after_anonymous_constructs', 'Whether the opening brace should be placed on "next" or "same" line after anonymous constructs (anonymous classes and lambda functions).')) ->setAllowedValues([self::LINE_NEXT, self::LINE_SAME]) ->setDefault(self::LINE_SAME) ->getOption(), ]); } protected function createProxyFixers(): array { $singleSpaceAroundConstructFixer = new SingleSpaceAroundConstructFixer(); $singleSpaceAroundConstructFixer->configure([ 'constructs_contain_a_single_space' => [], 'constructs_followed_by_a_single_space' => ['elseif', 'for', 'foreach', 'if', 'match', 'while', 'use_lambda'], 'constructs_preceded_by_a_single_space' => ['use_lambda'], ]); $noExtraBlankLinesFixer = new NoExtraBlankLinesFixer(); $noExtraBlankLinesFixer->configure([ 'tokens' => ['curly_brace_block'], ]); return [ $singleSpaceAroundConstructFixer, new ControlStructureBracesFixer(), $noExtraBlankLinesFixer, $this->getBracesPositionFixer(), $this->getControlStructureContinuationPositionFixer(), new DeclareParenthesesFixer(), new NoMultipleStatementsPerLineFixer(), new StatementIndentationFixer(true), ]; } private function getBracesPositionFixer(): BracesPositionFixer { if (null === $this->bracesPositionFixer) { $this->bracesPositionFixer = new BracesPositionFixer(); } return $this->bracesPositionFixer; } private function getControlStructureContinuationPositionFixer(): ControlStructureContinuationPositionFixer { if (null === $this->controlStructureContinuationPositionFixer) { $this->controlStructureContinuationPositionFixer = new ControlStructureContinuationPositionFixer(); } return $this->controlStructureContinuationPositionFixer; } /** * @return BracesPositionFixer::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END|BracesPositionFixer::SAME_LINE */ private function translatePositionOption(string $option): string { return self::LINE_NEXT === $option ? BracesPositionFixer::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END : BracesPositionFixer::SAME_LINE; } }
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/FunctionNotation/ReturnTypeDeclarationFixer.php
src/Fixer/FunctionNotation/ReturnTypeDeclarationFixer.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\FunctionNotation; 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{ * space_before?: 'none'|'one', * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * space_before: 'none'|'one', * } * * @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 ReturnTypeDeclarationFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Adjust spacing around colon in return type declarations and backed enum types.', [ new CodeSample( "<?php\nfunction foo(int \$a):string {};\n", ), new CodeSample( "<?php\nfunction foo(int \$a):string {};\n", ['space_before' => 'none'], ), new CodeSample( "<?php\nfunction foo(int \$a):string {};\n", ['space_before' => 'one'], ), ], ); } /** * {@inheritdoc} * * Must run after PhpUnitDataProviderReturnTypeFixer, PhpdocToReturnTypeFixer, VoidReturnFixer. */ public function getPriority(): int { return -17; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(CT::T_TYPE_COLON); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $oneSpaceBefore = 'one' === $this->configuration['space_before']; for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) { if (!$tokens[$index]->isGivenKind(CT::T_TYPE_COLON)) { continue; } $previousIndex = $index - 1; $previousToken = $tokens[$previousIndex]; if ($previousToken->isWhitespace()) { if (!$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) { if ($oneSpaceBefore) { $tokens[$previousIndex] = new Token([\T_WHITESPACE, ' ']); } else { $tokens->clearAt($previousIndex); } } } elseif ($oneSpaceBefore) { $tokenWasAdded = $tokens->ensureWhitespaceAtIndex($index, 0, ' '); if ($tokenWasAdded) { ++$limit; } ++$index; } ++$index; $tokenWasAdded = $tokens->ensureWhitespaceAtIndex($index, 0, ' '); if ($tokenWasAdded) { ++$limit; } } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('space_before', 'Spacing to apply before colon.')) ->setAllowedValues(['one', 'none']) ->setDefault('none') ->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/FunctionNotation/DateTimeCreateFromFormatCallFixer.php
src/Fixer/FunctionNotation/DateTimeCreateFromFormatCallFixer.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\FunctionNotation; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DateTimeCreateFromFormatCallFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'The first argument of `DateTime::createFromFormat` method must start with `!`.', [ new CodeSample("<?php \\DateTime::createFromFormat('Y-m-d', '2022-02-11');\n"), ], "Consider this code: `DateTime::createFromFormat('Y-m-d', '2022-02-11')`. What value will be returned? '2022-02-11 00:00:00.0'? No, actual return value has 'H:i:s' section like '2022-02-11 16:55:37.0'. Change 'Y-m-d' to '!Y-m-d', return value will be '2022-02-11 00:00:00.0'. So, adding `!` to format string will make return value more intuitive.", 'Risky when depending on the actual timings being used even when not explicit set in format.', ); } /** * {@inheritdoc} * * Must run after NoUselessConcatOperatorFixer. */ public function getPriority(): int { return 0; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOUBLE_COLON); } public function isRisky(): bool { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $argumentsAnalyzer = new ArgumentsAnalyzer(); $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer(); foreach ($tokens->getNamespaceDeclarations() as $namespace) { $scopeStartIndex = $namespace->getScopeStartIndex(); $useDeclarations = $namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace); for ($index = $namespace->getScopeEndIndex(); $index > $scopeStartIndex; --$index) { if (!$tokens[$index]->isGivenKind(\T_DOUBLE_COLON)) { continue; } $functionNameIndex = $tokens->getNextMeaningfulToken($index); if (!$tokens[$functionNameIndex]->equals([\T_STRING, 'createFromFormat'], false)) { continue; } if (!$tokens[$tokens->getNextMeaningfulToken($functionNameIndex)]->equals('(')) { continue; } $classNameIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$classNameIndex]->equalsAny([[\T_STRING, \DateTime::class], [\T_STRING, \DateTimeImmutable::class]], false)) { continue; } $preClassNameIndex = $tokens->getPrevMeaningfulToken($classNameIndex); if ($tokens[$preClassNameIndex]->isGivenKind(\T_NS_SEPARATOR)) { if ($tokens[$tokens->getPrevMeaningfulToken($preClassNameIndex)]->isGivenKind(\T_STRING)) { continue; } } elseif (!$namespace->isGlobalNamespace()) { continue; } else { foreach ($useDeclarations as $useDeclaration) { foreach (['datetime', 'datetimeimmutable'] as $name) { if ($name === strtolower($useDeclaration->getShortName()) && $name !== strtolower($useDeclaration->getFullName())) { continue 3; } } } } $openIndex = $tokens->getNextTokenOfKind($functionNameIndex, ['(']); $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); $argumentIndex = $this->getFirstArgumentTokenIndex($tokens, $argumentsAnalyzer->getArguments($tokens, $openIndex, $closeIndex)); if (null === $argumentIndex) { continue; } $format = $tokens[$argumentIndex]->getContent(); if (\strlen($format) < 3) { continue; } $offset = 'b' === $format[0] || 'B' === $format[0] ? 2 : 1; if ('!' === $format[$offset]) { continue; } $tokens->clearAt($argumentIndex); $tokens->insertAt($argumentIndex, new Token([\T_CONSTANT_ENCAPSED_STRING, substr_replace($format, '!', $offset, 0)])); } } } /** * @param array<int, int> $arguments */ private function getFirstArgumentTokenIndex(Tokens $tokens, array $arguments): ?int { if (2 !== \count($arguments)) { return null; } $argumentStartIndex = array_key_first($arguments); $argumentEndIndex = $arguments[$argumentStartIndex]; $argumentStartIndex = $tokens->getNextMeaningfulToken($argumentStartIndex - 1); if ( $argumentStartIndex !== $argumentEndIndex && $tokens->getNextMeaningfulToken($argumentStartIndex) <= $argumentEndIndex ) { return null; // argument is not a simple single string } return !$tokens[$argumentStartIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING) ? null // first argument is not a string : $argumentStartIndex; } }
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/FunctionNotation/NoUnreachableDefaultArgumentValueFixer.php
src/Fixer/FunctionNotation/NoUnreachableDefaultArgumentValueFixer.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\FunctionNotation; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Tokens; /** * @author Mark Scherer * @author Lucas Manzke <lmanzke@outlook.com> * @author Gregor Harlan <gharlan@web.de> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NoUnreachableDefaultArgumentValueFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'In function arguments there must not be arguments with default values before non-default ones.', [ new CodeSample( <<<'PHP' <?php function example($foo = "two words", $bar) {} PHP, ), ], null, 'Modifies the signature of functions; therefore risky when using systems (such as some Symfony components) that rely on those (for example through reflection).', ); } /** * {@inheritdoc} * * Must run after NullableTypeDeclarationForDefaultNullValueFixer. */ public function getPriority(): int { return 0; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); } public function isRisky(): bool { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $functionKinds = [\T_FUNCTION, \T_FN]; for ($i = 0, $l = $tokens->count(); $i < $l; ++$i) { if (!$tokens[$i]->isGivenKind($functionKinds)) { continue; } $startIndex = $tokens->getNextTokenOfKind($i, ['(']); $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex); $this->fixFunctionDefinition($tokens, $startIndex, $i); } } private function fixFunctionDefinition(Tokens $tokens, int $startIndex, int $endIndex): void { $lastArgumentIndex = $this->getLastNonDefaultArgumentIndex($tokens, $startIndex, $endIndex); if (null === $lastArgumentIndex) { return; } for ($i = $lastArgumentIndex; $i > $startIndex; --$i) { $token = $tokens[$i]; if ($token->isGivenKind(\T_VARIABLE)) { $lastArgumentIndex = $i; continue; } if ($token->isGivenKind(CT::T_PROPERTY_HOOK_BRACE_CLOSE)) { $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PROPERTY_HOOK, $i); continue; } if (!$token->equals('=') || $this->isNonNullableTypehintedNullableVariable($tokens, $i)) { continue; } $this->removeDefaultValue($tokens, $i, $this->getDefaultValueEndIndex($tokens, $lastArgumentIndex)); } } private function getLastNonDefaultArgumentIndex(Tokens $tokens, int $startIndex, int $endIndex): ?int { for ($i = $endIndex - 1; $i > $startIndex; --$i) { $token = $tokens[$i]; if ($token->equals('=')) { $i = $tokens->getPrevMeaningfulToken($i); continue; } if ($token->isGivenKind(CT::T_PROPERTY_HOOK_BRACE_CLOSE)) { $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PROPERTY_HOOK, $i); continue; } if ($token->isGivenKind(\T_VARIABLE) && !$tokens[$tokens->getPrevMeaningfulToken($i)]->isGivenKind(\T_ELLIPSIS)) { return $i; } } return null; } private function getDefaultValueEndIndex(Tokens $tokens, int $index): int { do { $index = $tokens->getPrevMeaningfulToken($index); if ($tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); } } while (!$tokens[$index]->equals(',')); return $tokens->getPrevMeaningfulToken($index); } private function removeDefaultValue(Tokens $tokens, int $startIndex, int $endIndex): void { for ($i = $startIndex; $i <= $endIndex;) { $tokens->clearTokenAndMergeSurroundingWhitespace($i); $this->clearWhitespacesBeforeIndex($tokens, $i); $i = $tokens->getNextMeaningfulToken($i); } } /** * @param int $index Index of "=" */ private function isNonNullableTypehintedNullableVariable(Tokens $tokens, int $index): bool { $nextToken = $tokens[$tokens->getNextMeaningfulToken($index)]; if (!$nextToken->equals([\T_STRING, 'null'], false)) { return false; } $variableIndex = $tokens->getPrevMeaningfulToken($index); $searchTokens = [',', '(', [\T_STRING], [CT::T_ARRAY_TYPEHINT], [\T_CALLABLE]]; $typehintKinds = [\T_STRING, CT::T_ARRAY_TYPEHINT, \T_CALLABLE]; $prevIndex = $tokens->getPrevTokenOfKind($variableIndex, $searchTokens); if (!$tokens[$prevIndex]->isGivenKind($typehintKinds)) { return false; } return !$tokens[$tokens->getPrevMeaningfulToken($prevIndex)]->isGivenKind(CT::T_NULLABLE_TYPE); } private function clearWhitespacesBeforeIndex(Tokens $tokens, int $index): void { $prevIndex = $tokens->getNonEmptySibling($index, -1); if (!$tokens[$prevIndex]->isWhitespace()) { return; } $prevNonWhiteIndex = $tokens->getPrevNonWhitespace($prevIndex); if (null === $prevNonWhiteIndex || !$tokens[$prevNonWhiteIndex]->isComment()) { $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); } } }
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/FunctionNotation/MultilinePromotedPropertiesFixer.php
src/Fixer/FunctionNotation/MultilinePromotedPropertiesFixer.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\FunctionNotation; use PhpCsFixer\AbstractFixer; use PhpCsFixer\Fixer\ConfigurableFixerInterface; use PhpCsFixer\Fixer\ConfigurableFixerTrait; use PhpCsFixer\Fixer\ExperimentalFixerInterface; use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; 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\WhitespacesAnalyzer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Tokens; use PhpCsFixer\Tokenizer\TokensAnalyzer; /** * @phpstan-type _InputConfig array{keep_blank_lines?: bool, minimum_number_of_parameters?: int} * @phpstan-type _Config array{keep_blank_lines: bool, minimum_number_of_parameters: int} * @phpstan-type _AutogeneratedInputConfiguration array{ * keep_blank_lines?: bool, * minimum_number_of_parameters?: int, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * keep_blank_lines: bool, * minimum_number_of_parameters: int, * } * @phpstan-type _ConstructorAnalysis array{ * index?: int, * parameter_names: list<string>, * promotable_parameters: array<int, string>, * constructor_index?: int, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @TODO align on default configuration and remove experimental flag - https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/issues/8718 * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class MultilinePromotedPropertiesFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface, ExperimentalFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Promoted properties must be on separate lines.', [ new VersionSpecificCodeSample( <<<'PHP' <?php class Foo { public function __construct(private array $a, private bool $b, private int $i) {} } PHP, new VersionSpecification(80_000), ), new VersionSpecificCodeSample( <<<'PHP' <?php class Foo { public function __construct(private array $a, private bool $b, private int $i) {} } class Bar { public function __construct(private array $x) {} } PHP, new VersionSpecification(80_000), ['minimum_number_of_parameters' => 3], ), ], ); } /** * {@inheritdoc} * * Must run before BracesPositionFixer, TrailingCommaInMultilineFixer. */ public function getPriority(): int { return 1; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound([ CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, ]); } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('keep_blank_lines', 'Whether to keep blank lines between properties.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), (new FixerOptionBuilder('minimum_number_of_parameters', 'Minimum number of parameters in the constructor to fix.')) ->setAllowedTypes(['int']) ->setDefault(1) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $tokensAnalyzer = new TokensAnalyzer($tokens); foreach ($tokensAnalyzer->getClassyElements() as $index => $element) { if ('method' !== $element['type']) { continue; } $openParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(']); $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesisIndex); if (!$this->shouldBeFixed($tokens, $openParenthesisIndex, $closeParenthesisIndex)) { continue; } $this->fixParameters($tokens, $openParenthesisIndex, $closeParenthesisIndex); } } private function shouldBeFixed(Tokens $tokens, int $openParenthesisIndex, int $closeParenthesisIndex): bool { $promotedParameterFound = false; $minimumNumberOfParameters = 0; for ($index = $openParenthesisIndex + 1; $index < $closeParenthesisIndex; ++$index) { if ($tokens[$index]->isGivenKind(\T_VARIABLE)) { ++$minimumNumberOfParameters; } if ( $tokens[$index]->isGivenKind([ CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, ]) ) { $promotedParameterFound = true; } } return $promotedParameterFound && $minimumNumberOfParameters >= $this->configuration['minimum_number_of_parameters']; } private function fixParameters(Tokens $tokens, int $openParenthesis, int $closeParenthesis): void { $indent = WhitespacesAnalyzer::detectIndent($tokens, $openParenthesis); $tokens->ensureWhitespaceAtIndex( $closeParenthesis - 1, 1, $this->whitespacesConfig->getLineEnding().$indent, ); $index = $tokens->getPrevMeaningfulToken($closeParenthesis); \assert(\is_int($index)); while ($index > $openParenthesis) { $index = $tokens->getPrevMeaningfulToken($index); \assert(\is_int($index)); $blockType = Tokens::detectBlockType($tokens[$index]); if (null !== $blockType && !$blockType['isStart']) { $index = $tokens->findBlockStart($blockType['type'], $index); continue; } if (!$tokens[$index]->equalsAny(['(', ','])) { continue; } $this->fixParameter($tokens, $index + 1, $indent); } } private function fixParameter(Tokens $tokens, int $index, string $indent): void { if ($this->configuration['keep_blank_lines'] && $tokens[$index]->isWhitespace() && str_contains($tokens[$index]->getContent(), "\n")) { return; } $tokens->ensureWhitespaceAtIndex( $index, 0, $this->whitespacesConfig->getLineEnding().$indent.$this->whitespacesConfig->getIndent(), ); } }
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/FunctionNotation/NullableTypeDeclarationForDefaultNullValueFixer.php
src/Fixer/FunctionNotation/NullableTypeDeclarationForDefaultNullValueFixer.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\FunctionNotation; 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\Tokenizer\Analyzer\Analysis\ArgumentAnalysis; 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; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * use_nullable_type_declaration?: bool, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * use_nullable_type_declaration: 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 NullableTypeDeclarationForDefaultNullValueFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; private const CONSTRUCTOR_PROPERTY_MODIFIERS = [ CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, FCT::T_PUBLIC_SET, FCT::T_PROTECTED_SET, FCT::T_PRIVATE_SET, FCT::T_READONLY, ]; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Adds or removes `?` before single type declarations or `|null` at the end of union types when parameters have a default `null` value.', [ new CodeSample( "<?php\nfunction sample(string \$str = null)\n{}\n", ), new CodeSample( "<?php\nfunction sample(?string \$str = null)\n{}\n", ['use_nullable_type_declaration' => false], ), new VersionSpecificCodeSample( "<?php\nfunction sample(string|int \$str = null)\n{}\n", new VersionSpecification(8_00_00), ), new VersionSpecificCodeSample( "<?php\nfunction sample(string|int|null \$str = null)\n{}\n", new VersionSpecification(8_00_00), ['use_nullable_type_declaration' => false], ), new VersionSpecificCodeSample( "<?php\nfunction sample(\\Foo&\\Bar \$str = null)\n{}\n", new VersionSpecification(8_02_00), ), new VersionSpecificCodeSample( "<?php\nfunction sample((\\Foo&\\Bar)|null \$str = null)\n{}\n", new VersionSpecification(8_02_00), ['use_nullable_type_declaration' => false], ), ], ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_VARIABLE) && $tokens->isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); } /** * {@inheritdoc} * * Must run before NoUnreachableDefaultArgumentValueFixer, NullableTypeDeclarationFixer, OrderedTypesFixer. */ public function getPriority(): int { return 3; } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('use_nullable_type_declaration', 'Whether to add or remove `?` or `|null` to parameters with a default `null` value.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->setDeprecationMessage('Behaviour will follow default one.') // @TODO remove the option on next major 4.0 ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $functionsAnalyzer = new FunctionsAnalyzer(); $tokenKinds = [\T_FUNCTION, \T_FN]; for ($index = $tokens->count() - 1; $index >= 0; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind($tokenKinds)) { continue; } $arguments = $functionsAnalyzer->getFunctionArguments($tokens, $index); $this->fixFunctionParameters($tokens, $arguments); } } /** * @param array<string, ArgumentAnalysis> $arguments */ private function fixFunctionParameters(Tokens $tokens, array $arguments): void { foreach (array_reverse($arguments) as $argumentInfo) { if ( // Skip, if the parameter // - doesn't have a type declaration !$argumentInfo->hasTypeAnalysis() // - has a mixed or standalone null type || \in_array(strtolower($argumentInfo->getTypeAnalysis()->getName()), ['mixed', 'null'], true) // - a default value is not null we can continue || !$argumentInfo->hasDefault() || 'null' !== strtolower($argumentInfo->getDefault()) ) { continue; } $argumentTypeInfo = $argumentInfo->getTypeAnalysis(); if (\PHP_VERSION_ID >= 8_00_00 && false === $this->configuration['use_nullable_type_declaration']) { $visibility = $tokens[$tokens->getPrevMeaningfulToken($argumentTypeInfo->getStartIndex())]; if ($visibility->isGivenKind(self::CONSTRUCTOR_PROPERTY_MODIFIERS)) { continue; } } $typeAnalysisName = $argumentTypeInfo->getName(); if (str_contains($typeAnalysisName, '|') || str_contains($typeAnalysisName, '&')) { $this->fixUnionTypeParameter($tokens, $argumentTypeInfo); } else { $this->fixSingleTypeParameter($tokens, $argumentTypeInfo); } } } private function fixSingleTypeParameter(Tokens $tokens, TypeAnalysis $argumentTypeInfo): void { if (true === $this->configuration['use_nullable_type_declaration']) { if (!$argumentTypeInfo->isNullable()) { $tokens->insertAt($argumentTypeInfo->getStartIndex(), new Token([CT::T_NULLABLE_TYPE, '?'])); } } elseif ($argumentTypeInfo->isNullable()) { $tokens->removeTrailingWhitespace($startIndex = $argumentTypeInfo->getStartIndex()); $tokens->clearTokenAndMergeSurroundingWhitespace($startIndex); } } private function fixUnionTypeParameter(Tokens $tokens, TypeAnalysis $argumentTypeInfo): void { if (true === $this->configuration['use_nullable_type_declaration']) { if ($argumentTypeInfo->isNullable()) { return; } $typeAnalysisName = $argumentTypeInfo->getName(); $endIndex = $argumentTypeInfo->getEndIndex(); if (str_contains($typeAnalysisName, '&') && !str_contains($typeAnalysisName, '|')) { $endIndex += 2; $tokens->insertAt($argumentTypeInfo->getStartIndex(), new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, '('])); $tokens->insertAt($endIndex, new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, ')'])); } $tokens->insertAt($endIndex + 1, [ new Token([CT::T_TYPE_ALTERNATION, '|']), new Token([\T_STRING, 'null']), ]); } elseif ($argumentTypeInfo->isNullable()) { $startIndex = $argumentTypeInfo->getStartIndex(); $index = $tokens->getNextTokenOfKind($startIndex - 1, [[\T_STRING, 'null']], false); if ($index === $startIndex) { $tokens->removeTrailingWhitespace($index); $tokens->clearTokenAndMergeSurroundingWhitespace($index); $index = $tokens->getNextMeaningfulToken($index); if ($tokens[$index]->equals([CT::T_TYPE_ALTERNATION, '|'])) { $tokens->removeTrailingWhitespace($index); $tokens->clearTokenAndMergeSurroundingWhitespace($index); } } else { $tokens->removeLeadingWhitespace($index); $tokens->clearTokenAndMergeSurroundingWhitespace($index); $index = $tokens->getPrevMeaningfulToken($index); if ($tokens[$index]->equals([CT::T_TYPE_ALTERNATION, '|'])) { $tokens->removeLeadingWhitespace($index); $tokens->clearTokenAndMergeSurroundingWhitespace($index); } } $typeAnalysisName = $argumentTypeInfo->getName(); if (str_contains($typeAnalysisName, '&') && 1 === substr_count($typeAnalysisName, '|')) { $index = $tokens->getNextTokenOfKind($startIndex - 1, [[CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN]]); $tokens->removeTrailingWhitespace($index); $tokens->clearTokenAndMergeSurroundingWhitespace($index); $index = $tokens->getPrevTokenOfKind($argumentTypeInfo->getEndIndex() + 1, [[CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE]]); $tokens->removeLeadingWhitespace($index); $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/FunctionNotation/VoidReturnFixer.php
src/Fixer/FunctionNotation/VoidReturnFixer.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\FunctionNotation; use PhpCsFixer\AbstractFixer; use PhpCsFixer\DocBlock\Annotation; use PhpCsFixer\DocBlock\DocBlock; 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 Mark Nielsen * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class VoidReturnFixer extends AbstractFixer { private const PREVIOUS_TOKENS = [ \T_ABSTRACT, \T_FINAL, \T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC, FCT::T_ATTRIBUTE, ]; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Add `void` return type to functions with missing or empty return statements, but priority is given to `@return` annotations.', [ new CodeSample( "<?php\nfunction foo(\$a) {};\n", ), ], null, 'Modifies the signature of functions.', ); } /** * {@inheritdoc} * * Must run before PhpdocNoEmptyReturnFixer, ReturnTypeDeclarationFixer. * Must run after NoSuperfluousPhpdocTagsFixer, SimplifiedNullReturnFixer. */ public function getPriority(): int { return 5; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_FUNCTION); } public function isRisky(): bool { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { for ($index = $tokens->count() - 1; 0 <= $index; --$index) { if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { continue; } $functionName = $tokens->getNextMeaningfulToken($index); // These cause syntax errors. if ($tokens[$functionName]->equalsAny([ [\T_STRING, '__clone'], [\T_STRING, '__construct'], [\T_STRING, '__debugInfo'], [\T_STRING, '__destruct'], [\T_STRING, '__isset'], [\T_STRING, '__serialize'], [\T_STRING, '__set_state'], [\T_STRING, '__sleep'], [\T_STRING, '__toString'], ], false)) { continue; } $startIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); if ($this->hasReturnTypeHint($tokens, $startIndex)) { continue; } if ($tokens[$startIndex]->equals(';')) { // No function body defined, fallback to PHPDoc. if ($this->hasVoidReturnAnnotation($tokens, $index)) { $this->fixFunctionDefinition($tokens, $startIndex); } continue; } if ($this->hasReturnAnnotation($tokens, $index)) { continue; } $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startIndex); if ($this->hasVoidReturn($tokens, $startIndex, $endIndex)) { $this->fixFunctionDefinition($tokens, $startIndex); } } } /** * Determine whether there is a non-void return annotation in the function's PHPDoc comment. * * @param int $index The index of the function token */ private function hasReturnAnnotation(Tokens $tokens, int $index): bool { foreach ($this->findReturnAnnotations($tokens, $index) as $return) { if (['void'] !== $return->getTypes()) { return true; } } return false; } /** * Determine whether there is a void return annotation in the function's PHPDoc comment. * * @param int $index The index of the function token */ private function hasVoidReturnAnnotation(Tokens $tokens, int $index): bool { foreach ($this->findReturnAnnotations($tokens, $index) as $return) { if (['void'] === $return->getTypes()) { return true; } } return false; } /** * Determine whether the function already has a return type hint. * * @param int $index The index of the end of the function definition line, EG at { or ; */ private function hasReturnTypeHint(Tokens $tokens, int $index): bool { $endFuncIndex = $tokens->getPrevTokenOfKind($index, [')']); $nextIndex = $tokens->getNextMeaningfulToken($endFuncIndex); return $tokens[$nextIndex]->isGivenKind(CT::T_TYPE_COLON); } /** * Determine whether the function has a void return. * * @param int $startIndex Start of function body * @param int $endIndex End of function body */ private function hasVoidReturn(Tokens $tokens, int $startIndex, int $endIndex): bool { $tokensAnalyzer = new TokensAnalyzer($tokens); for ($i = $startIndex; $i < $endIndex; ++$i) { if ( // skip anonymous classes ($tokens[$i]->isGivenKind(\T_CLASS) && $tokensAnalyzer->isAnonymousClass($i)) // skip lambda functions || ($tokens[$i]->isGivenKind(\T_FUNCTION) && $tokensAnalyzer->isLambda($i)) ) { $i = $tokens->getNextTokenOfKind($i, ['{']); $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $i); continue; } if ($tokens[$i]->isGivenKind([\T_YIELD, \T_YIELD_FROM])) { return false; // Generators cannot return void. } if (!$tokens[$i]->isGivenKind(\T_RETURN)) { continue; } $i = $tokens->getNextMeaningfulToken($i); if (!$tokens[$i]->equals(';')) { return false; } } return true; } /** * @param int $index The index of the end of the function definition line, EG at { or ; */ private function fixFunctionDefinition(Tokens $tokens, int $index): void { $endFuncIndex = $tokens->getPrevTokenOfKind($index, [')']); $tokens->insertAt($endFuncIndex + 1, [ new Token([CT::T_TYPE_COLON, ':']), new Token([\T_WHITESPACE, ' ']), new Token([\T_STRING, 'void']), ]); } /** * Find all the return annotations in the function's PHPDoc comment. * * @param int $index The index of the function token * * @return list<Annotation> */ private function findReturnAnnotations(Tokens $tokens, int $index): array { do { $index = $tokens->getPrevNonWhitespace($index); if ($tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { $index = $tokens->getPrevTokenOfKind($index, [[\T_ATTRIBUTE]]); } } while ($tokens[$index]->isGivenKind(self::PREVIOUS_TOKENS)); if (!$tokens[$index]->isGivenKind(\T_DOC_COMMENT)) { return []; } $doc = new DocBlock($tokens[$index]->getContent()); return $doc->getAnnotationsOfType('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/FunctionNotation/PhpdocToParamTypeFixer.php
src/Fixer/FunctionNotation/PhpdocToParamTypeFixer.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\FunctionNotation; use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer; use PhpCsFixer\DocBlock\Annotation; use PhpCsFixer\Fixer\ConfigurableFixerInterface; use PhpCsFixer\Fixer\ExperimentalFixerInterface; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * scalar_types?: bool, * types_map?: array<string, string>, * union_types?: bool, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * scalar_types: bool, * types_map: array<string, string>, * union_types: bool, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @phpstan-import-type _PhpTokenArray from Token * * @author Jan Gantzert <jan@familie-gantzert.de> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocToParamTypeFixer extends AbstractPhpdocToTypeDeclarationFixer implements ConfigurableFixerInterface, ExperimentalFixerInterface { private const TYPE_CHECK_TEMPLATE = '<?php function f(%s $x) {}'; /** * @var non-empty-list<_PhpTokenArray> */ private const EXCLUDE_FUNC_NAMES = [ [\T_STRING, '__clone'], [\T_STRING, '__destruct'], ]; /** * @var array<string, true> */ private const SKIPPED_TYPES = [ 'resource' => true, 'static' => true, 'void' => true, ]; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Takes `@param` annotations of non-mixed types and adjusts accordingly the function signature.', [ new CodeSample( <<<'PHP' <?php /** * @param string $foo * @param string|null $bar */ function f($foo, $bar) {} PHP, ), new CodeSample( <<<'PHP' <?php /** @param Foo $foo */ function foo($foo) {} /** @param string $foo */ function bar($foo) {} PHP, ['scalar_types' => false], ), new CodeSample( <<<'PHP' <?php /** @param Foo $foo */ function foo($foo) {} /** @param int|string $foo */ function bar($foo) {} PHP, ['union_types' => false], ), ], null, 'The `@param` annotation is mandatory for the fixer to make changes, signatures of methods without it (no docblock, inheritdocs) will not be fixed. Manual actions are required if inherited signatures are not properly documented.', ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); } /** * {@inheritdoc} * * Must run before NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 8; } protected function isSkippedType(string $type): bool { return isset(self::SKIPPED_TYPES[$type]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $tokensToInsert = []; $typesToExclude = []; foreach ($tokens as $index => $token) { if ($token->isGivenKind(\T_DOC_COMMENT)) { $typesToExclude = array_merge($typesToExclude, self::getTypesToExclude($token->getContent())); continue; } if (!$token->isGivenKind([\T_FUNCTION, \T_FN])) { continue; } $funcName = $tokens->getNextMeaningfulToken($index); if ($tokens[$funcName]->equalsAny(self::EXCLUDE_FUNC_NAMES, false)) { continue; } $docCommentIndex = $this->findFunctionDocComment($tokens, $index); if (null === $docCommentIndex) { continue; } foreach ($this->getAnnotationsFromDocComment('param', $tokens, $docCommentIndex) as $paramTypeAnnotation) { $typesExpression = $paramTypeAnnotation->getTypeExpression(); if (null === $typesExpression) { continue; } $typeInfo = $this->getCommonTypeInfo($typesExpression, false); $unionTypes = null; if (null === $typeInfo) { $unionTypes = $this->getUnionTypes($typesExpression, false); } if (null === $typeInfo && null === $unionTypes) { continue; } if (null !== $typeInfo) { $paramType = $typeInfo['commonType']; $isNullable = $typeInfo['isNullable']; } elseif (null !== $unionTypes) { $paramType = $unionTypes; $isNullable = false; } if (!isset($paramType, $isNullable)) { continue; } if (\in_array($paramType, $typesToExclude, true)) { continue; } $startIndex = $tokens->getNextTokenOfKind($index, ['(']); $variableIndex = $this->findCorrectVariable($tokens, $startIndex, $paramTypeAnnotation); if (null === $variableIndex) { continue; } $byRefIndex = $tokens->getPrevMeaningfulToken($variableIndex); \assert(\is_int($byRefIndex)); if ($tokens[$byRefIndex]->equals('&')) { $variableIndex = $byRefIndex; } if ($this->hasParamTypeHint($tokens, $variableIndex)) { continue; } if (!$this->isValidSyntax(\sprintf(self::TYPE_CHECK_TEMPLATE, $paramType))) { continue; } $tokensToInsert[$variableIndex] = array_merge( $this->createTypeDeclarationTokens($paramType, $isNullable), [new Token([\T_WHITESPACE, ' '])], ); } } $tokens->insertSlices($tokensToInsert); } protected function createTokensFromRawType(string $type): Tokens { $typeTokens = Tokens::fromCode(\sprintf(self::TYPE_CHECK_TEMPLATE, $type)); $typeTokens->clearRange(0, 4); $typeTokens->clearRange(\count($typeTokens) - 6, \count($typeTokens) - 1); $typeTokens->clearEmptyTokens(); return $typeTokens; } private function findCorrectVariable(Tokens $tokens, int $startIndex, Annotation $paramTypeAnnotation): ?int { $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex); for ($index = $startIndex + 1; $index < $endIndex; ++$index) { if (!$tokens[$index]->isGivenKind(\T_VARIABLE)) { continue; } $variableName = $tokens[$index]->getContent(); if ($paramTypeAnnotation->getVariableName() === $variableName) { return $index; } } return null; } /** * Determine whether the function already has a param type hint. * * @param int $index The index of the end of the function definition line, EG at { or ; */ private function hasParamTypeHint(Tokens $tokens, int $index): bool { $prevIndex = $tokens->getPrevMeaningfulToken($index); return !$tokens[$prevIndex]->equalsAny([',', '(']); } }
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/FunctionNotation/NativeFunctionInvocationFixer.php
src/Fixer/FunctionNotation/NativeFunctionInvocationFixer.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\FunctionNotation; 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\FunctionsAnalyzer; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; use PhpCsFixer\Utils; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * exclude?: list<string>, * include?: list<string>, * scope?: 'all'|'namespaced', * strict?: bool, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * exclude: list<string>, * include: list<string>, * scope: 'all'|'namespaced', * strict: bool, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @author Andreas Möller <am@localheinz.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NativeFunctionInvocationFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; /** * @internal */ public const SET_ALL = '@all'; /** * Subset of SET_INTERNAL. * * Change function call to functions known to be optimized by the Zend engine. * For details: * - @see https://github.com/php/php-src/blob/php-7.2.6/Zend/zend_compile.c "zend_try_compile_special_func" * - @see https://github.com/php/php-src/blob/php-7.2.6/ext/opcache/Optimizer/pass1_5.c * * @internal */ public const SET_COMPILER_OPTIMIZED = '@compiler_optimized'; /** * @internal */ public const SET_INTERNAL = '@internal'; /** * @var callable */ private $functionFilter; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Add leading `\` before function invocation to speed up resolving.', [ new CodeSample( <<<'PHP' <?php function baz($options) { if (!array_key_exists("foo", $options)) { throw new \InvalidArgumentException(); } return json_encode($options); } PHP, ), new CodeSample( <<<'PHP' <?php function baz($options) { if (!array_key_exists("foo", $options)) { throw new \InvalidArgumentException(); } return json_encode($options); } PHP, [ 'exclude' => [ 'json_encode', ], ], ), new CodeSample( <<<'PHP' <?php namespace space1 { echo count([1]); } namespace { echo count([1]); } PHP, ['scope' => 'all'], ), new CodeSample( <<<'PHP' <?php namespace space1 { echo count([1]); } namespace { echo count([1]); } PHP, ['scope' => 'namespaced'], ), new CodeSample( <<<'PHP' <?php myGlobalFunction(); count(); PHP, ['include' => ['myGlobalFunction']], ), new CodeSample( <<<'PHP' <?php myGlobalFunction(); count(); PHP, ['include' => [self::SET_ALL]], ), new CodeSample( <<<'PHP' <?php myGlobalFunction(); count(); PHP, ['include' => [self::SET_INTERNAL]], ), new CodeSample( <<<'PHP' <?php $a .= str_repeat($a, 4); $c = get_class($d); PHP, ['include' => [self::SET_COMPILER_OPTIMIZED]], ), ], null, 'Risky when any of the functions are overridden.', ); } /** * {@inheritdoc} * * Must run before GlobalNamespaceImportFixer. * Must run after BacktickToShellExecFixer, MbStrFunctionsFixer, RegularCallableCallFixer, StrictParamFixer. */ public function getPriority(): int { return 1; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_STRING); } public function isRisky(): bool { return true; } protected function configurePostNormalisation(): void { $this->functionFilter = $this->getFunctionFilter(); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { if ('all' === $this->configuration['scope']) { $this->fixFunctionCalls($tokens, $this->functionFilter, 0, \count($tokens) - 1, false); return; } $namespaces = $tokens->getNamespaceDeclarations(); // 'scope' is 'namespaced' here foreach (array_reverse($namespaces) as $namespace) { $this->fixFunctionCalls($tokens, $this->functionFilter, $namespace->getScopeStartIndex(), $namespace->getScopeEndIndex(), $namespace->isGlobalNamespace()); } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('exclude', 'List of functions to ignore.')) ->setAllowedTypes(['string[]']) ->setAllowedValues([static function (array $value): bool { foreach ($value as $functionName) { if ('' === trim($functionName) || trim($functionName) !== $functionName) { throw new InvalidOptionsException(\sprintf( 'Each element must be a non-empty, trimmed string, got "%s" instead.', get_debug_type($functionName), )); } } return true; }]) ->setDefault([]) ->getOption(), (new FixerOptionBuilder('include', 'List of function names or sets to fix. Defined sets are `@internal` (all native functions), `@all` (all global functions) and `@compiler_optimized` (functions that are specially optimized by Zend).')) ->setAllowedTypes(['string[]']) ->setAllowedValues([static function (array $value): bool { foreach ($value as $functionName) { if ('' === trim($functionName) || trim($functionName) !== $functionName) { throw new InvalidOptionsException(\sprintf( 'Each element must be a non-empty, trimmed string, got "%s" instead.', get_debug_type($functionName), )); } $sets = [ self::SET_ALL, self::SET_INTERNAL, self::SET_COMPILER_OPTIMIZED, ]; if (str_starts_with($functionName, '@') && !\in_array($functionName, $sets, true)) { throw new InvalidOptionsException(\sprintf('Unknown set "%s", known sets are %s.', $functionName, Utils::naturalLanguageJoin($sets))); } } return true; }]) ->setDefault([self::SET_COMPILER_OPTIMIZED]) ->getOption(), (new FixerOptionBuilder('scope', 'Only fix function calls that are made within a namespace or fix all.')) ->setAllowedValues(['all', 'namespaced']) ->setDefault('all') ->getOption(), (new FixerOptionBuilder('strict', 'Whether leading `\` of function call not meant to have it should be removed.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), ]); } private function fixFunctionCalls(Tokens $tokens, callable $functionFilter, int $start, int $end, bool $tryToRemove): void { $functionsAnalyzer = new FunctionsAnalyzer(); $tokensToInsert = []; for ($index = $start; $index < $end; ++$index) { if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { continue; } $prevIndex = $tokens->getPrevMeaningfulToken($index); if (!$functionFilter($tokens[$index]->getContent()) || $tryToRemove) { if (false === $this->configuration['strict']) { continue; } if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); } continue; } if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { continue; // do not bother if previous token is already namespace separator } $tokensToInsert[$index] = new Token([\T_NS_SEPARATOR, '\\']); } $tokens->insertSlices($tokensToInsert); } private function getFunctionFilter(): callable { $exclude = $this->normalizeFunctionNames($this->configuration['exclude']); if (\in_array(self::SET_ALL, $this->configuration['include'], true)) { if (\count($exclude) > 0) { return static fn (string $functionName): bool => !isset($exclude[strtolower($functionName)]); } return static fn (): bool => true; } $include = []; if (\in_array(self::SET_INTERNAL, $this->configuration['include'], true)) { $include = $this->getAllInternalFunctionsNormalized(); } elseif (\in_array(self::SET_COMPILER_OPTIMIZED, $this->configuration['include'], true)) { $include = $this->getAllCompilerOptimizedFunctionsNormalized(); // if `@internal` is set all compiler optimized function are already loaded } foreach ($this->configuration['include'] as $additional) { if (!str_starts_with($additional, '@')) { $include[strtolower($additional)] = true; } } if (\count($exclude) > 0) { return static fn (string $functionName): bool => isset($include[strtolower($functionName)]) && !isset($exclude[strtolower($functionName)]); } return static fn (string $functionName): bool => isset($include[strtolower($functionName)]); } /** * @return array<string, true> normalized function names of which the PHP compiler optimizes */ private function getAllCompilerOptimizedFunctionsNormalized(): array { return $this->normalizeFunctionNames([ // @see https://github.com/php/php-src/blob/PHP-7.4/Zend/zend_compile.c "zend_try_compile_special_func" 'array_key_exists', 'array_slice', 'assert', 'boolval', 'call_user_func', 'call_user_func_array', 'chr', 'count', 'defined', 'doubleval', 'floatval', 'func_get_args', 'func_num_args', 'get_called_class', 'get_class', 'gettype', 'in_array', 'intval', 'is_array', 'is_bool', 'is_double', 'is_float', 'is_int', 'is_integer', 'is_long', 'is_null', 'is_object', 'is_real', 'is_resource', 'is_scalar', 'is_string', 'ord', 'sizeof', 'sprintf', 'strlen', 'strval', // @see https://github.com/php/php-src/blob/php-7.2.6/ext/opcache/Optimizer/pass1_5.c // @see https://github.com/php/php-src/blob/PHP-8.1.2/Zend/Optimizer/block_pass.c // @see https://github.com/php/php-src/blob/php-8.1.3/Zend/Optimizer/zend_optimizer.c 'constant', 'define', 'dirname', 'extension_loaded', 'function_exists', 'is_callable', 'ini_get', ]); } /** * @return array<string, true> normalized function names of all internal defined functions */ private function getAllInternalFunctionsNormalized(): array { return $this->normalizeFunctionNames(get_defined_functions()['internal']); } /** * @param list<string> $functionNames * * @return array<string, true> all function names lower cased */ private function normalizeFunctionNames(array $functionNames): array { $result = []; foreach ($functionNames as $functionName) { $result[strtolower($functionName)] = true; } 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/FunctionNotation/NoUselessPrintfFixer.php
src/Fixer/FunctionNotation/NoUselessPrintfFixer.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\FunctionNotation; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @author John Paul E. Balandan, CPA <paulbalandan@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NoUselessPrintfFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'There must be no `printf` calls with only the first argument.', [ new CodeSample( "<?php\n\nprintf('bar');\n", ), ], null, 'Risky when the `printf` function is overridden.', ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_STRING); } public function isRisky(): bool { return true; } /** * {@inheritdoc} * * Must run before EchoTagSyntaxFixer, NoExtraBlankLinesFixer, NoMixedEchoPrintFixer. */ public function getPriority(): int { return 10; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $functionsAnalyzer = new FunctionsAnalyzer(); $argumentsAnalyzer = new ArgumentsAnalyzer(); $printfIndices = []; for ($index = \count($tokens) - 1; $index > 0; --$index) { if (!$tokens[$index]->isGivenKind(\T_STRING)) { continue; } if ('printf' !== strtolower($tokens[$index]->getContent())) { continue; } if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { continue; } $openParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(']); if ($tokens[$tokens->getNextMeaningfulToken($openParenthesisIndex)]->isGivenKind([\T_ELLIPSIS, CT::T_FIRST_CLASS_CALLABLE])) { continue; } $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesisIndex); if (1 !== $argumentsAnalyzer->countArguments($tokens, $openParenthesisIndex, $closeParenthesisIndex)) { continue; } $tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesisIndex); $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($closeParenthesisIndex); if ($tokens[$prevMeaningfulTokenIndex]->equals(',')) { $tokens->clearTokenAndMergeSurroundingWhitespace($prevMeaningfulTokenIndex); } $tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesisIndex); $tokens->clearTokenAndMergeSurroundingWhitespace($index); $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prevMeaningfulTokenIndex]->isGivenKind(\T_NS_SEPARATOR)) { $tokens->clearTokenAndMergeSurroundingWhitespace($prevMeaningfulTokenIndex); } $printfIndices[] = $index; } if ([] === $printfIndices) { return; } $tokens->insertSlices(array_combine( $printfIndices, array_fill(0, \count($printfIndices), [new Token([\T_PRINT, 'print']), 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/FunctionNotation/NoTrailingCommaInSinglelineFunctionCallFixer.php
src/Fixer/FunctionNotation/NoTrailingCommaInSinglelineFunctionCallFixer.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\FunctionNotation; use PhpCsFixer\AbstractProxyFixer; use PhpCsFixer\Fixer\Basic\NoTrailingCommaInSinglelineFixer; use PhpCsFixer\Fixer\DeprecatedFixerInterface; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; /** * @deprecated * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NoTrailingCommaInSinglelineFunctionCallFixer extends AbstractProxyFixer implements DeprecatedFixerInterface { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'When making a method or function call on a single line there MUST NOT be a trailing comma after the last argument.', [new CodeSample("<?php\nfoo(\$a,);\n")], ); } /** * {@inheritdoc} * * Must run before NoSpacesInsideParenthesisFixer. */ public function getPriority(): int { return 3; } public function getSuccessorsNames(): array { return array_keys($this->proxyFixers); } protected function createProxyFixers(): array { $fixer = new NoTrailingCommaInSinglelineFixer(); $fixer->configure(['elements' => ['arguments', 'array_destructuring']]); 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/FunctionNotation/FunctionDeclarationFixer.php
src/Fixer/FunctionNotation/FunctionDeclarationFixer.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\FunctionNotation; 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\Future; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Tokens; use PhpCsFixer\Tokenizer\TokensAnalyzer; /** * Fixer for rules defined in PSR2 generally (¶1 and ¶6). * * @phpstan-type _AutogeneratedInputConfiguration array{ * closure_fn_spacing?: 'none'|'one', * closure_function_spacing?: 'none'|'one', * trailing_comma_single_line?: bool, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * closure_fn_spacing: 'none'|'one', * closure_function_spacing: 'none'|'one', * trailing_comma_single_line: 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 FunctionDeclarationFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; /** * @internal */ public const SPACING_NONE = 'none'; /** * @internal */ public const SPACING_ONE = 'one'; private const SUPPORTED_SPACINGS = [self::SPACING_NONE, self::SPACING_ONE]; private string $singleLineWhitespaceOptions = " \t"; public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); } public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Spaces should be properly placed in a function declaration.', [ new CodeSample( <<<'PHP' <?php class Foo { public static function bar ( $baz , $foo ) { return false; } } function foo ($bar, $baz) { return false; } PHP, ), new CodeSample( <<<'PHP' <?php $f = function () {}; PHP, ['closure_function_spacing' => self::SPACING_NONE], ), new CodeSample( <<<'PHP' <?php $f = fn () => null; PHP, ['closure_fn_spacing' => self::SPACING_NONE], ), ], ); } /** * {@inheritdoc} * * Must run before MethodArgumentSpaceFixer. * Must run after SingleSpaceAfterConstructFixer, SingleSpaceAroundConstructFixer, UseArrowFunctionsFixer. */ public function getPriority(): int { return 31; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $tokensAnalyzer = new TokensAnalyzer($tokens); for ($index = $tokens->count() - 1; $index >= 0; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind([\T_FUNCTION, \T_FN])) { continue; } $startParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(', ';', [\T_CLOSE_TAG]]); if (!$tokens[$startParenthesisIndex]->equals('(')) { continue; } $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex); if (false === $this->configuration['trailing_comma_single_line'] && !$tokens->isPartialCodeMultiline($index, $endParenthesisIndex) ) { $commaIndex = $tokens->getPrevMeaningfulToken($endParenthesisIndex); if ($tokens[$commaIndex]->equals(',')) { $tokens->clearTokenAndMergeSurroundingWhitespace($commaIndex); } } $startBraceIndex = $tokens->getNextTokenOfKind($endParenthesisIndex, [';', '{', [\T_DOUBLE_ARROW]]); // fix single-line whitespace before { or => // eg: `function foo(){}` => `function foo() {}` // eg: `function foo() {}` => `function foo() {}` // eg: `fn() =>` => `fn() =>` if ( $tokens[$startBraceIndex]->equalsAny(['{', [\T_DOUBLE_ARROW]]) && ( !$tokens[$startBraceIndex - 1]->isWhitespace() || $tokens[$startBraceIndex - 1]->isWhitespace($this->singleLineWhitespaceOptions) ) ) { $tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, ' '); } $afterParenthesisIndex = $tokens->getNextNonWhitespace($endParenthesisIndex); $afterParenthesisToken = $tokens[$afterParenthesisIndex]; if ($afterParenthesisToken->isGivenKind(CT::T_USE_LAMBDA)) { // fix whitespace after CT:T_USE_LAMBDA (we might add a token, so do this before determining start and end parenthesis) $tokens->ensureWhitespaceAtIndex($afterParenthesisIndex + 1, 0, ' '); $useStartParenthesisIndex = $tokens->getNextTokenOfKind($afterParenthesisIndex, ['(']); $useEndParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $useStartParenthesisIndex); if (false === $this->configuration['trailing_comma_single_line'] && !$tokens->isPartialCodeMultiline($index, $useEndParenthesisIndex) ) { $commaIndex = $tokens->getPrevMeaningfulToken($useEndParenthesisIndex); if ($tokens[$commaIndex]->equals(',')) { $tokens->clearTokenAndMergeSurroundingWhitespace($commaIndex); } } // remove single-line edge whitespaces inside use parentheses $this->fixParenthesisInnerEdge($tokens, $useStartParenthesisIndex, $useEndParenthesisIndex); // fix whitespace before CT::T_USE_LAMBDA $tokens->ensureWhitespaceAtIndex($afterParenthesisIndex - 1, 1, ' '); } // remove single-line edge whitespaces inside parameters list parentheses $this->fixParenthesisInnerEdge($tokens, $startParenthesisIndex, $endParenthesisIndex); $isLambda = $tokensAnalyzer->isLambda($index); // remove whitespace before ( // eg: `function foo () {}` => `function foo() {}` if (!$isLambda && $tokens[$startParenthesisIndex - 1]->isWhitespace() && !$tokens[$tokens->getPrevNonWhitespace($startParenthesisIndex - 1)]->isComment()) { $tokens->clearAt($startParenthesisIndex - 1); } $option = $token->isGivenKind(\T_FN) ? 'closure_fn_spacing' : 'closure_function_spacing'; if ($isLambda && self::SPACING_NONE === $this->configuration[$option]) { // optionally remove whitespace after T_FUNCTION of a closure // eg: `function () {}` => `function() {}` if ($tokens[$index + 1]->isWhitespace()) { $tokens->clearAt($index + 1); } } else { // otherwise, enforce whitespace after T_FUNCTION // eg: `function foo() {}` => `function foo() {}` $tokens->ensureWhitespaceAtIndex($index + 1, 0, ' '); } if ($isLambda) { $prev = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prev]->isGivenKind(\T_STATIC)) { // fix whitespace after T_STATIC // eg: `$a = static function(){};` => `$a = static function(){};` $tokens->ensureWhitespaceAtIndex($prev + 1, 0, ' '); } } } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('closure_function_spacing', 'Spacing to use before open parenthesis for closures.')) ->setDefault(self::SPACING_ONE) ->setAllowedValues(self::SUPPORTED_SPACINGS) ->getOption(), (new FixerOptionBuilder('closure_fn_spacing', 'Spacing to use before open parenthesis for short arrow functions.')) ->setDefault( Future::getV4OrV3( self::SPACING_NONE, self::SPACING_ONE, ), ) ->setAllowedValues(self::SUPPORTED_SPACINGS) ->getOption(), (new FixerOptionBuilder('trailing_comma_single_line', 'Whether trailing commas are allowed in single line signatures.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), ]); } private function fixParenthesisInnerEdge(Tokens $tokens, int $start, int $end): void { do { --$end; } while ($tokens->isEmptyAt($end)); // remove single-line whitespace before `)` if ($tokens[$end]->isWhitespace($this->singleLineWhitespaceOptions)) { $tokens->clearAt($end); } // remove single-line whitespace after `(` if ($tokens[$start + 1]->isWhitespace($this->singleLineWhitespaceOptions)) { $tokens->clearAt($start + 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/FunctionNotation/PhpdocToPropertyTypeFixer.php
src/Fixer/FunctionNotation/PhpdocToPropertyTypeFixer.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\FunctionNotation; use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer; use PhpCsFixer\DocBlock\Annotation; use PhpCsFixer\Fixer\ConfigurableFixerInterface; use PhpCsFixer\Fixer\ExperimentalFixerInterface; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @phpstan-import-type _CommonTypeInfo from AbstractPhpdocToTypeDeclarationFixer * * @phpstan-type _AutogeneratedInputConfiguration array{ * scalar_types?: bool, * types_map?: array<string, string>, * union_types?: bool, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * scalar_types: bool, * types_map: array<string, string>, * union_types: bool, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocToPropertyTypeFixer extends AbstractPhpdocToTypeDeclarationFixer implements ConfigurableFixerInterface, ExperimentalFixerInterface { private const TYPE_CHECK_TEMPLATE = '<?php class A { private %s $b; }'; /** * @var array<string, true> */ private array $skippedTypes = [ 'resource' => true, 'null' => true, ]; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Takes `@var` annotation of non-mixed types and adjusts accordingly the property signature..', [ new CodeSample( <<<'PHP' <?php class Foo { /** @var int */ private $foo; /** @var \Traversable */ private $bar; } PHP, ), new CodeSample( <<<'PHP' <?php class Foo { /** @var int */ private $foo; /** @var \Traversable */ private $bar; } PHP, ['scalar_types' => false], ), new CodeSample( <<<'PHP' <?php class Foo { /** @var int|string */ private $foo; /** @var \Traversable */ private $bar; } PHP, ['union_types' => false], ), ], null, 'The `@var` annotation is mandatory for the fixer to make changes, signatures of properties without it (no docblock) will not be fixed. Manual actions might be required for newly typed properties that are read before initialization.', ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } /** * {@inheritdoc} * * Must run before FullyQualifiedStrictTypesFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 8; } protected function isSkippedType(string $type): bool { return isset($this->skippedTypes[$type]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $tokensToInsert = []; $typesToExclude = []; foreach ($tokens as $index => $token) { if ($token->isGivenKind(\T_DOC_COMMENT)) { $typesToExclude = array_merge($typesToExclude, self::getTypesToExclude($token->getContent())); continue; } if ($tokens[$index]->isGivenKind([\T_CLASS, \T_TRAIT])) { $tokensToInsert += $this->fixClass($tokens, $index, $typesToExclude); } } $tokens->insertSlices($tokensToInsert); } protected function createTokensFromRawType(string $type): Tokens { $typeTokens = Tokens::fromCode(\sprintf(self::TYPE_CHECK_TEMPLATE, $type)); $typeTokens->clearRange(0, 8); $typeTokens->clearRange(\count($typeTokens) - 5, \count($typeTokens) - 1); $typeTokens->clearEmptyTokens(); return $typeTokens; } /** * @param list<string> $typesToExclude * * @return array<int, list<Token>> */ private function fixClass(Tokens $tokens, int $index, array $typesToExclude): array { $tokensToInsert = []; $index = $tokens->getNextTokenOfKind($index, ['{']); $classEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); for (; $index < $classEndIndex; ++$index) { if ($tokens[$index]->isGivenKind(\T_FUNCTION)) { $index = $tokens->getNextTokenOfKind($index, ['{', ';']); if ($tokens[$index]->equals('{')) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); } continue; } if (!$tokens[$index]->isGivenKind(\T_DOC_COMMENT)) { continue; } $docCommentIndex = $index; $propertyIndices = $this->findNextUntypedPropertiesDeclaration($tokens, $docCommentIndex); if ([] === $propertyIndices) { continue; } $typeInfo = $this->resolveApplicableType( $propertyIndices, $this->getAnnotationsFromDocComment('var', $tokens, $docCommentIndex), ); if (null === $typeInfo) { continue; } $propertyType = $typeInfo['commonType']; $isNullable = $typeInfo['isNullable']; if (\in_array($propertyType, ['callable', 'never', 'void'], true)) { continue; } if (\in_array($propertyType, $typesToExclude, true)) { continue; } if (!$this->isValidSyntax(\sprintf(self::TYPE_CHECK_TEMPLATE, $propertyType))) { continue; } $newTokens = array_merge( $this->createTypeDeclarationTokens($propertyType, $isNullable), [new Token([\T_WHITESPACE, ' '])], ); $tokensToInsert[current($propertyIndices)] = $newTokens; $index = max($propertyIndices) + 1; } return $tokensToInsert; } /** * @return array<string, int> */ private function findNextUntypedPropertiesDeclaration(Tokens $tokens, int $index): array { do { $index = $tokens->getNextMeaningfulToken($index); } while ($tokens[$index]->isGivenKind([ \T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC, \T_VAR, ])); if (!$tokens[$index]->isGivenKind(\T_VARIABLE)) { return []; } $properties = []; while (!$tokens[$index]->equals(';')) { if ($tokens[$index]->isGivenKind(\T_VARIABLE)) { $properties[$tokens[$index]->getContent()] = $index; } $index = $tokens->getNextMeaningfulToken($index); } return $properties; } /** * @param array<string, int> $propertyIndices * @param list<Annotation> $annotations * * @return ?_CommonTypeInfo */ private function resolveApplicableType(array $propertyIndices, array $annotations): ?array { $propertyTypes = []; foreach ($annotations as $annotation) { $propertyName = $annotation->getVariableName(); if (null === $propertyName) { if (1 !== \count($propertyIndices)) { continue; } $propertyName = array_key_first($propertyIndices); } if (!isset($propertyIndices[$propertyName])) { continue; } $typesExpression = $annotation->getTypeExpression(); if (null === $typesExpression) { continue; } $typeInfo = $this->getCommonTypeInfo($typesExpression, false); $unionTypes = null; if (null === $typeInfo) { $unionTypes = $this->getUnionTypes($typesExpression, false); } if (null === $typeInfo && null === $unionTypes) { continue; } if (null !== $unionTypes) { $typeInfo = ['commonType' => $unionTypes, 'isNullable' => false]; } if (\array_key_exists($propertyName, $propertyTypes) && $typeInfo !== $propertyTypes[$propertyName]) { return null; } $propertyTypes[$propertyName] = $typeInfo; } if (\count($propertyTypes) !== \count($propertyIndices)) { return null; } $type = array_shift($propertyTypes); foreach ($propertyTypes as $propertyType) { if ($propertyType !== $type) { return null; } } return $type; } }
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/FunctionNotation/FopenFlagsFixer.php
src/Fixer/FunctionNotation/FopenFlagsFixer.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\FunctionNotation; use PhpCsFixer\AbstractFopenFlagFixer; 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{ * b_mode?: bool, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * b_mode: bool, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class FopenFlagsFixer extends AbstractFopenFlagFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'The flags in `fopen` calls must omit `t`, and `b` must be omitted or included consistently.', [ new CodeSample("<?php\n\$a = fopen(\$foo, 'rwt');\n"), new CodeSample("<?php\n\$a = fopen(\$foo, 'rwt');\n", ['b_mode' => false]), ], null, 'Risky when the function `fopen` is overridden.', ); } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('b_mode', 'The `b` flag must be used (`true`) or omitted (`false`).')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), ]); } protected function fixFopenFlagToken(Tokens $tokens, int $argumentStartIndex, int $argumentEndIndex): void { $argumentFlagIndex = null; for ($i = $argumentStartIndex; $i <= $argumentEndIndex; ++$i) { if ($tokens[$i]->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { continue; } if (null !== $argumentFlagIndex) { return; // multiple meaningful tokens found, no candidate for fixing } $argumentFlagIndex = $i; } // check if second argument is candidate if (null === $argumentFlagIndex || !$tokens[$argumentFlagIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { return; } $content = $tokens[$argumentFlagIndex]->getContent(); $contentQuote = $content[0]; // `'`, `"`, `b` or `B` if ('b' === $contentQuote || 'B' === $contentQuote) { $binPrefix = $contentQuote; $contentQuote = $content[1]; // `'` or `"` $mode = substr($content, 2, -1); } else { $binPrefix = ''; $mode = substr($content, 1, -1); } if (false === $this->isValidModeString($mode)) { return; } $mode = str_replace('t', '', $mode); if (true === $this->configuration['b_mode']) { if (!str_contains($mode, 'b')) { $mode .= 'b'; } } else { $mode = str_replace('b', '', $mode); } $newContent = $binPrefix.$contentQuote.$mode.$contentQuote; if ($content !== $newContent) { $tokens[$argumentFlagIndex] = new Token([\T_CONSTANT_ENCAPSED_STRING, $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/FunctionNotation/FopenFlagOrderFixer.php
src/Fixer/FunctionNotation/FopenFlagOrderFixer.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\FunctionNotation; use PhpCsFixer\AbstractFopenFlagFixer; 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 FopenFlagOrderFixer extends AbstractFopenFlagFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Order the flags in `fopen` calls, `b` and `t` must be last.', [new CodeSample("<?php\n\$a = fopen(\$foo, 'br+');\n")], null, 'Risky when the function `fopen` is overridden.', ); } protected function fixFopenFlagToken(Tokens $tokens, int $argumentStartIndex, int $argumentEndIndex): void { $argumentFlagIndex = null; for ($i = $argumentStartIndex; $i <= $argumentEndIndex; ++$i) { if ($tokens[$i]->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { continue; } if (null !== $argumentFlagIndex) { return; // multiple meaningful tokens found, no candidate for fixing } $argumentFlagIndex = $i; } // check if second argument is candidate if (null === $argumentFlagIndex || !$tokens[$argumentFlagIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { return; } $content = $tokens[$argumentFlagIndex]->getContent(); $contentQuote = $content[0]; // `'`, `"`, `b` or `B` if ('b' === $contentQuote || 'B' === $contentQuote) { $binPrefix = $contentQuote; $contentQuote = $content[1]; // `'` or `"` $mode = substr($content, 2, -1); } else { $binPrefix = ''; $mode = substr($content, 1, -1); } $modeLength = \strlen($mode); if ($modeLength < 2) { return; // nothing to sort } if (false === $this->isValidModeString($mode)) { return; } $split = $this->sortFlags(Preg::split('#([^\+]\+?)#', $mode, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE)); $newContent = $binPrefix.$contentQuote.implode('', $split).$contentQuote; if ($content !== $newContent) { $tokens[$argumentFlagIndex] = new Token([\T_CONSTANT_ENCAPSED_STRING, $newContent]); } } /** * @param list<string> $flags * * @return list<string> */ private function sortFlags(array $flags): array { usort( $flags, static function (string $flag1, string $flag2): int { if ($flag1 === $flag2) { return 0; } if ('b' === $flag1) { return 1; } if ('b' === $flag2) { return -1; } if ('t' === $flag1) { return 1; } if ('t' === $flag2) { return -1; } return $flag1 < $flag2 ? -1 : 1; }, ); return $flags; } }
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/FunctionNotation/UseArrowFunctionsFixer.php
src/Fixer/FunctionNotation/UseArrowFunctionsFixer.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\FunctionNotation; 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 Gregor Harlan * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class UseArrowFunctionsFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Anonymous functions with return as the only statement must use arrow functions.', [ new CodeSample( <<<'SAMPLE' <?php foo(function ($a) use ($b) { return $a + $b; }); SAMPLE, ), ], null, 'Risky when using `isset()` on outside variables that are not imported with `use ()`.', ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isAllTokenKindsFound([\T_FUNCTION, \T_RETURN]); } public function isRisky(): bool { return true; } /** * {@inheritdoc} * * Must run before FunctionDeclarationFixer. */ public function getPriority(): int { return 32; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $analyzer = new TokensAnalyzer($tokens); for ($index = $tokens->count() - 1; $index > 0; --$index) { if (!$tokens[$index]->isGivenKind(\T_FUNCTION) || !$analyzer->isLambda($index)) { continue; } // Find parameters $parametersStart = $tokens->getNextMeaningfulToken($index); if ($tokens[$parametersStart]->isGivenKind(CT::T_RETURN_REF)) { $parametersStart = $tokens->getNextMeaningfulToken($parametersStart); } $parametersEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $parametersStart); // Find `use ()` start and end // Abort if it contains reference variables $next = $tokens->getNextMeaningfulToken($parametersEnd); $useStart = null; $useEnd = null; if ($tokens[$next]->isGivenKind(CT::T_USE_LAMBDA)) { $useStart = $next; if ($tokens[$useStart - 1]->isGivenKind(\T_WHITESPACE)) { --$useStart; } $next = $tokens->getNextMeaningfulToken($next); while (!$tokens[$next]->equals(')')) { if ($tokens[$next]->equals('&')) { // variables used by reference are not supported by arrow functions continue 2; } $next = $tokens->getNextMeaningfulToken($next); } $useEnd = $next; $next = $tokens->getNextMeaningfulToken($next); } // Find opening brace and following `return` // Abort if there is more than whitespace between them (like comments) $braceOpen = $tokens[$next]->equals('{') ? $next : $tokens->getNextTokenOfKind($next, ['{']); $return = $braceOpen + 1; if ($tokens[$return]->isGivenKind(\T_WHITESPACE)) { ++$return; } if (!$tokens[$return]->isGivenKind(\T_RETURN)) { continue; } // Find semicolon of `return` statement $semicolon = $tokens->getNextTokenOfKind($return, ['{', ';']); if (!$tokens[$semicolon]->equals(';')) { continue; } // Find closing brace // Abort if there is more than whitespace between semicolon and closing brace $braceClose = $semicolon + 1; if ($tokens[$braceClose]->isGivenKind(\T_WHITESPACE)) { ++$braceClose; } if (!$tokens[$braceClose]->equals('}')) { continue; } // Transform the function to an arrow function $this->transform($tokens, $index, $useStart, $useEnd, $braceOpen, $return, $semicolon, $braceClose); } } private function transform(Tokens $tokens, int $index, ?int $useStart, ?int $useEnd, int $braceOpen, int $return, int $semicolon, int $braceClose): void { $tokensToInsert = [new Token([\T_DOUBLE_ARROW, '=>'])]; if ($tokens->getNextMeaningfulToken($return) === $semicolon) { $tokensToInsert[] = new Token([\T_WHITESPACE, ' ']); $tokensToInsert[] = new Token([\T_STRING, 'null']); } $tokens->clearRange($semicolon, $braceClose - 1); $tokens->clearTokenAndMergeSurroundingWhitespace($braceClose); $tokens->clearRange($braceOpen + 1, $return); $tokens->overrideRange($braceOpen, $braceOpen, $tokensToInsert); if (null !== $useStart) { $tokens->clearRange($useStart, $useEnd); } $tokens[$index] = new Token([\T_FN, 'fn']); } }
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/FunctionNotation/SingleLineThrowFixer.php
src/Fixer/FunctionNotation/SingleLineThrowFixer.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\FunctionNotation; 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; /** * @author Kuba Werłos <werlos@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class SingleLineThrowFixer extends AbstractFixer { private const REMOVE_WHITESPACE_AFTER_TOKENS = ['[']; private const REMOVE_WHITESPACE_AROUND_TOKENS = ['(', [\T_DOUBLE_COLON]]; private const REMOVE_WHITESPACE_BEFORE_TOKENS = [')', ']', ',', ';']; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Throwing exception must be done in single line.', [ new CodeSample("<?php\nthrow new Exception(\n 'Error.',\n 500\n);\n"), ], ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_THROW); } /** * {@inheritdoc} * * Must run before BracesFixer, ConcatSpaceFixer. */ public function getPriority(): int { return 36; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { if (!$tokens[$index]->isGivenKind(\T_THROW)) { continue; } $endCandidateIndex = $tokens->getNextMeaningfulToken($index); while (!$tokens[$endCandidateIndex]->equalsAny([')', ']', ',', ';', [\T_CLOSE_TAG]])) { $blockType = Tokens::detectBlockType($tokens[$endCandidateIndex]); if (null !== $blockType) { if (Tokens::BLOCK_TYPE_CURLY_BRACE === $blockType['type'] || !$blockType['isStart']) { break; } $endCandidateIndex = $tokens->findBlockEnd($blockType['type'], $endCandidateIndex); } $endCandidateIndex = $tokens->getNextMeaningfulToken($endCandidateIndex); } $this->trimNewLines($tokens, $index, $tokens->getPrevMeaningfulToken($endCandidateIndex)); } } private function trimNewLines(Tokens $tokens, int $startIndex, int $endIndex): void { for ($index = $startIndex; $index < $endIndex; ++$index) { $content = $tokens[$index]->getContent(); if ($tokens[$index]->isGivenKind(\T_COMMENT)) { if (str_starts_with($content, '//')) { $content = '/*'.substr($content, 2).' */'; $tokens->clearAt($index + 1); } elseif (str_starts_with($content, '#')) { $content = '/*'.substr($content, 1).' */'; $tokens->clearAt($index + 1); } elseif (Preg::match('/\R/', $content)) { $content = Preg::replace('/\R/', ' ', $content); } $tokens[$index] = new Token([\T_COMMENT, $content]); continue; } if (!$tokens[$index]->isGivenKind(\T_WHITESPACE)) { continue; } if (!Preg::match('/\R/', $content)) { continue; } $prevIndex = $tokens->getNonEmptySibling($index, -1); if ($this->isPreviousTokenToClear($tokens[$prevIndex])) { $tokens->clearAt($index); continue; } $nextIndex = $tokens->getNonEmptySibling($index, 1); if ( $this->isNextTokenToClear($tokens[$nextIndex]) && !$tokens[$prevIndex]->isGivenKind(\T_FUNCTION) ) { $tokens->clearAt($index); continue; } $tokens[$index] = new Token([\T_WHITESPACE, ' ']); } } private function isPreviousTokenToClear(Token $token): bool { return $token->equalsAny([...self::REMOVE_WHITESPACE_AFTER_TOKENS, ...self::REMOVE_WHITESPACE_AROUND_TOKENS]) || $token->isObjectOperator(); } private function isNextTokenToClear(Token $token): bool { return $token->equalsAny([...self::REMOVE_WHITESPACE_AROUND_TOKENS, ...self::REMOVE_WHITESPACE_BEFORE_TOKENS]) || $token->isObjectOperator(); } }
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/FunctionNotation/MethodArgumentSpaceFixer.php
src/Fixer/FunctionNotation/MethodArgumentSpaceFixer.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\FunctionNotation; 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\Future; use PhpCsFixer\Preg; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * after_heredoc?: bool, * attribute_placement?: 'ignore'|'same_line'|'standalone', * keep_multiple_spaces_after_comma?: bool, * on_multiline?: 'ensure_fully_multiline'|'ensure_single_line'|'ignore', * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * after_heredoc: bool, * attribute_placement: 'ignore'|'same_line'|'standalone', * keep_multiple_spaces_after_comma: bool, * on_multiline: 'ensure_fully_multiline'|'ensure_single_line'|'ignore', * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @author Kuanhung Chen <ericj.tw@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class MethodArgumentSpaceFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'In method arguments and method call, there MUST NOT be a space before each comma and there MUST be one space after each comma. Argument lists 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 argument per line.', [ new CodeSample( "<?php\nfunction sample(\$a=10,\$b=20,\$c=30) {}\nsample(1, 2);\n", null, ), new CodeSample( "<?php\nfunction sample(\$a=10,\$b=20,\$c=30) {}\nsample(1, 2);\n", ['keep_multiple_spaces_after_comma' => false], ), new CodeSample( "<?php\nfunction sample(\$a=10,\$b=20,\$c=30) {}\nsample(1, 2);\n", ['keep_multiple_spaces_after_comma' => true], ), new CodeSample( "<?php\nfunction sample(\$a=10,\n \$b=20,\$c=30) {}\nsample(1,\n 2);\n", ['on_multiline' => 'ensure_fully_multiline'], ), new CodeSample( "<?php\nfunction sample(\n \$a=10,\n \$b=20,\n \$c=30\n) {}\nsample(\n 1,\n 2\n);\n", ['on_multiline' => 'ensure_single_line'], ), new CodeSample( "<?php\nfunction sample(\$a=10,\n \$b=20,\$c=30) {}\nsample(1, \n 2);\nsample('foo', 'foobarbaz', 'baz');\nsample('foobar', 'bar', 'baz');\n", [ 'on_multiline' => 'ensure_fully_multiline', 'keep_multiple_spaces_after_comma' => true, ], ), new CodeSample( "<?php\nfunction sample(\$a=10,\n \$b=20,\$c=30) {}\nsample(1, \n 2);\nsample('foo', 'foobarbaz', 'baz');\nsample('foobar', 'bar', 'baz');\n", [ 'on_multiline' => 'ensure_fully_multiline', 'keep_multiple_spaces_after_comma' => false, ], ), new CodeSample( "<?php\nfunction sample(#[Foo] #[Bar] \$a=10,\n \$b=20,\$c=30) {}\nsample(1, 2);\n", [ 'on_multiline' => 'ensure_fully_multiline', 'attribute_placement' => 'ignore', ], ), new CodeSample( "<?php\nfunction sample(#[Foo]\n #[Bar]\n \$a=10,\n \$b=20,\$c=30) {}\nsample(1, 2);\n", [ 'on_multiline' => 'ensure_fully_multiline', 'attribute_placement' => 'same_line', ], ), new CodeSample( "<?php\nfunction sample(#[Foo] #[Bar] \$a=10,\n \$b=20,\$c=30) {}\nsample(1, 2);\n", [ 'on_multiline' => 'ensure_fully_multiline', 'attribute_placement' => 'standalone', ], ), new CodeSample( <<<'SAMPLE' <?php sample( <<<EOD foo EOD , 'bar' ); SAMPLE, ['after_heredoc' => true], ), ], 'This fixer covers rules defined in PSR2 ¶4.4, ¶4.6.', ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound('('); } /** * {@inheritdoc} * * Must run before ArrayIndentationFixer, StatementIndentationFixer. * Must run after CombineNestedDirnameFixer, FunctionDeclarationFixer, ImplodeCallFixer, LambdaNotUsedImportFixer, NoMultilineWhitespaceAroundDoubleArrowFixer, NoUselessSprintfFixer, PowToExponentiationFixer, StrictParamFixer. */ public function getPriority(): int { return 30; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $expectedTokens = [\T_LIST, \T_FUNCTION, CT::T_USE_LAMBDA, \T_FN, \T_CLASS]; $tokenCount = $tokens->count(); for ($index = 1; $index < $tokenCount; ++$index) { $token = $tokens[$index]; if (!$token->equals('(')) { continue; } $meaningfulTokenBeforeParenthesis = $tokens[$tokens->getPrevMeaningfulToken($index)]; if ( $meaningfulTokenBeforeParenthesis->isKeyword() && !$meaningfulTokenBeforeParenthesis->isGivenKind($expectedTokens) ) { continue; } $isMultiline = $this->fixFunction($tokens, $index); if ( $isMultiline && 'ensure_fully_multiline' === $this->configuration['on_multiline'] && !$meaningfulTokenBeforeParenthesis->isGivenKind(\T_LIST) ) { $this->ensureFunctionFullyMultiline($tokens, $index); } } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('keep_multiple_spaces_after_comma', 'Whether keep multiple spaces after comma.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), (new FixerOptionBuilder( 'on_multiline', 'Defines how to handle function arguments lists that contain newlines.', )) ->setAllowedValues(['ignore', 'ensure_single_line', 'ensure_fully_multiline']) ->setDefault('ensure_fully_multiline') ->getOption(), (new FixerOptionBuilder('after_heredoc', 'Whether the whitespace between heredoc end and comma should be removed.')) ->setAllowedTypes(['bool']) ->setDefault(Future::getV4OrV3(true, false)) ->getOption(), (new FixerOptionBuilder( 'attribute_placement', 'Defines how to handle argument attributes when function definition is multiline.', )) ->setAllowedValues(['ignore', 'same_line', 'standalone']) ->setDefault('standalone') ->getOption(), ]); } /** * Fix arguments spacing for given function. * * @param Tokens $tokens Tokens to handle * @param int $startFunctionIndex Start parenthesis position * * @return bool whether the function is multiline */ private function fixFunction(Tokens $tokens, int $startFunctionIndex): bool { $isMultiline = false; $endFunctionIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startFunctionIndex); $firstWhitespaceIndex = $this->findWhitespaceIndexAfterParenthesis($tokens, $startFunctionIndex, $endFunctionIndex); $lastWhitespaceIndex = $this->findWhitespaceIndexAfterParenthesis($tokens, $endFunctionIndex, $startFunctionIndex); foreach ([$firstWhitespaceIndex, $lastWhitespaceIndex] as $index) { if (null === $index || !Preg::match('/\R/', $tokens[$index]->getContent())) { continue; } if ('ensure_single_line' !== $this->configuration['on_multiline']) { $isMultiline = true; continue; } $newLinesRemoved = $this->ensureSingleLine($tokens, $index); if (!$newLinesRemoved) { $isMultiline = true; } } for ($index = $endFunctionIndex - 1; $index > $startFunctionIndex; --$index) { $token = $tokens[$index]; if ($token->equals(')')) { $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); continue; } if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_CLOSE)) { $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index); continue; } if ($token->equals('}')) { $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); continue; } if ($token->equals(',')) { $this->fixSpace($tokens, $index); if (!$isMultiline && $this->isNewline($tokens[$index + 1])) { $isMultiline = true; } } } return $isMultiline; } private function findWhitespaceIndexAfterParenthesis(Tokens $tokens, int $startParenthesisIndex, int $endParenthesisIndex): ?int { $direction = $endParenthesisIndex > $startParenthesisIndex ? 1 : -1; $startIndex = $startParenthesisIndex + $direction; $endIndex = $endParenthesisIndex - $direction; for ($index = $startIndex; $index !== $endIndex; $index += $direction) { $token = $tokens[$index]; if ($token->isWhitespace()) { return $index; } if (!$token->isComment()) { break; } } return null; } /** * @return bool Whether newlines were removed from the whitespace token */ private function ensureSingleLine(Tokens $tokens, int $index): bool { $previousToken = $tokens[$index - 1]; if ($previousToken->isComment() && !str_starts_with($previousToken->getContent(), '/*')) { return false; } $content = Preg::replace('/\R\h*/', '', $tokens[$index]->getContent()); $tokens->ensureWhitespaceAtIndex($index, 0, $content); return true; } private function ensureFunctionFullyMultiline(Tokens $tokens, int $startFunctionIndex): void { // find out what the indentation is $searchIndex = $startFunctionIndex; do { $prevWhitespaceTokenIndex = $tokens->getPrevTokenOfKind( $searchIndex, [[\T_ENCAPSED_AND_WHITESPACE], [\T_INLINE_HTML], [\T_WHITESPACE]], ); $searchIndex = $prevWhitespaceTokenIndex; } while (null !== $prevWhitespaceTokenIndex && !str_contains($tokens[$prevWhitespaceTokenIndex]->getContent(), "\n") ); if (null === $prevWhitespaceTokenIndex) { $existingIndentation = ''; } elseif (!$tokens[$prevWhitespaceTokenIndex]->isGivenKind(\T_WHITESPACE)) { return; } else { $existingIndentation = $tokens[$prevWhitespaceTokenIndex]->getContent(); $lastLineIndex = strrpos($existingIndentation, "\n"); $existingIndentation = false === $lastLineIndex ? $existingIndentation : substr($existingIndentation, $lastLineIndex + 1); } $indentation = $existingIndentation.$this->whitespacesConfig->getIndent(); $endFunctionIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startFunctionIndex); $wasWhitespaceBeforeEndFunctionAddedAsNewToken = $tokens->ensureWhitespaceAtIndex( $tokens[$endFunctionIndex - 1]->isWhitespace() ? $endFunctionIndex - 1 : $endFunctionIndex, 0, $this->whitespacesConfig->getLineEnding().$existingIndentation, ); if ($wasWhitespaceBeforeEndFunctionAddedAsNewToken) { ++$endFunctionIndex; } for ($index = $endFunctionIndex - 1; $index > $startFunctionIndex; --$index) { $token = $tokens[$index]; // skip nested method calls and arrays if ($token->equals(')')) { $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); continue; } // skip nested arrays if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_CLOSE)) { $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index); continue; } if ($token->equals('}')) { $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); continue; } if ($tokens[$tokens->getNextMeaningfulToken($index)]->equals(')')) { continue; } if ($token->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { if ('standalone' === $this->configuration['attribute_placement']) { $this->fixNewline($tokens, $index, $indentation); } elseif ('same_line' === $this->configuration['attribute_placement']) { $this->ensureSingleLine($tokens, $index + 1); $tokens->ensureWhitespaceAtIndex($index + 1, 0, ' '); } $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); continue; } if ($token->equals(',')) { $this->fixNewline($tokens, $index, $indentation); } } $this->fixNewline($tokens, $startFunctionIndex, $indentation, false); } /** * Method to insert newline after comma, attribute or opening parenthesis. * * @param int $index index of a comma * @param string $indentation the indentation that should be used * @param bool $override whether to override the existing character or not */ private function fixNewline(Tokens $tokens, int $index, string $indentation, bool $override = true): void { if ($tokens[$index + 1]->isComment()) { return; } if ($tokens[$index + 2]->isComment()) { $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($index + 2); if (!$this->isNewline($tokens[$nextMeaningfulTokenIndex - 1])) { if ($tokens[$nextMeaningfulTokenIndex - 1]->isWhitespace()) { $tokens->clearAt($nextMeaningfulTokenIndex - 1); } $tokens->ensureWhitespaceAtIndex($nextMeaningfulTokenIndex, 0, $this->whitespacesConfig->getLineEnding().$indentation); } return; } $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($index); if ($tokens[$nextMeaningfulTokenIndex]->equals(')')) { return; } $tokens->ensureWhitespaceAtIndex($index + 1, 0, $this->whitespacesConfig->getLineEnding().$indentation); } /** * Method to insert space after comma and remove space before comma. */ private function fixSpace(Tokens $tokens, int $index): void { // remove space before comma if exist if ($tokens[$index - 1]->isWhitespace()) { $prevIndex = $tokens->getPrevNonWhitespace($index - 1); if ( !$tokens[$prevIndex]->equals(',') && !$tokens[$prevIndex]->isComment() && (true === $this->configuration['after_heredoc'] || !$tokens[$prevIndex]->isGivenKind(\T_END_HEREDOC)) ) { $tokens->clearAt($index - 1); } } $nextIndex = $index + 1; $nextToken = $tokens[$nextIndex]; // Two cases for fix space after comma (exclude multiline comments) // 1) multiple spaces after comma // 2) no space after comma if ($nextToken->isWhitespace()) { $newContent = $nextToken->getContent(); if ('ensure_single_line' === $this->configuration['on_multiline']) { $newContent = Preg::replace('/\R/', '', $newContent); } if ( (false === $this->configuration['keep_multiple_spaces_after_comma'] || Preg::match('/\R/', $newContent)) && !$this->isCommentLastLineToken($tokens, $index + 2) ) { $newContent = ltrim($newContent, " \t"); } $tokens[$nextIndex] = new Token([\T_WHITESPACE, '' === $newContent ? ' ' : $newContent]); return; } if (!$this->isCommentLastLineToken($tokens, $index + 1)) { $tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' '])); } } /** * Check if last item of current line is a comment. * * @param Tokens $tokens tokens to handle * @param int $index index of token */ private function isCommentLastLineToken(Tokens $tokens, int $index): bool { if (!$tokens[$index]->isComment() || !$tokens[$index + 1]->isWhitespace()) { return false; } $content = $tokens[$index + 1]->getContent(); return $content !== ltrim($content, "\r\n"); } /** * Checks if token is new line. */ private function isNewline(Token $token): bool { return $token->isWhitespace() && str_contains($token->getContent(), "\n"); } }
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/FunctionNotation/StaticLambdaFixer.php
src/Fixer/FunctionNotation/StaticLambdaFixer.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\FunctionNotation; 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; /** * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class StaticLambdaFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Lambdas not (indirectly) referencing `$this` must be declared `static`.', [new CodeSample("<?php\n\$a = function () use (\$b)\n{ echo \$b;\n};\n")], null, 'Risky when using `->bindTo` on lambdas without referencing to `$this`.', ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); } public function isRisky(): bool { return true; } /** * {@inheritdoc} * * Must run after StaticPrivateMethodFixer. */ public function getPriority(): int { return parent::getPriority(); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $analyzer = new TokensAnalyzer($tokens); $expectedFunctionKinds = [\T_FUNCTION, \T_FN]; for ($index = $tokens->count() - 4; $index > 0; --$index) { if (!$tokens[$index]->isGivenKind($expectedFunctionKinds) || !$analyzer->isLambda($index)) { continue; } $prev = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prev]->isGivenKind(\T_STATIC)) { continue; // lambda is already 'static' } $argumentsStartIndex = $tokens->getNextTokenOfKind($index, ['(']); $argumentsEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $argumentsStartIndex); // figure out where the lambda starts and ends if ($tokens[$index]->isGivenKind(\T_FUNCTION)) { $lambdaOpenIndex = $tokens->getNextTokenOfKind($argumentsEndIndex, ['{']); $lambdaEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $lambdaOpenIndex); } else { // T_FN $lambdaOpenIndex = $tokens->getNextTokenOfKind($argumentsEndIndex, [[\T_DOUBLE_ARROW]]); $lambdaEndIndex = $analyzer->getLastTokenIndexOfArrowFunction($index); } if ($this->hasPossibleReferenceToThis($tokens, $lambdaOpenIndex, $lambdaEndIndex)) { continue; } // make the lambda static $tokens->insertAt( $index, [ new Token([\T_STATIC, 'static']), new Token([\T_WHITESPACE, ' ']), ], ); $index -= 4; // fixed after a lambda, closes candidate is at least 4 tokens before that } } /** * Returns 'true' if there is a possible reference to '$this' within the given tokens index range. */ private function hasPossibleReferenceToThis(Tokens $tokens, int $startIndex, int $endIndex): bool { for ($i = $startIndex; $i <= $endIndex; ++$i) { if ($tokens[$i]->isGivenKind(\T_VARIABLE) && '$this' === strtolower($tokens[$i]->getContent())) { return true; // directly accessing '$this' } if ($tokens[$i]->isGivenKind([ \T_INCLUDE, // loading additional symbols we cannot analyse here \T_INCLUDE_ONCE, // " \T_REQUIRE, // " \T_REQUIRE_ONCE, // " CT::T_DYNAMIC_VAR_BRACE_OPEN, // "$h = ${$g};" case \T_EVAL, // "$c = eval('return $this;');" case ])) { return true; } if ($tokens[$i]->isClassy()) { $openBraceIndex = $tokens->getNextTokenOfKind($i, ['{']); $i = $tokens->getNextMeaningfulToken($i); if ($i <= $openBraceIndex && $this->hasPossibleReferenceToThis( $tokens, $i, $openBraceIndex, )) { return true; } $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openBraceIndex); continue; } if ($tokens[$i]->equals('$')) { $nextIndex = $tokens->getNextMeaningfulToken($i); if ($tokens[$nextIndex]->isGivenKind(\T_VARIABLE)) { return true; // "$$a" case } } if ($tokens[$i]->equals([\T_STRING, 'parent'], false)) { return true; // parent:: case } } 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/FunctionNotation/PhpdocToReturnTypeFixer.php
src/Fixer/FunctionNotation/PhpdocToReturnTypeFixer.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\FunctionNotation; use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer; use PhpCsFixer\Fixer\ConfigurableFixerInterface; use PhpCsFixer\Fixer\ExperimentalFixerInterface; 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; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * scalar_types?: bool, * types_map?: array<string, string>, * union_types?: bool, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * scalar_types: bool, * types_map: array<string, string>, * union_types: bool, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @phpstan-import-type _PhpTokenArray from Token * * @author Filippo Tessarotto <zoeslam@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocToReturnTypeFixer extends AbstractPhpdocToTypeDeclarationFixer implements ConfigurableFixerInterface, ExperimentalFixerInterface { private const TYPE_CHECK_TEMPLATE = '<?php function f(): %s {}'; /** * @var non-empty-list<_PhpTokenArray> */ private array $excludeFuncNames = [ [\T_STRING, '__construct'], [\T_STRING, '__destruct'], [\T_STRING, '__clone'], ]; /** * @var array<string, true> */ private array $skippedTypes = [ 'resource' => true, 'null' => true, ]; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Takes `@return` annotation of non-mixed types and adjusts accordingly the function signature.', [ new CodeSample( <<<'PHP' <?php /** @return \My\Bar */ function f1() {} /** @return void */ function f2() {} /** @return object */ function my_foo() {} PHP, ), new CodeSample( <<<'PHP' <?php /** @return Foo */ function foo() {} /** @return string */ function bar() {} PHP, ['scalar_types' => false], ), new CodeSample( <<<'PHP' <?php /** @return Foo */ function foo() {} /** @return int|string */ function bar() {} PHP, ['union_types' => false], ), new VersionSpecificCodeSample( <<<'PHP' <?php final class Foo { /** * @return static */ public function create($prototype) { return new static($prototype); } } PHP, new VersionSpecification(8_00_00), ), ], null, 'The `@return` annotation is mandatory for the fixer to make changes, signatures of methods without it (no docblock, inheritdocs) will not be fixed. Manual actions are required if inherited signatures are not properly documented.', ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); } /** * {@inheritdoc} * * Must run before FullyQualifiedStrictTypesFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer, ReturnToYieldFromFixer, ReturnTypeDeclarationFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 13; } protected function isSkippedType(string $type): bool { return isset($this->skippedTypes[$type]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $tokensToInsert = []; $typesToExclude = []; foreach ($tokens as $index => $token) { if ($token->isGivenKind(\T_DOC_COMMENT)) { $typesToExclude = array_merge($typesToExclude, self::getTypesToExclude($token->getContent())); continue; } if (!$tokens[$index]->isGivenKind([\T_FUNCTION, \T_FN])) { continue; } $funcName = $tokens->getNextMeaningfulToken($index); if ($tokens[$funcName]->equalsAny($this->excludeFuncNames, false)) { continue; } $docCommentIndex = $this->findFunctionDocComment($tokens, $index); if (null === $docCommentIndex) { continue; } $returnTypeAnnotations = $this->getAnnotationsFromDocComment('return', $tokens, $docCommentIndex); if (1 !== \count($returnTypeAnnotations)) { continue; } $returnTypeAnnotation = $returnTypeAnnotations[0]; $typesExpression = $returnTypeAnnotation->getTypeExpression(); if (null === $typesExpression) { continue; } $typeInfo = $this->getCommonTypeInfo($typesExpression, true); $unionTypes = null; if (null === $typeInfo) { $unionTypes = $this->getUnionTypes($typesExpression, true); } if (null === $typeInfo && null === $unionTypes) { continue; } if (null !== $typeInfo) { $returnType = $typeInfo['commonType']; $isNullable = $typeInfo['isNullable']; } elseif (null !== $unionTypes) { $returnType = $unionTypes; $isNullable = false; } if (!isset($returnType, $isNullable)) { continue; } if (\in_array($returnType, $typesToExclude, true)) { continue; } $paramsStartIndex = $tokens->getNextTokenOfKind($index, ['(']); $paramsEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $paramsStartIndex); $bodyStartIndex = $tokens->getNextTokenOfKind($paramsEndIndex, ['{', ';', [\T_DOUBLE_ARROW]]); if ($this->hasReturnTypeHint($tokens, $bodyStartIndex)) { continue; } if (!$this->isValidSyntax(\sprintf(self::TYPE_CHECK_TEMPLATE, $returnType))) { continue; } $tokensToInsert[$paramsEndIndex + 1] = array_merge( [ new Token([CT::T_TYPE_COLON, ':']), new Token([\T_WHITESPACE, ' ']), ], $this->createTypeDeclarationTokens($returnType, $isNullable), ); } $tokens->insertSlices($tokensToInsert); } protected function createTokensFromRawType(string $type): Tokens { $typeTokens = Tokens::fromCode(\sprintf(self::TYPE_CHECK_TEMPLATE, $type)); $typeTokens->clearRange(0, 7); $typeTokens->clearRange(\count($typeTokens) - 3, \count($typeTokens) - 1); $typeTokens->clearEmptyTokens(); return $typeTokens; } /** * Determine whether the function already has a return type hint. * * @param int $index The index of the end of the function definition line, EG at { or ; */ private function hasReturnTypeHint(Tokens $tokens, int $index): bool { $endFuncIndex = $tokens->getPrevTokenOfKind($index, [')']); $nextIndex = $tokens->getNextMeaningfulToken($endFuncIndex); return $tokens[$nextIndex]->isGivenKind(CT::T_TYPE_COLON); } }
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/FunctionNotation/FunctionTypehintSpaceFixer.php
src/Fixer/FunctionNotation/FunctionTypehintSpaceFixer.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\FunctionNotation; use PhpCsFixer\AbstractProxyFixer; use PhpCsFixer\Fixer\DeprecatedFixerInterface; use PhpCsFixer\Fixer\Whitespace\TypeDeclarationSpacesFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Tokens; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @deprecated * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class FunctionTypehintSpaceFixer extends AbstractProxyFixer implements DeprecatedFixerInterface { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Ensure single space between function\'s argument and its typehint.', [ new CodeSample("<?php\nfunction sample(array\$a)\n{}\n"), new CodeSample("<?php\nfunction sample(array \$a)\n{}\n"), ], ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); } public function getSuccessorsNames(): array { return array_keys($this->proxyFixers); } protected function createProxyFixers(): array { $fixer = new TypeDeclarationSpacesFixer(); $fixer->configure(['elements' => ['function']]); 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/FunctionNotation/CombineNestedDirnameFixer.php
src/Fixer/FunctionNotation/CombineNestedDirnameFixer.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\FunctionNotation; 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; /** * @author Gregor Harlan * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class CombineNestedDirnameFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Replace multiple nested calls of `dirname` by only one call with second `$level` parameter.', [ new CodeSample( "<?php\ndirname(dirname(dirname(\$path)));\n", ), ], null, 'Risky when the function `dirname` is overridden.', ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_STRING); } public function isRisky(): bool { return true; } /** * {@inheritdoc} * * Must run before MethodArgumentSpaceFixer, NoSpacesInsideParenthesisFixer, SpacesInsideParenthesesFixer. * Must run after DirConstantFixer. */ public function getPriority(): int { return 35; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { for ($index = $tokens->count() - 1; 0 <= $index; --$index) { $dirnameInfo = $this->getDirnameInfo($tokens, $index); if (false === $dirnameInfo) { continue; } $prev = $tokens->getPrevMeaningfulToken($dirnameInfo['indices'][0]); if (!$tokens[$prev]->equals('(')) { continue; } $prev = $tokens->getPrevMeaningfulToken($prev); $firstArgumentEnd = $dirnameInfo['end']; $dirnameInfoArray = [$dirnameInfo]; while (($dirnameInfo = $this->getDirnameInfo($tokens, $prev, $firstArgumentEnd)) !== false) { $dirnameInfoArray[] = $dirnameInfo; $prev = $tokens->getPrevMeaningfulToken($dirnameInfo['indices'][0]); if (!$tokens[$prev]->equals('(')) { break; } $prev = $tokens->getPrevMeaningfulToken($prev); $firstArgumentEnd = $dirnameInfo['end']; } if (\count($dirnameInfoArray) > 1) { $this->combineDirnames($tokens, $dirnameInfoArray); } $index = $prev; } } /** * @param int $index Index of `dirname` * @param null|int $firstArgumentEndIndex Index of last token of first argument of `dirname` call * * @return array{indices: non-empty-list<int>, secondArgument?: int, levels: int, end: int}|false `false` when it is not a (supported) `dirname` call, an array with info about the dirname call otherwise */ private function getDirnameInfo(Tokens $tokens, int $index, ?int $firstArgumentEndIndex = null) { if (!$tokens[$index]->equals([\T_STRING, 'dirname'], false)) { return false; } if (!(new FunctionsAnalyzer())->isGlobalFunctionCall($tokens, $index)) { return false; } $info = ['indices' => []]; $prev = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prev]->isGivenKind(\T_NS_SEPARATOR)) { $info['indices'][] = $prev; } $info['indices'][] = $index; // opening parenthesis "(" $next = $tokens->getNextMeaningfulToken($index); $info['indices'][] = $next; if (null !== $firstArgumentEndIndex) { $next = $tokens->getNextMeaningfulToken($firstArgumentEndIndex); } else { $next = $tokens->getNextMeaningfulToken($next); if ($tokens[$next]->equals(')')) { return false; } while (!$tokens[$next]->equalsAny([',', ')'])) { $blockType = Tokens::detectBlockType($tokens[$next]); if (null !== $blockType) { $next = $tokens->findBlockEnd($blockType['type'], $next); } $next = $tokens->getNextMeaningfulToken($next); } } $info['indices'][] = $next; if ($tokens[$next]->equals(',')) { $next = $tokens->getNextMeaningfulToken($next); $info['indices'][] = $next; } if ($tokens[$next]->equals(')')) { $info['levels'] = 1; $info['end'] = $next; return $info; } if (!$tokens[$next]->isGivenKind(\T_LNUMBER)) { return false; } $info['secondArgument'] = $next; $info['levels'] = (int) $tokens[$next]->getContent(); $next = $tokens->getNextMeaningfulToken($next); if ($tokens[$next]->equals(',')) { $info['indices'][] = $next; $next = $tokens->getNextMeaningfulToken($next); } if (!$tokens[$next]->equals(')')) { return false; } $info['indices'][] = $next; $info['end'] = $next; return $info; } /** * @param non-empty-list<array{indices: non-empty-list<int>, secondArgument?: int, levels: int, end: int}> $dirnameInfoArray */ private function combineDirnames(Tokens $tokens, array $dirnameInfoArray): void { $outerDirnameInfo = array_pop($dirnameInfoArray); $levels = $outerDirnameInfo['levels']; foreach ($dirnameInfoArray as $dirnameInfo) { $levels += $dirnameInfo['levels']; foreach ($dirnameInfo['indices'] as $index) { $tokens->removeLeadingWhitespace($index); $tokens->clearTokenAndMergeSurroundingWhitespace($index); } } $levelsToken = new Token([\T_LNUMBER, (string) $levels]); if (isset($outerDirnameInfo['secondArgument'])) { $tokens[$outerDirnameInfo['secondArgument']] = $levelsToken; } else { $prev = $tokens->getPrevMeaningfulToken($outerDirnameInfo['end']); $items = []; if (!$tokens[$prev]->equals(',')) { $items = [new Token(','), new Token([\T_WHITESPACE, ' '])]; } $items[] = $levelsToken; $tokens->insertAt($outerDirnameInfo['end'], $items); } } }
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/FunctionNotation/ImplodeCallFixer.php
src/Fixer/FunctionNotation/ImplodeCallFixer.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\FunctionNotation; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; 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 ImplodeCallFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Function `implode` must be called with 2 arguments in the documented order.', [ new CodeSample("<?php\nimplode(\$pieces, '');\n"), new CodeSample("<?php\nimplode(\$pieces);\n"), ], null, 'Risky when the function `implode` is overridden.', ); } public function isRisky(): bool { return true; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_STRING); } /** * {@inheritdoc} * * Must run before MethodArgumentSpaceFixer. * Must run after NoAliasFunctionsFixer. */ public function getPriority(): int { return 37; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $functionsAnalyzer = new FunctionsAnalyzer(); for ($index = \count($tokens) - 1; $index > 0; --$index) { if (!$tokens[$index]->equals([\T_STRING, 'implode'], false)) { continue; } if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { continue; } $argumentsIndices = $this->getArgumentIndices($tokens, $index); if (1 === \count($argumentsIndices)) { $firstArgumentIndex = array_key_first($argumentsIndices); $tokens->insertAt($firstArgumentIndex, [ new Token([\T_CONSTANT_ENCAPSED_STRING, "''"]), new Token(','), new Token([\T_WHITESPACE, ' ']), ]); continue; } if (2 === \count($argumentsIndices)) { [$firstArgumentIndex, $secondArgumentIndex] = array_keys($argumentsIndices); // If the first argument is string we have nothing to do if ($tokens[$firstArgumentIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { continue; } // If the second argument is not string we cannot make a swap if (!$tokens[$secondArgumentIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { continue; } // collect tokens from first argument $firstArgumentEndIndex = $argumentsIndices[key($argumentsIndices)]; $newSecondArgumentTokens = []; for ($i = array_key_first($argumentsIndices); $i <= $firstArgumentEndIndex; ++$i) { $newSecondArgumentTokens[] = clone $tokens[$i]; $tokens->clearAt($i); } $tokens->insertAt($firstArgumentIndex, clone $tokens[$secondArgumentIndex]); // insert above increased the second argument index ++$secondArgumentIndex; $tokens->clearAt($secondArgumentIndex); $tokens->insertAt($secondArgumentIndex, $newSecondArgumentTokens); } } } /** * @return array<int, int> In the format: startIndex => endIndex */ private function getArgumentIndices(Tokens $tokens, int $functionNameIndex): array { $argumentsAnalyzer = new ArgumentsAnalyzer(); $openParenthesis = $tokens->getNextTokenOfKind($functionNameIndex, ['(']); $closeParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis); $indices = []; foreach ($argumentsAnalyzer->getArguments($tokens, $openParenthesis, $closeParenthesis) as $startIndexCandidate => $endIndex) { $indices[$tokens->getNextMeaningfulToken($startIndexCandidate - 1)] = $tokens->getPrevMeaningfulToken($endIndex + 1); } return $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/FunctionNotation/RegularCallableCallFixer.php
src/Fixer/FunctionNotation/RegularCallableCallFixer.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\FunctionNotation; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; 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 RegularCallableCallFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Callables must be called without using `call_user_func*` when possible.', [ new CodeSample( <<<'PHP' <?php call_user_func("var_dump", 1, 2); call_user_func("Bar\Baz::d", 1, 2); call_user_func_array($callback, [1, 2]); PHP, ), new CodeSample( <<<'PHP' <?php call_user_func(function ($a, $b) { var_dump($a, $b); }, 1, 2); call_user_func(static function ($a, $b) { var_dump($a, $b); }, 1, 2); PHP, ), ], null, 'Risky when the `call_user_func` or `call_user_func_array` function is overridden or when are used in constructions that should be avoided, like `call_user_func_array(\'foo\', [\'bar\' => \'baz\'])` or `call_user_func($foo, $foo = \'bar\')`.', ); } /** * {@inheritdoc} * * Must run before NativeFunctionInvocationFixer. * Must run after NoBinaryStringFixer, NoUselessConcatOperatorFixer. */ public function getPriority(): int { return 2; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_STRING); } public function isRisky(): bool { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $functionsAnalyzer = new FunctionsAnalyzer(); $argumentsAnalyzer = new ArgumentsAnalyzer(); for ($index = $tokens->count() - 1; $index > 0; --$index) { if (!$tokens[$index]->equalsAny([[\T_STRING, 'call_user_func'], [\T_STRING, 'call_user_func_array']], false)) { continue; } if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { continue; // redeclare/override } $openParenthesis = $tokens->getNextMeaningfulToken($index); $closeParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis); $arguments = $argumentsAnalyzer->getArguments($tokens, $openParenthesis, $closeParenthesis); if (1 > \count($arguments)) { return; // no arguments! } $this->processCall($tokens, $index, $arguments); } } /** * @param non-empty-array<int, int> $arguments */ private function processCall(Tokens $tokens, int $index, array $arguments): void { $firstArgIndex = $tokens->getNextMeaningfulToken( $tokens->getNextMeaningfulToken($index), ); $firstArgToken = $tokens[$firstArgIndex]; if ($firstArgToken->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { $afterFirstArgIndex = $tokens->getNextMeaningfulToken($firstArgIndex); if (!$tokens[$afterFirstArgIndex]->equalsAny([',', ')'])) { return; // first argument is an expression like `call_user_func("foo"."bar", ...)`, not supported! } $firstArgTokenContent = $firstArgToken->getContent(); if (!$this->isValidFunctionInvoke($firstArgTokenContent)) { return; } $newCallTokens = Tokens::fromCode('<?php '.substr(str_replace('\\\\', '\\', $firstArgToken->getContent()), 1, -1).'();'); $newCallTokensSize = $newCallTokens->count(); $newCallTokens->clearAt(0); $newCallTokens->clearRange($newCallTokensSize - 3, $newCallTokensSize - 1); $newCallTokens->clearEmptyTokens(); $this->replaceCallUserFuncWithCallback($tokens, $index, $newCallTokens, $firstArgIndex, $firstArgIndex); } elseif ( $firstArgToken->isGivenKind(\T_FUNCTION) || ( $firstArgToken->isGivenKind(\T_STATIC) && $tokens[$tokens->getNextMeaningfulToken($firstArgIndex)]->isGivenKind(\T_FUNCTION) ) ) { $firstArgEndIndex = $tokens->findBlockEnd( Tokens::BLOCK_TYPE_CURLY_BRACE, $tokens->getNextTokenOfKind($firstArgIndex, ['{']), ); $newCallTokens = $this->getTokensSubcollection($tokens, $firstArgIndex, $firstArgEndIndex); $newCallTokens->insertAt($newCallTokens->count(), new Token(')')); $newCallTokens->insertAt(0, new Token('(')); $this->replaceCallUserFuncWithCallback($tokens, $index, $newCallTokens, $firstArgIndex, $firstArgEndIndex); } elseif ($firstArgToken->isGivenKind(\T_VARIABLE)) { $firstArgEndIndex = reset($arguments); // check if the same variable is used multiple times and if so do not fix foreach ($arguments as $argumentStart => $argumentEnd) { if ($firstArgEndIndex === $argumentEnd) { continue; } for ($i = $argumentStart; $i <= $argumentEnd; ++$i) { if ($tokens[$i]->equals($firstArgToken)) { return; } } } // check if complex statement and if so wrap the call in () if on PHP 7 or up, else do not fix $newCallTokens = $this->getTokensSubcollection($tokens, $firstArgIndex, $firstArgEndIndex); $complex = false; for ($newCallIndex = \count($newCallTokens) - 1; $newCallIndex >= 0; --$newCallIndex) { if ($newCallTokens[$newCallIndex]->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT, \T_VARIABLE])) { continue; } $blockType = Tokens::detectBlockType($newCallTokens[$newCallIndex]); if (null !== $blockType && (Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE === $blockType['type'] || Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE === $blockType['type'])) { $newCallIndex = $newCallTokens->findBlockStart($blockType['type'], $newCallIndex); continue; } $complex = true; break; } if ($complex) { $newCallTokens->insertAt($newCallTokens->count(), new Token(')')); $newCallTokens->insertAt(0, new Token('(')); } $this->replaceCallUserFuncWithCallback($tokens, $index, $newCallTokens, $firstArgIndex, $firstArgEndIndex); } } private function replaceCallUserFuncWithCallback(Tokens $tokens, int $callIndex, Tokens $newCallTokens, int $firstArgStartIndex, int $firstArgEndIndex): void { $tokens->clearRange($firstArgStartIndex, $firstArgEndIndex); $afterFirstArgIndex = $tokens->getNextMeaningfulToken($firstArgEndIndex); $afterFirstArgToken = $tokens[$afterFirstArgIndex]; if ($afterFirstArgToken->equals(',')) { $useEllipsis = $tokens[$callIndex]->equals([\T_STRING, 'call_user_func_array'], false); if ($useEllipsis) { $secondArgIndex = $tokens->getNextMeaningfulToken($afterFirstArgIndex); $tokens->insertAt($secondArgIndex, new Token([\T_ELLIPSIS, '...'])); } $tokens->clearAt($afterFirstArgIndex); $tokens->removeTrailingWhitespace($afterFirstArgIndex); } $tokens->overrideRange($callIndex, $callIndex, $newCallTokens); $prevIndex = $tokens->getPrevMeaningfulToken($callIndex); if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); } } private function getTokensSubcollection(Tokens $tokens, int $indexStart, int $indexEnd): Tokens { $size = $indexEnd - $indexStart + 1; $subCollection = new Tokens($size); for ($i = 0; $i < $size; ++$i) { $toClone = $tokens[$i + $indexStart]; $subCollection[$i] = clone $toClone; } return $subCollection; } private function isValidFunctionInvoke(string $name): bool { if (\strlen($name) < 3 || 'b' === $name[0] || 'B' === $name[0]) { return false; } $name = substr($name, 1, -1); if ($name !== trim($name)) { 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/FunctionNotation/NoUselessSprintfFixer.php
src/Fixer/FunctionNotation/NoUselessSprintfFixer.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\FunctionNotation; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; use PhpCsFixer\Tokenizer\Tokens; /** * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NoUselessSprintfFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'There must be no `sprintf` calls with only the first argument.', [ new CodeSample( "<?php\n\$foo = sprintf('bar');\n", ), ], null, 'Risky when if the `sprintf` function is overridden.', ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_STRING); } public function isRisky(): bool { return true; } /** * {@inheritdoc} * * Must run before MethodArgumentSpaceFixer, NativeFunctionCasingFixer, NoEmptyStatementFixer, NoExtraBlankLinesFixer, NoSpacesInsideParenthesisFixer, SpacesInsideParenthesesFixer. */ public function getPriority(): int { return 42; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $functionAnalyzer = new FunctionsAnalyzer(); $argumentsAnalyzer = new ArgumentsAnalyzer(); for ($index = \count($tokens) - 1; $index > 0; --$index) { if (!$tokens[$index]->isGivenKind(\T_STRING)) { continue; } if ('sprintf' !== strtolower($tokens[$index]->getContent())) { continue; } if (!$functionAnalyzer->isGlobalFunctionCall($tokens, $index)) { continue; } $openParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(']); if ($tokens[$tokens->getNextMeaningfulToken($openParenthesisIndex)]->isGivenKind(\T_ELLIPSIS)) { continue; } $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesisIndex); if (1 !== $argumentsAnalyzer->countArguments($tokens, $openParenthesisIndex, $closeParenthesisIndex)) { continue; } $tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesisIndex); $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($closeParenthesisIndex); if ($tokens[$prevMeaningfulTokenIndex]->equals(',')) { $tokens->clearTokenAndMergeSurroundingWhitespace($prevMeaningfulTokenIndex); } $tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesisIndex); $tokens->clearTokenAndMergeSurroundingWhitespace($index); $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prevMeaningfulTokenIndex]->isGivenKind(\T_NS_SEPARATOR)) { $tokens->clearTokenAndMergeSurroundingWhitespace($prevMeaningfulTokenIndex); } } } }
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/FunctionNotation/LambdaNotUsedImportFixer.php
src/Fixer/FunctionNotation/LambdaNotUsedImportFixer.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\FunctionNotation; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Tokens; use PhpCsFixer\Tokenizer\TokensAnalyzer; /** * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class LambdaNotUsedImportFixer extends AbstractFixer { private ArgumentsAnalyzer $argumentsAnalyzer; private FunctionsAnalyzer $functionAnalyzer; private TokensAnalyzer $tokensAnalyzer; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Lambda must not import variables it doesn\'t use.', [new CodeSample("<?php\n\$foo = function() use (\$bar) {};\n")], ); } /** * {@inheritdoc} * * Must run before MethodArgumentSpaceFixer, NoSpacesInsideParenthesisFixer, SpacesInsideParenthesesFixer. */ public function getPriority(): int { return 31; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAllTokenKindsFound([\T_FUNCTION, CT::T_USE_LAMBDA]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $this->argumentsAnalyzer = new ArgumentsAnalyzer(); $this->functionAnalyzer = new FunctionsAnalyzer(); $this->tokensAnalyzer = new TokensAnalyzer($tokens); for ($index = $tokens->count() - 4; $index > 0; --$index) { $lambdaUseIndex = $this->getLambdaUseIndex($tokens, $index); if (false !== $lambdaUseIndex) { $this->fixLambda($tokens, $lambdaUseIndex); } } } private function fixLambda(Tokens $tokens, int $lambdaUseIndex): void { $lambdaUseOpenBraceIndex = $tokens->getNextTokenOfKind($lambdaUseIndex, ['(']); $lambdaUseCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $lambdaUseOpenBraceIndex); $arguments = $this->argumentsAnalyzer->getArguments($tokens, $lambdaUseOpenBraceIndex, $lambdaUseCloseBraceIndex); $imports = $this->filterArguments($tokens, $arguments); if (0 === \count($imports)) { return; // no imports to remove } $notUsedImports = $this->findNotUsedLambdaImports($tokens, $imports, $lambdaUseCloseBraceIndex); $notUsedImportsCount = \count($notUsedImports); if (0 === $notUsedImportsCount) { return; // no not used imports found } if ($notUsedImportsCount === \count($arguments)) { $this->clearImportsAndUse($tokens, $lambdaUseIndex, $lambdaUseCloseBraceIndex); // all imports are not used return; } $this->clearImports($tokens, array_reverse($notUsedImports)); } /** * @param array<string, int> $imports * * @return array<string, int> */ private function findNotUsedLambdaImports(Tokens $tokens, array $imports, int $lambdaUseCloseBraceIndex): array { // figure out where the lambda starts ... $lambdaOpenIndex = $tokens->getNextTokenOfKind($lambdaUseCloseBraceIndex, ['{']); $curlyBracesLevel = 0; for ($index = $lambdaOpenIndex;; ++$index) { // go through the body of the lambda and keep count of the (possible) usages of the imported variables $token = $tokens[$index]; if ($token->equals('{')) { ++$curlyBracesLevel; continue; } if ($token->equals('}')) { --$curlyBracesLevel; if (0 === $curlyBracesLevel) { break; } continue; } if ($token->isGivenKind(\T_STRING) && 'compact' === strtolower($token->getContent()) && $this->functionAnalyzer->isGlobalFunctionCall($tokens, $index)) { return []; // wouldn't touch it with a ten-foot pole } if ($token->isGivenKind([ CT::T_DYNAMIC_VAR_BRACE_OPEN, \T_EVAL, \T_INCLUDE, \T_INCLUDE_ONCE, \T_REQUIRE, \T_REQUIRE_ONCE, ])) { return []; } if ($token->equals('$')) { $nextIndex = $tokens->getNextMeaningfulToken($index); if ($tokens[$nextIndex]->isGivenKind(\T_VARIABLE)) { return []; // "$$a" case } } if ($token->isGivenKind(\T_VARIABLE)) { $content = $token->getContent(); if (isset($imports[$content])) { unset($imports[$content]); if (0 === \count($imports)) { return $imports; } } } if ($token->isGivenKind(\T_STRING_VARNAME)) { $content = '$'.$token->getContent(); if (isset($imports[$content])) { unset($imports[$content]); if (0 === \count($imports)) { return $imports; } } } if ($token->isClassy()) { // is anonymous class // check if used as argument in the constructor of the anonymous class $index = $tokens->getNextTokenOfKind($index, ['(', '{']); if ($tokens[$index]->equals('(')) { $closeBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); $arguments = $this->argumentsAnalyzer->getArguments($tokens, $index, $closeBraceIndex); $imports = $this->countImportsUsedAsArgument($tokens, $imports, $arguments); $index = $tokens->getNextTokenOfKind($closeBraceIndex, ['{']); } // skip body $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); continue; } if ($token->isGivenKind(\T_FUNCTION)) { // check if used as argument $lambdaUseOpenBraceIndex = $tokens->getNextTokenOfKind($index, ['(']); $lambdaUseCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $lambdaUseOpenBraceIndex); $arguments = $this->argumentsAnalyzer->getArguments($tokens, $lambdaUseOpenBraceIndex, $lambdaUseCloseBraceIndex); $imports = $this->countImportsUsedAsArgument($tokens, $imports, $arguments); // check if used as import $index = $tokens->getNextTokenOfKind($index, [[CT::T_USE_LAMBDA], '{']); if ($tokens[$index]->isGivenKind(CT::T_USE_LAMBDA)) { $lambdaUseOpenBraceIndex = $tokens->getNextTokenOfKind($index, ['(']); $lambdaUseCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $lambdaUseOpenBraceIndex); $arguments = $this->argumentsAnalyzer->getArguments($tokens, $lambdaUseOpenBraceIndex, $lambdaUseCloseBraceIndex); $imports = $this->countImportsUsedAsArgument($tokens, $imports, $arguments); $index = $tokens->getNextTokenOfKind($lambdaUseCloseBraceIndex, ['{']); } // skip body $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); continue; } } return $imports; } /** * @param array<string, int> $imports * @param array<int, int> $arguments * * @return array<string, int> */ private function countImportsUsedAsArgument(Tokens $tokens, array $imports, array $arguments): array { foreach ($arguments as $start => $end) { $info = $this->argumentsAnalyzer->getArgumentInfo($tokens, $start, $end); $content = $info->getName(); if (isset($imports[$content])) { unset($imports[$content]); if (0 === \count($imports)) { return $imports; } } } return $imports; } /** * @return false|int */ private function getLambdaUseIndex(Tokens $tokens, int $index) { if (!$tokens[$index]->isGivenKind(\T_FUNCTION) || !$this->tokensAnalyzer->isLambda($index)) { return false; } $lambdaUseIndex = $tokens->getNextMeaningfulToken($index); // we are @ '(' or '&' after this if ($tokens[$lambdaUseIndex]->isGivenKind(CT::T_RETURN_REF)) { $lambdaUseIndex = $tokens->getNextMeaningfulToken($lambdaUseIndex); } $lambdaUseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $lambdaUseIndex); // we are @ ')' after this $lambdaUseIndex = $tokens->getNextMeaningfulToken($lambdaUseIndex); if (!$tokens[$lambdaUseIndex]->isGivenKind(CT::T_USE_LAMBDA)) { return false; } return $lambdaUseIndex; } /** * @param array<int, int> $arguments * * @return array<string, int> */ private function filterArguments(Tokens $tokens, array $arguments): array { $imports = []; foreach ($arguments as $start => $end) { $info = $this->argumentsAnalyzer->getArgumentInfo($tokens, $start, $end); $argument = $info->getNameIndex(); if ($tokens[$tokens->getPrevMeaningfulToken($argument)]->equals('&')) { continue; } $argumentCandidate = $tokens[$argument]; if ('$this' === $argumentCandidate->getContent()) { continue; } if ($this->tokensAnalyzer->isSuperGlobal($argument)) { continue; } $imports[$argumentCandidate->getContent()] = $argument; } return $imports; } /** * @param array<string, int> $imports */ private function clearImports(Tokens $tokens, array $imports): void { foreach ($imports as $removeIndex) { $tokens->clearTokenAndMergeSurroundingWhitespace($removeIndex); $previousRemoveIndex = $tokens->getPrevMeaningfulToken($removeIndex); if ($tokens[$previousRemoveIndex]->equals(',')) { $tokens->clearTokenAndMergeSurroundingWhitespace($previousRemoveIndex); } elseif ($tokens[$previousRemoveIndex]->equals('(')) { $tokens->clearTokenAndMergeSurroundingWhitespace($tokens->getNextMeaningfulToken($removeIndex)); // next is always ',' here } } } /** * Remove `use` and all imported variables. */ private function clearImportsAndUse(Tokens $tokens, int $lambdaUseIndex, int $lambdaUseCloseBraceIndex): void { for ($i = $lambdaUseCloseBraceIndex; $i >= $lambdaUseIndex; --$i) { if ($tokens[$i]->isComment()) { continue; } if ($tokens[$i]->isWhitespace()) { $previousIndex = $tokens->getPrevNonWhitespace($i); if ($tokens[$previousIndex]->isComment()) { continue; } } $tokens->clearTokenAndMergeSurroundingWhitespace($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/FunctionNotation/NoSpacesAfterFunctionNameFixer.php
src/Fixer/FunctionNotation/NoSpacesAfterFunctionNameFixer.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\FunctionNotation; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Tokens; /** * Fixer for rules defined in PSR2 ¶4.6. * * @author Varga Bence <vbence@czentral.org> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NoSpacesAfterFunctionNameFixer extends AbstractFixer { /** * Token kinds which can work as function calls. */ private const FUNCTIONY_TOKEN_KINDS = [ \T_ARRAY, \T_ECHO, \T_EMPTY, \T_EVAL, \T_EXIT, \T_INCLUDE, \T_INCLUDE_ONCE, \T_ISSET, \T_LIST, \T_PRINT, \T_REQUIRE, \T_REQUIRE_ONCE, \T_UNSET, \T_VARIABLE, ]; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'When making a method or function call, there MUST NOT be a space between the method or function name and the opening parenthesis.', [new CodeSample("<?php\nstrlen ('Hello World!');\nfoo (test (3));\nexit (1);\n\$func ();\n")], ); } /** * {@inheritdoc} * * Must run before FunctionToConstantFixer, GetClassToClassKeywordFixer. * Must run after PowToExponentiationFixer. */ public function getPriority(): int { return 3; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound([\T_STRING, ...self::FUNCTIONY_TOKEN_KINDS]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ($tokens as $index => $token) { // looking for start brace if (!$token->equals('(')) { continue; } // last non-whitespace token, can never be `null` always at least PHP open tag before it $lastTokenIndex = $tokens->getPrevNonWhitespace($index); // check for ternary operator $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); $nextNonWhiteSpace = $tokens->getNextMeaningfulToken($endParenthesisIndex); if ( null !== $nextNonWhiteSpace && !$tokens[$nextNonWhiteSpace]->equals(';') && $tokens[$lastTokenIndex]->isGivenKind([ \T_ECHO, \T_PRINT, \T_INCLUDE, \T_INCLUDE_ONCE, \T_REQUIRE, \T_REQUIRE_ONCE, ]) ) { continue; } // check if it is a function call if ($tokens[$lastTokenIndex]->isGivenKind(self::FUNCTIONY_TOKEN_KINDS)) { $this->fixFunctionCall($tokens, $index); } elseif ($tokens[$lastTokenIndex]->isGivenKind(\T_STRING)) { // for real function calls or definitions $possibleDefinitionIndex = $tokens->getPrevMeaningfulToken($lastTokenIndex); if (!$tokens[$possibleDefinitionIndex]->isGivenKind(\T_FUNCTION)) { $this->fixFunctionCall($tokens, $index); } } elseif ($tokens[$lastTokenIndex]->equalsAny([ ')', ']', [CT::T_DYNAMIC_VAR_BRACE_CLOSE], [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], ])) { $block = Tokens::detectBlockType($tokens[$lastTokenIndex]); if ( Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE === $block['type'] || Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE === $block['type'] || Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE === $block['type'] || Tokens::BLOCK_TYPE_PARENTHESIS_BRACE === $block['type'] ) { $this->fixFunctionCall($tokens, $index); } } } } /** * Fixes whitespaces around braces of a function(y) call. * * @param Tokens $tokens tokens to handle * @param int $index index of token */ private function fixFunctionCall(Tokens $tokens, int $index): void { // remove space before opening brace if ($tokens[$index - 1]->isWhitespace()) { $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/Phpdoc/PhpdocSingleLineVarSpacingFixer.php
src/Fixer/Phpdoc/PhpdocSingleLineVarSpacingFixer.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\Phpdoc; 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 part of rule defined in PSR5 ¶7.22. * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocSingleLineVarSpacingFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Single line `@var` PHPDoc should have proper spacing.', [new CodeSample("<?php /**@var MyClass \$a */\n\$a = test();\n")], ); } /** * {@inheritdoc} * * Must run before PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocNoAliasTagFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return -10; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound([\T_COMMENT, \T_DOC_COMMENT]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ($tokens as $index => $token) { if (!$token->isComment()) { continue; } $content = $token->getContent(); $fixedContent = $this->fixTokenContent($content); if ($content !== $fixedContent) { $tokens[$index] = new Token([\T_DOC_COMMENT, $fixedContent]); } } } private function fixTokenContent(string $content): string { return Preg::replaceCallback( '#^/\*\*\h*@var\h+(\S+)\h*(\$\S+)?\h*([^\n]*)\*/$#', static function (array $matches) { $content = '/** @var'; for ($i = 1, $m = \count($matches); $i < $m; ++$i) { if ('' !== $matches[$i]) { $content .= ' '.$matches[$i]; } } return rtrim($content).' */'; }, $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/Phpdoc/PhpdocOrderByValueFixer.php
src/Fixer/Phpdoc/PhpdocOrderByValueFixer.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\Phpdoc; use PhpCsFixer\AbstractFixer; use PhpCsFixer\DocBlock\DocBlock; 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\Token; use PhpCsFixer\Tokenizer\Tokens; use Symfony\Component\OptionsResolver\Options; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * annotations?: list<'author'|'covers'|'coversNothing'|'dataProvider'|'depends'|'group'|'internal'|'method'|'mixin'|'property'|'property-read'|'property-write'|'requires'|'throws'|'uses'>, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * annotations: array{'author'?: 'author', 'covers'?: 'covers', 'coversNothing'?: 'coversnothing', 'dataProvider'?: 'dataprovider', 'depends'?: 'depends', 'group'?: 'group', 'internal'?: 'internal', 'method'?: 'method', 'mixin'?: 'mixin', 'property'?: 'property', 'property-read'?: 'property-read', 'property-write'?: 'property-write', 'requires'?: 'requires', 'throws'?: 'throws', 'uses'?: 'uses'}, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @author Filippo Tessarotto <zoeslam@gmail.com> * @author Andreas Möller <am@localheinz.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocOrderByValueFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Order PHPDoc tags by value.', [ new CodeSample( <<<'PHP' <?php /** * @covers Foo * @covers Bar */ final class MyTest extends \PHPUnit_Framework_TestCase {} PHP, ), new CodeSample( <<<'PHP' <?php /** * @author Bob * @author Alice */ final class MyTest extends \PHPUnit_Framework_TestCase {} PHP, [ 'annotations' => [ 'author', ], ], ), ], ); } /** * {@inheritdoc} * * Must run before PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpUnitFqcnAnnotationFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return -10; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAllTokenKindsFound([\T_CLASS, \T_DOC_COMMENT]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { if ([] === $this->configuration['annotations']) { return; } for ($index = $tokens->count() - 1; $index > 0; --$index) { foreach ($this->configuration['annotations'] as $type => $typeLowerCase) { $findPattern = \sprintf( '/@%s\s.+@%s\s/s', $type, $type, ); if ( !$tokens[$index]->isGivenKind(\T_DOC_COMMENT) || !Preg::match($findPattern, $tokens[$index]->getContent()) ) { continue; } $docBlock = new DocBlock($tokens[$index]->getContent()); $annotations = $docBlock->getAnnotationsOfType($type); $annotationMap = []; if (\in_array($type, ['property', 'property-read', 'property-write'], true)) { $replacePattern = \sprintf( '/(?s)\*\s*@%s\s+(?P<optionalTypes>.+\s+)?\$(?P<comparableContent>\S+).*/', $type, ); $replacement = '\2'; } elseif ('method' === $type) { $replacePattern = '/(?s)\*\s*@method\s+(?P<optionalReturnTypes>.+\s+)?(?P<comparableContent>.+)\(.*/'; $replacement = '\2'; } else { $replacePattern = \sprintf( '/\*\s*@%s\s+(?P<comparableContent>.+)/', $typeLowerCase, ); $replacement = '\1'; } foreach ($annotations as $annotation) { $rawContent = $annotation->getContent(); $comparableContent = Preg::replace( $replacePattern, $replacement, strtolower(trim($rawContent)), ); $annotationMap[$comparableContent] = $rawContent; } $orderedAnnotationMap = $annotationMap; ksort($orderedAnnotationMap, \SORT_STRING); if ($orderedAnnotationMap === $annotationMap) { continue; } $lines = $docBlock->getLines(); foreach (array_reverse($annotations) as $annotation) { array_splice( $lines, $annotation->getStart(), $annotation->getEnd() - $annotation->getStart() + 1, array_pop($orderedAnnotationMap), ); } $tokens[$index] = new Token([\T_DOC_COMMENT, implode('', $lines)]); } } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { $allowedValues = [ 'author', 'covers', 'coversNothing', 'dataProvider', 'depends', 'group', 'internal', 'method', 'mixin', 'property', 'property-read', 'property-write', 'requires', 'throws', 'uses', ]; return new FixerConfigurationResolver([ (new FixerOptionBuilder('annotations', 'List of annotations to order, e.g. `["covers"]`.')) ->setAllowedTypes(['string[]']) ->setAllowedValues([ new AllowedValueSubset($allowedValues), ]) ->setNormalizer(static function (Options $options, array $value): array { $normalized = []; foreach ($value as $annotation) { // since we will be using "strtolower" on the input annotations when building the sorting // map we must match the type in lower case as well $normalized[$annotation] = strtolower($annotation); } return $normalized; }) ->setDefault([ 'covers', ]) ->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/Phpdoc/PhpdocSeparationFixer.php
src/Fixer/Phpdoc/PhpdocSeparationFixer.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\Phpdoc; use PhpCsFixer\AbstractFixer; use PhpCsFixer\DocBlock\Annotation; 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\Future; use PhpCsFixer\Preg; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * groups?: list<list<string>>, * skip_unlisted_annotations?: bool, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * groups: list<list<string>>, * skip_unlisted_annotations: bool, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @author Graham Campbell <hello@gjcampbell.co.uk> * @author Jakub Kwaśniewski <jakub@zero-85.pl> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocSeparationFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; /** * @internal * * @var non-empty-list<non-empty-list<string>> */ public const OPTION_GROUPS_DEFAULT = [ ['author', 'copyright', 'license'], ['category', 'package', 'subpackage'], ['property', 'property-read', 'property-write'], ['deprecated', 'link', 'see', 'since'], ]; /** * @var list<list<string>> */ private array $groups; public function getDefinition(): FixerDefinitionInterface { $code = <<<'EOF' <?php /** * Hello there! * * @author John Doe * @custom Test! * * @throws Exception|RuntimeException foo * @param string $foo * * @param bool $bar Bar * @return int Return the number of changes. */ EOF; return new FixerDefinition( 'Annotations in PHPDoc should be grouped together so that annotations of the same type immediately follow each other. Annotations of a different type are separated by a single blank line.', [ new CodeSample($code), new CodeSample($code, ['groups' => [ ['deprecated', 'link', 'see', 'since'], ['author', 'copyright', 'license'], ['category', 'package', 'subpackage'], ['property', 'property-read', 'property-write'], ['param', 'return'], ]]), new CodeSample($code, ['groups' => [ ['author', 'throws', 'custom'], ['return', 'param'], ]]), new CodeSample( <<<'EOF' <?php /** * @ORM\Id * * @ORM\GeneratedValue * @Assert\NotNull * * @Assert\Type("string") */ EOF, ['groups' => [['ORM\*'], ['Assert\*']]], ), new CodeSample($code, ['skip_unlisted_annotations' => true]), ], ); } /** * {@inheritdoc} * * Must run before PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, GeneralPhpdocAnnotationRemoveFixer, PhpUnitAttributesFixer, PhpUnitInternalClassFixer, PhpUnitSizeClassFixer, PhpUnitTestClassRequiresCoversFixer, PhpdocIndentFixer, PhpdocNoAccessFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocOrderFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return -3; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } protected function configurePostNormalisation(): void { $this->groups = $this->configuration['groups']; } 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()); $this->fixDescription($doc); $this->fixAnnotations($doc); $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { $allowTagToBelongToOnlyOneGroup = static function (array $groups): bool { $tags = []; foreach ($groups as $groupIndex => $group) { foreach ($group as $member) { if (isset($tags[$member])) { if ($groupIndex === $tags[$member]) { throw new InvalidOptionsException( 'The option "groups" value is invalid. ' .'The "'.$member.'" tag is specified more than once.', ); } throw new InvalidOptionsException( 'The option "groups" value is invalid. ' .'The "'.$member.'" tag belongs to more than one group.', ); } $tags[$member] = $groupIndex; } } return true; }; return new FixerConfigurationResolver([ (new FixerOptionBuilder('groups', 'Sets of annotation types to be grouped together. Use `*` to match any tag character.')) ->setAllowedTypes(['string[][]']) ->setDefault(self::OPTION_GROUPS_DEFAULT) ->setAllowedValues([$allowTagToBelongToOnlyOneGroup]) ->getOption(), (new FixerOptionBuilder('skip_unlisted_annotations', 'Whether to skip annotations that are not listed in any group.')) ->setAllowedTypes(['bool']) ->setDefault(Future::getV4OrV3(true, false)) ->getOption(), ]); } /** * Make sure the description is separated from the annotations. */ private function fixDescription(DocBlock $doc): void { foreach ($doc->getLines() as $index => $line) { if ($line->containsATag()) { break; } if ($line->containsUsefulContent()) { $next = $doc->getLine($index + 1); if (null !== $next && $next->containsATag()) { $line->addBlank(); break; } } } } /** * Make sure the annotations are correctly separated. */ private function fixAnnotations(DocBlock $doc): void { foreach ($doc->getAnnotations() as $index => $annotation) { $next = $doc->getAnnotation($index + 1); if (null === $next) { break; } $shouldBeTogether = $this->shouldBeTogether($annotation, $next, $this->groups); if (true === $shouldBeTogether) { $this->ensureAreTogether($doc, $annotation, $next); } elseif (false === $shouldBeTogether || false === $this->configuration['skip_unlisted_annotations']) { $this->ensureAreSeparate($doc, $annotation, $next); } } } /** * Force the given annotations to immediately follow each other. */ private function ensureAreTogether(DocBlock $doc, Annotation $first, Annotation $second): void { $pos = $first->getEnd(); $final = $second->getStart(); for (++$pos; $pos < $final; ++$pos) { $doc->getLine($pos)->remove(); } } /** * Force the given annotations to have one empty line between each other. */ private function ensureAreSeparate(DocBlock $doc, Annotation $first, Annotation $second): void { $pos = $first->getEnd(); $final = $second->getStart() - 1; // check if we need to add a line, or need to remove one or more lines if ($pos === $final) { $doc->getLine($pos)->addBlank(); return; } for (++$pos; $pos < $final; ++$pos) { $doc->getLine($pos)->remove(); } } /** * @param list<list<string>> $groups */ private function shouldBeTogether(Annotation $first, Annotation $second, array $groups): ?bool { $firstName = $this->tagName($first); $secondName = $this->tagName($second); // A tag could not be read. if (null === $firstName || null === $secondName) { return null; } if ($firstName === $secondName) { return true; } foreach ($groups as $group) { $firstTagIsInGroup = $this->isInGroup($firstName, $group); $secondTagIsInGroup = $this->isInGroup($secondName, $group); if ($firstTagIsInGroup) { return $secondTagIsInGroup; } if ($secondTagIsInGroup) { return false; } } return null; } private function tagName(Annotation $annotation): ?string { Preg::match('/@([a-zA-Z0-9_\\\-]+(?=\s|$|\())/', $annotation->getContent(), $matches); return $matches[1] ?? null; } /** * @param list<string> $group */ private function isInGroup(string $tag, array $group): bool { foreach ($group as $tagInGroup) { $tagInGroup = str_replace('*', '\*', $tagInGroup); $tagInGroup = preg_quote($tagInGroup, '/'); $tagInGroup = str_replace('\\\\\*', '.*?', $tagInGroup); if (Preg::match("/^{$tagInGroup}$/", $tag)) { 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/Phpdoc/PhpdocParamOrderFixer.php
src/Fixer/Phpdoc/PhpdocParamOrderFixer.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\Phpdoc; use PhpCsFixer\AbstractFixer; use PhpCsFixer\DocBlock\Annotation; use PhpCsFixer\DocBlock\DocBlock; use PhpCsFixer\DocBlock\TypeExpression; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Preg; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @author Jonathan Gruber <gruberjonathan@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocParamOrderFixer extends AbstractFixer { private const PARAM_TAG = 'param'; public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } /** * {@inheritdoc} * * Must run before PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return parent::getPriority(); } public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Orders all `@param` annotations in DocBlocks according to method signature.', [ new CodeSample( <<<'PHP' <?php /** * Annotations in wrong order * * @param int $a * @param Foo $c * @param array $b */ function m($a, array $b, Foo $c) {} PHP, ), ], ); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(\T_DOC_COMMENT)) { continue; } // Check for function / closure token $nextFunctionToken = $tokens->getNextTokenOfKind($index, [[\T_FUNCTION], [\T_FN]]); if (null === $nextFunctionToken) { return; } // Find start index of param block (opening parenthesis) $paramBlockStart = $tokens->getNextTokenOfKind($index, ['(']); if (null === $paramBlockStart) { return; } $doc = new DocBlock($token->getContent()); $paramAnnotations = $doc->getAnnotationsOfType(self::PARAM_TAG); if ([] === $paramAnnotations) { continue; } $paramNames = $this->getFunctionParamNames($tokens, $paramBlockStart); $doc = $this->rewriteDocBlock($doc, $paramNames, $paramAnnotations); $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); } } /** * @return list<Token> */ private function getFunctionParamNames(Tokens $tokens, int $paramBlockStart): array { $paramBlockEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $paramBlockStart); $paramNames = []; for ( $i = $tokens->getNextTokenOfKind($paramBlockStart, [[\T_VARIABLE]]); null !== $i && $i < $paramBlockEnd; $i = $tokens->getNextTokenOfKind($i, [[\T_VARIABLE]]) ) { $paramNames[] = $tokens[$i]; } return $paramNames; } /** * Overwrite the param annotations in order. * * @param list<Token> $paramNames * @param non-empty-list<Annotation> $paramAnnotations */ private function rewriteDocBlock(DocBlock $doc, array $paramNames, array $paramAnnotations): DocBlock { $orderedAnnotations = $this->sortParamAnnotations($paramNames, $paramAnnotations); $otherAnnotations = $this->getOtherAnnotationsBetweenParams($doc, $paramAnnotations); // Append annotations found between param ones if ([] !== $otherAnnotations) { array_push($orderedAnnotations, ...$otherAnnotations); } // Overwrite all annotations between first and last @param tag in order $paramsStart = reset($paramAnnotations)->getStart(); $paramsEnd = end($paramAnnotations)->getEnd(); foreach ($doc->getAnnotations() as $annotation) { if ($annotation->getStart() < $paramsStart || $annotation->getEnd() > $paramsEnd) { continue; } $annotation->remove(); $doc ->getLine($annotation->getStart()) ->setContent(current($orderedAnnotations)) ; next($orderedAnnotations); } return $doc; } /** * Sort the param annotations according to the function parameters. * * @param list<Token> $funcParamNames * @param non-empty-list<Annotation> $paramAnnotations * * @return non-empty-list<string> */ private function sortParamAnnotations(array $funcParamNames, array $paramAnnotations): array { $validParams = []; foreach ($funcParamNames as $paramName) { foreach ($this->findParamAnnotationByIdentifier($paramAnnotations, $paramName->getContent()) as $index => $annotation) { // Found an exactly matching @param annotation $validParams[$index] = $annotation->getContent(); } } // Detect superfluous annotations $invalidParams = array_values( array_diff_key($paramAnnotations, $validParams), ); // Append invalid parameters to the (ordered) valid ones $orderedParams = array_values($validParams); foreach ($invalidParams as $params) { $orderedParams[] = $params->getContent(); } \assert(\count($orderedParams) > 0); return $orderedParams; } /** * Fetch all annotations except the param ones. * * @param list<Annotation> $paramAnnotations * * @return list<string> */ private function getOtherAnnotationsBetweenParams(DocBlock $doc, array $paramAnnotations): array { if (0 === \count($paramAnnotations)) { return []; } $paramsStart = reset($paramAnnotations)->getStart(); $paramsEnd = end($paramAnnotations)->getEnd(); $otherAnnotations = []; foreach ($doc->getAnnotations() as $annotation) { if ($annotation->getStart() < $paramsStart || $annotation->getEnd() > $paramsEnd) { continue; } if (self::PARAM_TAG !== $annotation->getTag()->getName()) { $otherAnnotations[] = $annotation->getContent(); } } return $otherAnnotations; } /** * Return the indices of the lines of a specific parameter annotation. * * @param list<Annotation> $paramAnnotations * * @return array<int, Annotation> Mapping of found indices and corresponding Annotations */ private function findParamAnnotationByIdentifier(array $paramAnnotations, string $identifier): array { $blockLevel = 0; $blockMatch = false; $blockIndices = []; $paramRegex = '/\*\h*@param\h*(?:|'.TypeExpression::REGEX_TYPES.'\h*)&?(?=\$\b)'.preg_quote($identifier).'\b/'; foreach ($paramAnnotations as $i => $param) { $blockStart = Preg::match('/\s*{\s*/', $param->getContent()); $blockEndMatches = Preg::matchAll('/}[\*\s\n]*/', $param->getContent()); if (0 === $blockLevel && Preg::match($paramRegex, $param->getContent())) { if ($blockStart) { $blockMatch = true; // Start of a nested block } else { return [$i => $param]; // Top level match } } if ($blockStart) { ++$blockLevel; } if (0 !== $blockEndMatches) { $blockLevel -= $blockEndMatches; } if ($blockMatch) { $blockIndices[$i] = $param; if (0 === $blockLevel) { return $blockIndices; } } } 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/Phpdoc/PhpdocAnnotationWithoutDotFixer.php
src/Fixer/Phpdoc/PhpdocAnnotationWithoutDotFixer.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\Phpdoc; use PhpCsFixer\AbstractFixer; use PhpCsFixer\DocBlock\DocBlock; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Preg; 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 PhpdocAnnotationWithoutDotFixer extends AbstractFixer { /** * @var non-empty-list<string> */ private array $tags = ['throws', 'return', 'param', 'internal', 'deprecated', 'var', 'type']; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'PHPDoc annotation descriptions should not be a sentence.', [ new CodeSample( <<<'PHP' <?php /** * @param string $bar Some string. */ function foo ($bar) {} PHP, ), ], ); } /** * {@inheritdoc} * * Must run before PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocToCommentFixer. */ public function getPriority(): int { return 17; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } 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->getAnnotations(); if (0 === \count($annotations)) { continue; } foreach ($annotations as $annotation) { if ( !$annotation->getTag()->valid() || !\in_array($annotation->getTag()->getName(), $this->tags, true) ) { continue; } $lineAfterAnnotation = $doc->getLine($annotation->getEnd() + 1); if (null !== $lineAfterAnnotation) { $lineAfterAnnotationTrimmed = ltrim($lineAfterAnnotation->getContent()); if ('' === $lineAfterAnnotationTrimmed || !str_starts_with($lineAfterAnnotationTrimmed, '*')) { // malformed PHPDoc, missing asterisk ! continue; } } $content = $annotation->getContent(); if ( !Preg::match('/[.。]\h*$/u', $content) || Preg::match('/[.。](?!\h*$)/u', $content, $matches) ) { continue; } $endLine = $doc->getLine($annotation->getEnd()); $endLine->setContent(Preg::replace('/(?<![.。])[.。]\h*(\H+)$/u', '\1', $endLine->getContent())); $startLine = $doc->getLine($annotation->getStart()); $optionalTypeRegEx = $annotation->supportTypes() ? \sprintf('(?:%s\s+(?:\$\w+\s+)?)', preg_quote(implode('|', $annotation->getTypes()), '/')) : ''; $content = Preg::replaceCallback( '/^(\s*\*\s*@\w+\s+'.$optionalTypeRegEx.')(\p{Lu}?(?=\p{Ll}|\p{Zs}))(.*)$/', static fn (array $matches): string => $matches[1].mb_strtolower($matches[2]).$matches[3], $startLine->getContent(), 1, ); $startLine->setContent($content); } $tokens[$index] = 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/Phpdoc/PhpdocNoEmptyReturnFixer.php
src/Fixer/Phpdoc/PhpdocNoEmptyReturnFixer.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\Phpdoc; use PhpCsFixer\AbstractFixer; use PhpCsFixer\DocBlock\Annotation; use PhpCsFixer\DocBlock\DocBlock; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Token; 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 PhpdocNoEmptyReturnFixer extends AbstractFixer { public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( '`@return void` and `@return null` annotations must be removed from PHPDoc.', [ new CodeSample( <<<'PHP' <?php /** * @return null */ function foo() {} PHP, ), new CodeSample( <<<'PHP' <?php /** * @return void */ function foo() {} PHP, ), ], ); } /** * {@inheritdoc} * * Must run before NoEmptyPhpdocFixer, PhpdocAlignFixer, PhpdocSeparationFixer, PhpdocTrimFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer, VoidReturnFixer. */ public function getPriority(): int { return 4; } 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('return'); if (0 === \count($annotations)) { continue; } foreach ($annotations as $annotation) { $this->fixAnnotation($annotation); } $newContent = $doc->getContent(); if ($newContent === $token->getContent()) { continue; } if ('' === $newContent) { $tokens->clearTokenAndMergeSurroundingWhitespace($index); continue; } $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); } } /** * Remove `return void` or `return null` annotations. */ private function fixAnnotation(Annotation $annotation): void { $types = $annotation->getNormalizedTypes(); if (1 === \count($types) && ('null' === $types[0] || 'void' === $types[0])) { $annotation->remove(); } } }
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/Phpdoc/PhpdocOrderFixer.php
src/Fixer/Phpdoc/PhpdocOrderFixer.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\Phpdoc; use PhpCsFixer\AbstractFixer; 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\Future; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; use PhpCsFixer\Utils; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * order?: list<string>, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * order: list<string>, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @author Graham Campbell <hello@gjcampbell.co.uk> * @author Jakub Kwaśniewski <jakub@zero-85.pl> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocOrderFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; /** @var list<string> */ private array $configurationOrder; public function getDefinition(): FixerDefinitionInterface { $code = <<<'EOF' <?php /** * Hello there! * * @throws Exception|RuntimeException foo * @custom Test! * @return int Return the number of changes. * @param string $foo * @param bool $bar Bar */ EOF; return new FixerDefinition( 'Annotations in PHPDoc should be ordered in defined sequence.', [ new CodeSample($code), new CodeSample($code, ['order' => ['param', 'return', 'throws']]), new CodeSample($code, ['order' => ['param', 'throws', 'return']]), new CodeSample($code, ['order' => ['param', 'custom', 'throws', 'return']]), ], ); } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } /** * {@inheritdoc} * * Must run before PhpdocAlignFixer, PhpdocSeparationFixer, PhpdocTrimFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return -2; } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('order', 'Sequence in which annotations in PHPDoc should be ordered.')) ->setAllowedTypes(['string[]']) ->setAllowedValues([static function (array $order): bool { if (\count($order) < 2) { throw new InvalidOptionsException('The option "order" value is invalid. Minimum two tags are required.'); } $unique = array_unique($order); if (\count($order) !== \count($unique)) { $duplicates = array_keys(array_filter(array_count_values($order), static fn (int $count): bool => $count > 1)); throw new InvalidOptionsException(\sprintf( 'The option "order" value is invalid. Tag%s %s %s duplicated.', \count($duplicates) > 1 ? 's' : '', Utils::naturalLanguageJoin($duplicates), \count($duplicates) > 1 ? 'are' : 'is', )); } return true; }]) ->setDefault(Future::getV4OrV3(['param', 'return', 'throws'], ['param', 'throws', 'return'])) ->getOption(), ]); } protected function configurePostNormalisation(): void { $this->configurationOrder = []; foreach ($this->configuration['order'] as $type) { $this->configurationOrder[] = $type; if (!\in_array('phpstan-'.$type, $this->configuration['order'], true)) { $this->configurationOrder[] = 'phpstan-'.$type; } if (!\in_array('psalm-'.$type, $this->configuration['order'], true)) { $this->configurationOrder[] = 'psalm-'.$type; } } } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(\T_DOC_COMMENT)) { continue; } // assuming annotations are already grouped by tags $content = $token->getContent(); // sort annotations $successors = $this->configurationOrder; while (\count($successors) >= 3) { $predecessor = array_shift($successors); $content = $this->moveAnnotationsBefore($predecessor, $successors, $content); } // we're parsing the content last time to make sure the internal // state of the docblock is correct after the modifications $predecessors = $this->configurationOrder; $last = array_pop($predecessors); $content = $this->moveAnnotationsAfter($last, $predecessors, $content); // persist the content at the end $tokens[$index] = new Token([\T_DOC_COMMENT, $content]); } } /** * Move all given annotations in before given set of annotations. * * @param string $move Tag of annotations that should be moved * @param list<string> $before Tags of annotations that should moved annotations be placed before */ private function moveAnnotationsBefore(string $move, array $before, string $content): string { $doc = new DocBlock($content); $toBeMoved = $doc->getAnnotationsOfType($move); // nothing to do if there are no annotations to be moved if (0 === \count($toBeMoved)) { return $content; } $others = $doc->getAnnotationsOfType($before); if (0 === \count($others)) { return $content; } // get the index of the final line of the final toBoMoved annotation $end = end($toBeMoved)->getEnd(); $line = $doc->getLine($end); // move stuff about if required foreach ($others as $other) { if ($other->getStart() < $end) { // we're doing this to maintain the original line indices $line->setContent($line->getContent().$other->getContent()); $other->remove(); } } return $doc->getContent(); } /** * Move all given annotations after given set of annotations. * * @param string $move Tag of annotations that should be moved * @param list<string> $after Tags of annotations that should moved annotations be placed after */ private function moveAnnotationsAfter(string $move, array $after, string $content): string { $doc = new DocBlock($content); $toBeMoved = $doc->getAnnotationsOfType($move); // nothing to do if there are no annotations to be moved if (0 === \count($toBeMoved)) { return $content; } $others = $doc->getAnnotationsOfType($after); // nothing to do if there are no other annotations if (0 === \count($others)) { return $content; } // get the index of the first line of the first toBeMoved annotation $start = $toBeMoved[0]->getStart(); $line = $doc->getLine($start); // move stuff about if required foreach (array_reverse($others) as $other) { if ($other->getEnd() > $start) { // we're doing this to maintain the original line indices $line->setContent($other->getContent().$line->getContent()); $other->remove(); } } return $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/Phpdoc/PhpdocNoUselessInheritdocFixer.php
src/Fixer/Phpdoc/PhpdocNoUselessInheritdocFixer.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\Phpdoc; 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; /** * Remove inheritdoc tags from classy that does not inherit. * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocNoUselessInheritdocFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Classy that does not inherit must not have `@inheritdoc` tags.', [ new CodeSample("<?php\n/** {@inheritdoc} */\nclass Sample\n{\n}\n"), new CodeSample("<?php\nclass Sample\n{\n /**\n * @inheritdoc\n */\n public function Test()\n {\n }\n}\n"), ], ); } /** * {@inheritdoc} * * Must run before NoEmptyPhpdocFixer, NoTrailingWhitespaceInCommentFixer, PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 6; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT) && $tokens->isAnyTokenKindsFound([\T_CLASS, \T_INTERFACE]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { // min. offset 4 as minimal candidate is @: <?php\n/** @inheritdoc */class min{} for ($index = 1, $count = \count($tokens) - 4; $index < $count; ++$index) { if ($tokens[$index]->isGivenKind([\T_CLASS, \T_INTERFACE])) { $index = $this->fixClassy($tokens, $index); } } } private function fixClassy(Tokens $tokens, int $index): int { // figure out where the classy starts $classOpenIndex = $tokens->getNextTokenOfKind($index, ['{']); // figure out where the classy ends $classEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpenIndex); // is classy extending or implementing some interface $extendingOrImplementing = $this->isExtendingOrImplementing($tokens, $index, $classOpenIndex); if (!$extendingOrImplementing) { // PHPDoc of classy should not have inherit tag even when using traits as Traits cannot provide this information $this->fixClassyOutside($tokens, $index); } // figure out if the classy uses a trait if (!$extendingOrImplementing && $this->isUsingTrait($tokens, $index, $classOpenIndex, $classEndIndex)) { $extendingOrImplementing = true; } $this->fixClassyInside($tokens, $classOpenIndex, $classEndIndex, !$extendingOrImplementing); return $classEndIndex; } private function fixClassyInside(Tokens $tokens, int $classOpenIndex, int $classEndIndex, bool $fixThisLevel): void { for ($i = $classOpenIndex; $i < $classEndIndex; ++$i) { if ($tokens[$i]->isGivenKind(\T_CLASS)) { $i = $this->fixClassy($tokens, $i); } elseif ($fixThisLevel && $tokens[$i]->isGivenKind(\T_DOC_COMMENT)) { $this->fixToken($tokens, $i); } } } private function fixClassyOutside(Tokens $tokens, int $classIndex): void { $previousIndex = $tokens->getPrevNonWhitespace($classIndex); if ($tokens[$previousIndex]->isGivenKind(\T_DOC_COMMENT)) { $this->fixToken($tokens, $previousIndex); } } private function fixToken(Tokens $tokens, int $tokenIndex): void { $count = 0; $content = Preg::replaceCallback( '#(\h*(?:@{*|{*\h*@)\h*inheritdoc\h*)([^}]*)((?:}*)\h*)#i', static fn (array $matches): string => ' '.$matches[2], $tokens[$tokenIndex]->getContent(), -1, $count, ); if ($count > 0) { $tokens[$tokenIndex] = new Token([\T_DOC_COMMENT, $content]); } } private function isExtendingOrImplementing(Tokens $tokens, int $classIndex, int $classOpenIndex): bool { for ($index = $classIndex; $index < $classOpenIndex; ++$index) { if ($tokens[$index]->isGivenKind([\T_EXTENDS, \T_IMPLEMENTS])) { return true; } } return false; } private function isUsingTrait(Tokens $tokens, int $classIndex, int $classOpenIndex, int $classCloseIndex): bool { if ($tokens[$classIndex]->isGivenKind(\T_INTERFACE)) { // cannot use Trait inside an interface return false; } $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/Phpdoc/NoEmptyPhpdocFixer.php
src/Fixer/Phpdoc/NoEmptyPhpdocFixer.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\Phpdoc; 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 NoEmptyPhpdocFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'There should not be empty PHPDoc blocks.', [new CodeSample("<?php /** */\n")], ); } /** * {@inheritdoc} * * Must run before NoExtraBlankLinesFixer, NoTrailingWhitespaceFixer, PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, GeneralPhpdocAnnotationRemoveFixer, NoSuperfluousPhpdocTagsFixer, PhpUnitAttributesFixer, PhpUnitNoExpectationAnnotationFixer, PhpUnitTestAnnotationFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocIndentFixer, PhpdocNoAccessFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 3; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(\T_DOC_COMMENT)) { continue; } if (!Preg::match('#^/\*\*[\s\*]*\*/$#', $token->getContent())) { continue; } if ( $tokens[$index - 1]->isGivenKind([\T_OPEN_TAG, \T_WHITESPACE]) && substr_count($tokens[$index - 1]->getContent(), "\n") > 0 && $tokens[$index + 1]->isGivenKind(\T_WHITESPACE) && Preg::match('/^\R/', $tokens[$index + 1]->getContent()) ) { $tokens[$index - 1] = new Token([ $tokens[$index - 1]->getId(), Preg::replace('/\h*$/', '', $tokens[$index - 1]->getContent()), ]); $newContent = Preg::replace('/^\R/', '', $tokens[$index + 1]->getContent()); if ('' === $newContent) { $tokens->clearAt($index + 1); } else { $tokens[$index + 1] = new Token([\T_WHITESPACE, $newContent]); } } $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/Phpdoc/PhpdocTrimFixer.php
src/Fixer/Phpdoc/PhpdocTrimFixer.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\Phpdoc; 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; /** * @author Graham Campbell <hello@gjcampbell.co.uk> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocTrimFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'PHPDoc should start and end with content, excluding the very first and last line of the docblocks.', [ new CodeSample( <<<'PHP' <?php /** * * Foo must be final class. * * */ final class Foo {} PHP, ), ], ); } /** * {@inheritdoc} * * Must run before PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, GeneralPhpdocAnnotationRemoveFixer, PhpUnitAttributesFixer, PhpUnitTestAnnotationFixer, PhpdocIndentFixer, PhpdocNoAccessFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocOrderFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return -5; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(\T_DOC_COMMENT)) { continue; } $content = $token->getContent(); $content = $this->fixStart($content); // we need re-parse the docblock after fixing the start before // fixing the end in order for the lines to be correctly indexed $content = $this->fixEnd($content); $tokens[$index] = new Token([\T_DOC_COMMENT, $content]); } } /** * Make sure the first useful line starts immediately after the first line. */ private function fixStart(string $content): string { return Preg::replace( '~ (^/\*\*) # DocComment begin (?: \R\h*(?:\*\h*)? # lines without useful content (?!\R\h*\*/) # not followed by a DocComment end )+ (\R\h*(?:\*\h*)?\S) # first line with useful content ~x', '$1$2', $content, ); } /** * Make sure the last useful line is immediately before the final line. */ private function fixEnd(string $content): string { return Preg::replace( '~ (\R\h*(?:\*\h*)?\S.*?) # last line with useful content (?: (?<!/\*\*) # not preceded by a DocComment start \R\h*(?:\*\h*)? # lines without useful content )+ (\R\h*\*/$) # DocComment end ~xu', '$1$2', $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/Phpdoc/PhpdocNoAccessFixer.php
src/Fixer/Phpdoc/PhpdocNoAccessFixer.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\Phpdoc; use PhpCsFixer\AbstractProxyFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; /** * @author Graham Campbell <hello@gjcampbell.co.uk> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocNoAccessFixer extends AbstractProxyFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( '`@access` annotations must be removed from PHPDoc.', [ new CodeSample( <<<'PHP' <?php class Foo { /** * @internal * @access private */ private $bar; } PHP, ), ], ); } /** * {@inheritdoc} * * Must run before NoEmptyPhpdocFixer, PhpdocAlignFixer, PhpdocSeparationFixer, PhpdocTrimFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return parent::getPriority(); } protected function createProxyFixers(): array { $fixer = new GeneralPhpdocAnnotationRemoveFixer(); $fixer->configure( ['annotations' => ['access'], 'case_sensitive' => 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/Phpdoc/PhpdocTagNoNamedArgumentsFixer.php
src/Fixer/Phpdoc/PhpdocTagNoNamedArgumentsFixer.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\Phpdoc; use PhpCsFixer\AbstractFixer; use PhpCsFixer\Fixer\ConfigurableFixerInterface; use PhpCsFixer\Fixer\ConfigurableFixerTrait; use PhpCsFixer\Fixer\DocBlockAnnotationTrait; 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\AttributeAnalyzer; use PhpCsFixer\Tokenizer\Analyzer\FullyQualifiedNameAnalyzer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * description?: string, * fix_attribute?: bool, * fix_internal?: bool, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * description: string, * fix_attribute: bool, * fix_internal: bool, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocTagNoNamedArgumentsFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; use DocBlockAnnotationTrait; public function getDefinition(): FixerDefinitionInterface { $code = <<<'PHP' <?php class Foo { public function bar(string $s) {} } PHP; return new FixerDefinition( 'There must be `@no-named-arguments` tag in PHPDoc of a class/enum/interface/trait.', [ new CodeSample($code), new CodeSample($code, ['description' => 'Parameter names are not covered by the backward compatibility promise.']), ], ); } public function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('description', 'Description of the tag.')) ->setAllowedTypes(['string']) ->setDefault('') ->getOption(), (new FixerOptionBuilder('fix_attribute', 'Whether to fix attribute classes.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), (new FixerOptionBuilder('fix_internal', 'Whether to fix internal elements (marked with `@internal`).')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), ]); } /** * {@inheritdoc} * * Must run before PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 0; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { for ($index = $tokens->count() - 1; $index > 0; --$index) { if (!$tokens[$index]->isClassy()) { continue; } $prevIndex = $tokens->getPrevMeaningfulToken($index); \assert(\is_int($prevIndex)); if ($tokens[$prevIndex]->isGivenKind(\T_NEW)) { continue; } if (!$this->configuration['fix_attribute'] && self::isAttributeClass($tokens, $prevIndex)) { continue; } $this->ensureIsDocBlockWithAnnotation( $tokens, $index, 'no-named-arguments', $this->configuration['fix_internal'] ? ['no-named-arguments'] : ['internal', 'no-named-arguments'], [], ); $docBlockIndex = $tokens->getPrevTokenOfKind($index + 2, [[\T_DOC_COMMENT]]); \assert(\is_int($docBlockIndex)); $content = $tokens[$docBlockIndex]->getContent(); $newContent = Preg::replace('/@no-named-arguments.*\R/', rtrim('@no-named-arguments '.$this->configuration['description']).$this->whitespacesConfig->getLineEnding(), $content); if ($newContent !== $content) { $tokens[$docBlockIndex] = new Token([\T_DOC_COMMENT, $newContent]); } } } private static function isAttributeClass(Tokens $tokens, int $index): bool { while ($tokens[$index]->isGivenKind([\T_FINAL, FCT::T_READONLY])) { $index = $tokens->getPrevMeaningfulToken($index); \assert(\is_int($index)); } if (!$tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { return false; } $fullyQualifiedNameAnalyzer = new FullyQualifiedNameAnalyzer($tokens); foreach (AttributeAnalyzer::collect($tokens, $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $index)) as $attributeAnalysis) { foreach ($attributeAnalysis->getAttributes() as $attribute) { $attributeName = strtolower($fullyQualifiedNameAnalyzer->getFullyQualifiedName($attribute['name'], $attribute['start'], NamespaceUseAnalysis::TYPE_CLASS)); if ('attribute' === $attributeName) { 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/Phpdoc/NoBlankLinesAfterPhpdocFixer.php
src/Fixer/Phpdoc/NoBlankLinesAfterPhpdocFixer.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\Phpdoc; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Token; 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 NoBlankLinesAfterPhpdocFixer extends AbstractFixer { public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'There should not be blank lines between docblock and the documented element.', [ new CodeSample( <<<'PHP' <?php /** * This is the bar class. */ class Bar {} PHP, ), ], ); } /** * {@inheritdoc} * * Must run before HeaderCommentFixer, PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return -20; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(\T_DOC_COMMENT)) { continue; } // get the next non-whitespace token inc comments, provided // that there is whitespace between it and the current token $next = $tokens->getNextNonWhitespace($index); if ($index + 2 === $next && false === $tokens[$next]->isGivenKind([ \T_BREAK, \T_COMMENT, \T_CONTINUE, \T_DECLARE, \T_DOC_COMMENT, \T_GOTO, \T_INCLUDE, \T_INCLUDE_ONCE, \T_NAMESPACE, \T_REQUIRE, \T_REQUIRE_ONCE, \T_RETURN, \T_THROW, \T_USE, \T_WHITESPACE, ])) { $this->fixWhitespace($tokens, $index + 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, substr($content, strrpos($content, "\n"))]); } } }
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/Phpdoc/PhpdocArrayTypeFixer.php
src/Fixer/Phpdoc/PhpdocArrayTypeFixer.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\Phpdoc; use PhpCsFixer\AbstractPhpdocTypesFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Preg; use PhpCsFixer\Tokenizer\Tokens; /** * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocArrayTypeFixer extends AbstractPhpdocTypesFixer { public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } public function isRisky(): bool { return true; } public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'PHPDoc `array<T>` type must be used instead of `T[]`.', [ new CodeSample( <<<'PHP' <?php /** * @param int[] $x * @param string[][] $y */ PHP, ), ], null, 'Risky when using `T[]` in union types.', ); } /** * {@inheritdoc} * * Must run before PhpdocAlignFixer, PhpdocListTypeFixer, PhpdocTypesOrderFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 2; } protected function normalize(string $type): string { if (Preg::match('/^\??\s*[\'"]/', $type)) { return $type; } $prefix = ''; if (str_starts_with($type, '?')) { $prefix = '?'; $type = substr($type, 1); } return $prefix.Preg::replaceCallback( '/^(.+?)((?:\h*\[\h*\])+)$/', static function (array $matches): string { $type = $matches[1]; $level = substr_count($matches[2], '['); if (str_starts_with($type, '(') && str_ends_with($type, ')')) { $type = substr($type, 1, -1); } return str_repeat('array<', $level).$type.str_repeat('>', $level); }, $type, ); } }
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/Phpdoc/PhpdocTypesFixer.php
src/Fixer/Phpdoc/PhpdocTypesFixer.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\Phpdoc; use PhpCsFixer\AbstractPhpdocTypesFixer; use PhpCsFixer\DocBlock\TypeExpression; 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; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * groups?: list<'alias'|'meta'|'simple'>, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * groups: list<'alias'|'meta'|'simple'>, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @author Graham Campbell <hello@gjcampbell.co.uk> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocTypesFixer extends AbstractPhpdocTypesFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; /** * Available types, grouped. * * @var non-empty-array<string, non-empty-list<string>> */ private const POSSIBLE_TYPES = [ 'alias' => [ 'boolean', 'double', 'integer', ], 'meta' => [ '$this', 'false', 'mixed', 'parent', 'resource', 'scalar', 'self', 'static', 'true', 'void', ], 'simple' => [ 'array', 'bool', 'callable', 'float', 'int', 'iterable', 'null', 'object', 'string', ], ]; /** @var array<string, true> */ private array $typesSetToFix; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'The correct case must be used for standard PHP types in PHPDoc.', [ new CodeSample( <<<'PHP' <?php /** * @param STRING|String[] $bar * * @return inT[] */ PHP, ), new CodeSample( <<<'PHP' <?php /** * @param BOOL $foo * * @return MIXED */ PHP, ['groups' => ['simple', 'alias']], ), ], ); } /** * {@inheritdoc} * * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocArrayTypeFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocListTypeFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocScalarFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagNoNamedArgumentsFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. * Must run after PhpdocIndentFixer. */ public function getPriority(): int { /* * Should be run before all other docblock fixers apart from the * phpdoc_to_comment and phpdoc_indent fixer to make sure all fixers * apply correct indentation to new code they add. This should run * before alignment of params is done since this fixer might change * the type and thereby un-aligning the params. We also must run before * the phpdoc_scalar_fixer so that it can make changes after us. */ return 16; } protected function configurePostNormalisation(): void { $typesToFix = array_merge(...array_map(static fn (string $group): array => self::POSSIBLE_TYPES[$group], $this->configuration['groups'])); $this->typesSetToFix = array_combine($typesToFix, array_fill(0, \count($typesToFix), true)); } protected function normalize(string $type): string { $typeExpression = new TypeExpression($type, null, []); $newTypeExpression = $typeExpression->mapTypes(function (TypeExpression $type) { if ($type->isUnionType()) { return $type; } $value = $type->toString(); $valueLower = strtolower($value); if (isset($this->typesSetToFix[$valueLower])) { return new TypeExpression($valueLower, null, []); } return $type; }); return $newTypeExpression->toString(); } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { $possibleGroups = array_keys(self::POSSIBLE_TYPES); return new FixerConfigurationResolver([ (new FixerOptionBuilder('groups', 'Type groups to fix.')) ->setAllowedTypes(['string[]']) ->setAllowedValues([new AllowedValueSubset($possibleGroups)]) ->setDefault($possibleGroups) ->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/Phpdoc/PhpdocTagCasingFixer.php
src/Fixer/Phpdoc/PhpdocTagCasingFixer.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\Phpdoc; use PhpCsFixer\AbstractProxyFixer; use PhpCsFixer\ConfigurationException\InvalidConfigurationException; 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\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Preg; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * tags?: list<string>, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * tags: list<string>, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocTagCasingFixer extends AbstractProxyFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Fixes casing of PHPDoc tags.', [ new CodeSample("<?php\n/**\n * @inheritdoc\n */\n"), new CodeSample("<?php\n/**\n * @inheritdoc\n * @Foo\n */\n", [ 'tags' => ['foo'], ]), ], ); } /** * {@inheritdoc} * * Must run before PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return parent::getPriority(); } protected function configurePostNormalisation(): void { $replacements = []; foreach ($this->configuration['tags'] as $tag) { $replacements[$tag] = $tag; } /** @var GeneralPhpdocTagRenameFixer $generalPhpdocTagRenameFixer */ $generalPhpdocTagRenameFixer = $this->proxyFixers['general_phpdoc_tag_rename']; try { $generalPhpdocTagRenameFixer->configure([ 'case_sensitive' => false, 'fix_annotation' => true, 'fix_inline' => true, 'replacements' => $replacements, ]); } catch (InvalidConfigurationException $exception) { throw new InvalidFixerConfigurationException( $this->getName(), Preg::replace('/^\[.+?\] /', '', $exception->getMessage()), $exception, ); } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('tags', 'List of tags to fix with their expected casing.')) ->setAllowedTypes(['string[]']) ->setDefault(['inheritDoc']) ->getOption(), ]); } protected function createProxyFixers(): array { return [new GeneralPhpdocTagRenameFixer()]; } }
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/Phpdoc/PhpdocToCommentFixer.php
src/Fixer/Phpdoc/PhpdocToCommentFixer.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\Phpdoc; 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\Future; use PhpCsFixer\Preg; use PhpCsFixer\Tokenizer\Analyzer\CommentsAnalyzer; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * allow_before_return_statement?: bool, * ignored_tags?: list<string>, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * allow_before_return_statement: bool, * ignored_tags: list<string>, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @author Ceeram <ceeram@cakephp.org> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocToCommentFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; /** * @var list<string> */ private array $ignoredTags = []; private bool $allowBeforeReturnStatement = false; public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } /** * {@inheritdoc} * * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyCommentFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocAnnotationWithoutDotFixer, PhpdocArrayTypeFixer, PhpdocIndentFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocListTypeFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagNoNamedArgumentsFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer, SingleLineCommentSpacingFixer, SingleLineCommentStyleFixer. * Must run after CommentToPhpdocFixer. */ public function getPriority(): int { /* * Should be run before all other docblock fixers so that these fixers * don't touch doc comments which are meant to be converted to regular * comments. */ return 25; } public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Docblocks should only be used on structural elements.', [ new CodeSample( <<<'PHP' <?php $first = true;// needed because by default first docblock is never fixed. /** This should be a comment */ foreach($connections as $key => $sqlite) { $sqlite->open($path); } PHP, ), new CodeSample( <<<'PHP' <?php $first = true;// needed because by default first docblock is never fixed. /** This should be a comment */ foreach($connections as $key => $sqlite) { $sqlite->open($path); } /** @todo This should be a PHPDoc as the tag is on "ignored_tags" list */ foreach($connections as $key => $sqlite) { $sqlite->open($path); } PHP, ['ignored_tags' => ['todo']], ), new CodeSample( <<<'PHP' <?php $first = true;// needed because by default first docblock is never fixed. /** This should be a comment */ foreach($connections as $key => $sqlite) { $sqlite->open($path); } function returnClassName() { /** @var class-string */ return \StdClass::class; } PHP, ['allow_before_return_statement' => true], ), ], ); } protected function configurePostNormalisation(): void { $this->ignoredTags = array_map( static fn (string $tag): string => strtolower($tag), $this->configuration['ignored_tags'], ); $this->allowBeforeReturnStatement = true === $this->configuration['allow_before_return_statement']; } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('ignored_tags', 'List of ignored tags (matched case insensitively).')) ->setAllowedTypes(['string[]']) ->setDefault([]) ->getOption(), (new FixerOptionBuilder('allow_before_return_statement', 'Whether to allow PHPDoc before return statement.')) ->setAllowedTypes(['bool']) ->setDefault(Future::getV4OrV3(true, false)) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $commentsAnalyzer = new CommentsAnalyzer(); foreach ($tokens as $index => $token) { if (!$token->isGivenKind(\T_DOC_COMMENT)) { continue; } if ($commentsAnalyzer->isHeaderComment($tokens, $index)) { continue; } if ($this->allowBeforeReturnStatement && $commentsAnalyzer->isBeforeReturn($tokens, $index)) { continue; } if ($commentsAnalyzer->isBeforeStructuralElement($tokens, $index)) { continue; } if (0 < Preg::matchAll('~\@([a-zA-Z0-9_\\\-]+)\b~', $token->getContent(), $matches)) { foreach ($matches[1] as $match) { if (\in_array(strtolower($match), $this->ignoredTags, true)) { continue 2; } } } $tokens[$index] = new Token([\T_COMMENT, '/*'.ltrim($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/Phpdoc/PhpdocVarAnnotationCorrectOrderFixer.php
src/Fixer/Phpdoc/PhpdocVarAnnotationCorrectOrderFixer.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\Phpdoc; 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; /** * @author Kuba Werłos <werlos@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocVarAnnotationCorrectOrderFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( '`@var` and `@type` annotations must have type and name in the correct order.', [ new CodeSample( <<<'PHP' <?php /** @var $foo int */ $foo = 2 + 2; PHP, ), ], ); } /** * {@inheritdoc} * * Must run before PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 0; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(\T_DOC_COMMENT)) { continue; } if (!str_contains(strtolower($token->getContent()), strtolower('@var')) && !str_contains(strtolower($token->getContent()), strtolower('@type'))) { continue; } $newContent = Preg::replace( '/(@(?:type|var)\s*)(\$\S+)(\h+)([^\$](?:[^<\s]|<[^>]*>)*)(\s|\*)/i', '$1$4$3$2$5', $token->getContent(), ); if ($newContent === $token->getContent()) { continue; } $tokens[$index] = new Token([$token->getId(), $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/Phpdoc/PhpdocIndentFixer.php
src/Fixer/Phpdoc/PhpdocIndentFixer.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\Phpdoc; 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; use PhpCsFixer\Utils; /** * @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 PhpdocIndentFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Docblocks should have the same indentation as the documented subject.', [ new CodeSample( <<<'PHP' <?php class DocBlocks { /** * Test constants */ const INDENT = 1; } PHP, ), ], ); } /** * {@inheritdoc} * * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocAnnotationWithoutDotFixer, PhpdocArrayTypeFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocListTypeFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagNoNamedArgumentsFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. * Must run after IndentationTypeFixer, PhpdocToCommentFixer. */ public function getPriority(): int { return 20; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { for ($index = $tokens->count() - 1; 0 <= $index; --$index) { $token = $tokens[$index]; if (!$token->isGivenKind(\T_DOC_COMMENT)) { continue; } $nextIndex = $tokens->getNextMeaningfulToken($index); // skip if there is no next token or if next token is block end `}` if (null === $nextIndex || $tokens[$nextIndex]->equals('}')) { continue; } $prevIndex = $index - 1; $prevToken = $tokens[$prevIndex]; // ignore inline docblocks if ( $prevToken->isGivenKind(\T_OPEN_TAG) || ($prevToken->isWhitespace(" \t") && !$tokens[$index - 2]->isGivenKind(\T_OPEN_TAG)) || $prevToken->equalsAny([';', ',', '{', '(']) ) { continue; } if ($tokens[$nextIndex - 1]->isWhitespace()) { $indent = Utils::calculateTrailingWhitespaceIndent($tokens[$nextIndex - 1]); } else { $indent = ''; } $newPrevContent = $this->fixWhitespaceBeforeDocblock($prevToken->getContent(), $indent); $tokens[$index] = new Token([\T_DOC_COMMENT, $this->fixDocBlock($token->getContent(), $indent)]); if (!$prevToken->isWhitespace()) { if ('' !== $indent) { $tokens->insertAt($index, new Token([\T_WHITESPACE, $indent])); } } elseif ('' !== $newPrevContent) { if ($prevToken->isArray()) { $tokens[$prevIndex] = new Token([$prevToken->getId(), $newPrevContent]); } else { $tokens[$prevIndex] = new Token($newPrevContent); } } else { $tokens->clearAt($prevIndex); } } } /** * Fix indentation of Docblock. * * @param string $content Docblock contents * @param string $indent Indentation to apply * * @return string Dockblock contents including correct indentation */ private function fixDocBlock(string $content, string $indent): string { return ltrim(Preg::replace('/^\h*\*/m', $indent.' *', $content)); } /** * @param string $content Whitespace before Docblock * @param string $indent Indentation of the documented subject * * @return string Whitespace including correct indentation for Dockblock after this whitespace */ private function fixWhitespaceBeforeDocblock(string $content, string $indent): string { return rtrim($content, " \t").$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/Phpdoc/PhpdocListTypeFixer.php
src/Fixer/Phpdoc/PhpdocListTypeFixer.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\Phpdoc; use PhpCsFixer\AbstractPhpdocTypesFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Preg; use PhpCsFixer\Tokenizer\Tokens; /** * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocListTypeFixer extends AbstractPhpdocTypesFixer { public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } public function isRisky(): bool { return true; } public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'PHPDoc `list` type must be used instead of `array` without a key.', [ new CodeSample( <<<'PHP' <?php /** * @param array<int> $x * @param array<array<string>> $y */ PHP, ), ], null, 'Risky when `array` key should be present, but is missing.', ); } /** * {@inheritdoc} * * Must run before PhpdocAlignFixer, PhpdocTypesOrderFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocArrayTypeFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 1; } protected function normalize(string $type): string { return Preg::replace('/\barray(?=<(?:[^,<]|<[^>]+>)+(>|{|\())/i', 'list', $type); } }
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/Phpdoc/PhpdocReturnSelfReferenceFixer.php
src/Fixer/Phpdoc/PhpdocReturnSelfReferenceFixer.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\Phpdoc; use PhpCsFixer\AbstractFixer; 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\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 _AutogeneratedInputConfiguration array{ * replacements?: array<string, string>, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * replacements: array<string, string>, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocReturnSelfReferenceFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; /** * @var non-empty-list<string> */ private const TO_TYPES = [ '$this', 'static', 'self', ]; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'The type of `@return` annotations of methods returning a reference to itself must the configured one.', [ new CodeSample( <<<'PHP' <?php class Sample { /** * @return this */ public function test1() { return $this; } /** * @return $self */ public function test2() { return $this; } } PHP, ), new CodeSample( <<<'PHP' <?php class Sample { /** * @return this */ public function test1() { return $this; } /** * @return $self */ public function test2() { return $this; } } PHP, ['replacements' => ['this' => 'self']], ), ], ); } public function isCandidate(Tokens $tokens): bool { return \count($tokens) > 10 && $tokens->isAllTokenKindsFound([\T_DOC_COMMENT, \T_FUNCTION]) && $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); } /** * {@inheritdoc} * * Must run before NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 10; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $tokensAnalyzer = new TokensAnalyzer($tokens); foreach ($tokensAnalyzer->getClassyElements() as $index => $element) { if ('method' === $element['type']) { $this->fixMethod($tokens, $index); } } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { $default = [ 'this' => '$this', '@this' => '$this', '$self' => 'self', '@self' => 'self', '$static' => 'static', '@static' => 'static', ]; return new FixerConfigurationResolver([ (new FixerOptionBuilder('replacements', 'Mapping between replaced return types with new ones.')) ->setAllowedTypes(['array<string, string>']) ->setNormalizer(static function (Options $options, array $value) use ($default): array { $normalizedValue = []; foreach ($value as $from => $to) { if (\is_string($from)) { $from = strtolower($from); } if (!isset($default[$from])) { throw new InvalidOptionsException(\sprintf( 'Unknown key "%s", expected any of %s.', \gettype($from).'#'.$from, Utils::naturalLanguageJoin(array_keys($default)), )); } if (!\in_array($to, self::TO_TYPES, true)) { throw new InvalidOptionsException(\sprintf( 'Unknown value "%s", expected any of %s.', \is_object($to) ? \get_class($to) : \gettype($to).(\is_resource($to) ? '' : '#'.$to), Utils::naturalLanguageJoin(self::TO_TYPES), )); } $normalizedValue[$from] = $to; } return $normalizedValue; }) ->setDefault($default) ->getOption(), ]); } private function fixMethod(Tokens $tokens, int $index): void { // find PHPDoc of method (if any) while (true) { $tokenIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$tokenIndex]->isGivenKind([\T_STATIC, \T_FINAL, \T_ABSTRACT, \T_PRIVATE, \T_PROTECTED, \T_PUBLIC])) { break; } $index = $tokenIndex; } $docIndex = $tokens->getPrevNonWhitespace($index); if (!$tokens[$docIndex]->isGivenKind(\T_DOC_COMMENT)) { return; } // find @return $docBlock = new DocBlock($tokens[$docIndex]->getContent()); $returnsBlock = $docBlock->getAnnotationsOfType('return'); if (0 === \count($returnsBlock)) { return; // no return annotation found } $returnsBlock = $returnsBlock[0]; $types = $returnsBlock->getTypes(); if (0 === \count($types)) { return; // no return type(s) found } $newTypes = []; foreach ($types as $type) { $newTypes[] = $this->configuration['replacements'][strtolower($type)] ?? $type; } if ($types === $newTypes) { return; } $returnsBlock->setTypes($newTypes); $tokens[$docIndex] = new Token([\T_DOC_COMMENT, $docBlock->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/Phpdoc/NoSuperfluousPhpdocTagsFixer.php
src/Fixer/Phpdoc/NoSuperfluousPhpdocTagsFixer.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\Phpdoc; use PhpCsFixer\AbstractFixer; use PhpCsFixer\DocBlock\Annotation; use PhpCsFixer\DocBlock\DocBlock; use PhpCsFixer\DocBlock\TypeExpression; 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\Future; use PhpCsFixer\Preg; use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer; 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; /** * @phpstan-type _TypeInfo array{ * types: list<string>, * allows_null: bool, * } * @phpstan-type _DocumentElement array{ * index: int, * type: 'classy'|'function'|'property', * modifiers: array<int, Token>, * types: array<int, Token>, * } * @phpstan-type _AutogeneratedInputConfiguration array{ * allow_hidden_params?: bool, * allow_mixed?: bool, * allow_unused_params?: bool, * remove_inheritdoc?: bool, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * allow_hidden_params: bool, * allow_mixed: bool, * allow_unused_params: bool, * remove_inheritdoc: bool, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NoSuperfluousPhpdocTagsFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; /** @var _TypeInfo */ private const NO_TYPE_INFO = [ 'types' => [], 'allows_null' => true, ]; private const SYMBOL_KINDS = [\T_CLASS, \T_INTERFACE, FCT::T_ENUM]; private const MODIFIER_KINDS = [ \T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_ABSTRACT, \T_FINAL, \T_STATIC, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET, ]; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Removes `@param`, `@return` and `@var` tags that don\'t provide any useful information.', [ new CodeSample( <<<'PHP' <?php class Foo { /** * @param Bar $bar * @param mixed $baz * * @return Baz */ public function doFoo(Bar $bar, $baz): Baz {} } PHP, ), new CodeSample( <<<'PHP' <?php class Foo { /** * @param Bar $bar * @param mixed $baz */ public function doFoo(Bar $bar, $baz) {} } PHP, ['allow_mixed' => true], ), new CodeSample( <<<'PHP' <?php class Foo { /** * @inheritDoc */ public function doFoo(Bar $bar, $baz) {} } PHP, ['remove_inheritdoc' => true], ), new CodeSample( <<<'PHP' <?php class Foo { /** * @param Bar $bar * @param mixed $baz * @param string|int|null $qux * @param mixed $foo */ public function doFoo(Bar $bar, $baz /*, $qux = null */) {} } PHP, ['allow_hidden_params' => true], ), new CodeSample( <<<'PHP' <?php class Foo { /** * @param Bar $bar * @param mixed $baz * @param string|int|null $qux * @param mixed $foo */ public function doFoo(Bar $bar, $baz /*, $qux = null */) {} } PHP, ['allow_unused_params' => true], ), ], ); } /** * {@inheritdoc} * * Must run before NoEmptyPhpdocFixer, PhpdocAlignFixer, VoidReturnFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, FullyQualifiedStrictTypesFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocIndentFixer, PhpdocLineSpanFixer, PhpdocReturnSelfReferenceFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 6; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $tokensAnalyzer = new TokensAnalyzer($tokens); $namespaceUseAnalyzer = new NamespaceUsesAnalyzer(); $shortNames = []; $currentSymbol = null; $currentSymbolEndIndex = null; foreach ($namespaceUseAnalyzer->getDeclarationsFromTokens($tokens) as $namespaceUseAnalysis) { $shortNames[strtolower($namespaceUseAnalysis->getShortName())] = strtolower($namespaceUseAnalysis->getFullName()); } foreach ($tokens as $index => $token) { if ($index === $currentSymbolEndIndex) { $currentSymbol = null; $currentSymbolEndIndex = null; continue; } if ($token->isGivenKind(\T_CLASS) && $tokensAnalyzer->isAnonymousClass($index)) { continue; } if ($token->isGivenKind(self::SYMBOL_KINDS)) { $currentSymbol = $tokens[$tokens->getNextMeaningfulToken($index)]->getContent(); $currentSymbolEndIndex = $tokens->findBlockEnd( Tokens::BLOCK_TYPE_CURLY_BRACE, $tokens->getNextTokenOfKind($index, ['{']), ); continue; } if (!$token->isGivenKind(\T_DOC_COMMENT)) { continue; } $documentedElement = $this->findDocumentedElement($tokens, $index); if (null === $documentedElement) { continue; } $content = $initialContent = $token->getContent(); if (true === $this->configuration['remove_inheritdoc']) { $content = $this->removeSuperfluousInheritDoc($content); } $namespace = (new NamespacesAnalyzer())->getNamespaceAt($tokens, $index)->getFullName(); if ('' === $namespace) { $namespace = null; } if ('function' === $documentedElement['type']) { $content = $this->fixFunctionDocComment($content, $tokens, $documentedElement, $namespace, $currentSymbol, $shortNames); } elseif ('property' === $documentedElement['type']) { $content = $this->fixPropertyDocComment($content, $tokens, $documentedElement, $namespace, $currentSymbol, $shortNames); } elseif ('classy' === $documentedElement['type']) { $content = $this->fixClassDocComment($content, $documentedElement); } else { throw new \RuntimeException('Unknown type.'); } if ('' === $content) { $content = '/** */'; } if ($content !== $initialContent) { $tokens[$index] = new Token([\T_DOC_COMMENT, $content]); } } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('allow_mixed', 'Whether type `mixed` without description is allowed (`true`) or considered superfluous (`false`).')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), (new FixerOptionBuilder('remove_inheritdoc', 'Remove `@inheritDoc` tags.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), (new FixerOptionBuilder('allow_hidden_params', 'Whether `param` annotation for hidden params in method signature are allowed.')) ->setAllowedTypes(['bool']) ->setDefault(Future::getV4OrV3(true, false)) ->getOption(), (new FixerOptionBuilder('allow_unused_params', 'Whether `param` annotation without actual signature is allowed (`true`) or considered superfluous (`false`).')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), ]); } /** * @return null|_DocumentElement */ private function findDocumentedElement(Tokens $tokens, int $docCommentIndex): ?array { $typeKinds = [ CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, \T_STRING, \T_NS_SEPARATOR, ]; $element = [ 'modifiers' => [], 'types' => [], ]; $index = $tokens->getNextMeaningfulToken($docCommentIndex); if (null !== $index && $tokens[$index]->isGivenKind(FCT::T_ATTRIBUTE)) { do { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); $index = $tokens->getNextMeaningfulToken($index); } while (null !== $index && $tokens[$index]->isGivenKind(\T_ATTRIBUTE)); } while (true) { if (null === $index) { break; } if ($tokens[$index]->isClassy()) { $element['index'] = $index; $element['type'] = 'classy'; return $element; } if ($tokens[$index]->isGivenKind([\T_FUNCTION, \T_FN])) { $element['index'] = $index; $element['type'] = 'function'; return $element; } if ($tokens[$index]->isGivenKind(\T_VARIABLE)) { $element['index'] = $index; $element['type'] = 'property'; return $element; } if ($tokens[$index]->isGivenKind(self::MODIFIER_KINDS)) { $element['modifiers'][$index] = $tokens[$index]; } elseif ($tokens[$index]->isGivenKind($typeKinds)) { $element['types'][$index] = $tokens[$index]; } else { break; } $index = $tokens->getNextMeaningfulToken($index); } return null; } /** * @param _DocumentElement&array{type: 'function'} $element * @param null|non-empty-string $namespace * @param array<string, string> $shortNames */ private function fixFunctionDocComment( string $content, Tokens $tokens, array $element, ?string $namespace, ?string $currentSymbol, array $shortNames ): string { $docBlock = new DocBlock($content); $openingParenthesisIndex = $tokens->getNextTokenOfKind($element['index'], ['(']); $closingParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openingParenthesisIndex); $argumentsInfo = $this->getArgumentsInfo( $tokens, $openingParenthesisIndex + 1, $closingParenthesisIndex - 1, ); foreach ($docBlock->getAnnotationsOfType('param') as $annotation) { $argumentName = $annotation->getVariableName(); if (null === $argumentName) { if ($this->annotationIsSuperfluous($annotation, self::NO_TYPE_INFO, $namespace, $currentSymbol, $shortNames)) { $annotation->remove(); } continue; } if (!isset($argumentsInfo[$argumentName]) && true === $this->configuration['allow_unused_params']) { continue; } if (!isset($argumentsInfo[$argumentName]) || $this->annotationIsSuperfluous($annotation, $argumentsInfo[$argumentName], $namespace, $currentSymbol, $shortNames)) { $annotation->remove(); } } $returnTypeInfo = $this->getReturnTypeInfo($tokens, $closingParenthesisIndex); foreach ($docBlock->getAnnotationsOfType('return') as $annotation) { if ($this->annotationIsSuperfluous($annotation, $returnTypeInfo, $namespace, $currentSymbol, $shortNames)) { $annotation->remove(); } } $this->removeSuperfluousModifierAnnotation($docBlock, $element); return $docBlock->getContent(); } /** * @param _DocumentElement&array{type: 'property'} $element * @param null|non-empty-string $namespace * @param array<string, string> $shortNames */ private function fixPropertyDocComment( string $content, Tokens $tokens, array $element, ?string $namespace, ?string $currentSymbol, array $shortNames ): string { if (\count($element['types']) > 0) { $propertyTypeInfo = $this->parseTypeHint($tokens, array_key_first($element['types'])); } else { $propertyTypeInfo = self::NO_TYPE_INFO; } $docBlock = new DocBlock($content); foreach ($docBlock->getAnnotationsOfType('var') as $annotation) { if ($this->annotationIsSuperfluous($annotation, $propertyTypeInfo, $namespace, $currentSymbol, $shortNames)) { $annotation->remove(); } } return $docBlock->getContent(); } /** * @param _DocumentElement&array{type: 'classy'} $element */ private function fixClassDocComment(string $content, array $element): string { $docBlock = new DocBlock($content); $this->removeSuperfluousModifierAnnotation($docBlock, $element); return $docBlock->getContent(); } /** * @return array<non-empty-string, _TypeInfo> */ private function getArgumentsInfo(Tokens $tokens, int $start, int $end): array { $argumentsInfo = []; for ($index = $start; $index <= $end; ++$index) { $token = $tokens[$index]; if (!$token->isGivenKind(\T_VARIABLE)) { continue; } $beforeArgumentIndex = $tokens->getPrevTokenOfKind($index, ['(', ',', [CT::T_ATTRIBUTE_CLOSE]]); $typeIndex = $tokens->getNextMeaningfulToken($beforeArgumentIndex); if ($typeIndex !== $index) { $info = $this->parseTypeHint($tokens, $typeIndex); } else { $info = self::NO_TYPE_INFO; } if (!$info['allows_null']) { $nextIndex = $tokens->getNextMeaningfulToken($index); if ( $tokens[$nextIndex]->equals('=') && $tokens[$tokens->getNextMeaningfulToken($nextIndex)]->equals([\T_STRING, 'null'], false) ) { $info['allows_null'] = true; } } $argumentsInfo[$token->getContent()] = $info; } // virtualise "hidden params" as if they would be regular ones if (true === $this->configuration['allow_hidden_params']) { $paramsString = $tokens->generatePartialCode($start, $end); Preg::matchAll('|/\*[^$]*(\$\w+)[^*]*\*/|', $paramsString, $matches); foreach ($matches[1] as $match) { $argumentsInfo[$match] = self::NO_TYPE_INFO; // HINT: one could try to extract actual type for hidden param, for now we only indicate it's existence } } return $argumentsInfo; } /** * @return _TypeInfo */ private function getReturnTypeInfo(Tokens $tokens, int $closingParenthesisIndex): array { $colonIndex = $tokens->getNextMeaningfulToken($closingParenthesisIndex); return $tokens[$colonIndex]->isGivenKind(CT::T_TYPE_COLON) ? $this->parseTypeHint($tokens, $tokens->getNextMeaningfulToken($colonIndex)) : self::NO_TYPE_INFO; } /** * @param int $index The index of the first token of the type hint * * @return _TypeInfo */ private function parseTypeHint(Tokens $tokens, int $index): array { $allowsNull = false; $types = []; while (true) { $type = ''; if ($tokens[$index]->isGivenKind([FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET])) { $index = $tokens->getNextMeaningfulToken($index); } if ($tokens[$index]->isGivenKind([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE])) { $index = $tokens->getNextMeaningfulToken($index); continue; } if ($tokens[$index]->isGivenKind(CT::T_NULLABLE_TYPE)) { $allowsNull = true; $index = $tokens->getNextMeaningfulToken($index); } while ($tokens[$index]->isGivenKind([\T_NS_SEPARATOR, \T_STATIC, \T_STRING, CT::T_ARRAY_TYPEHINT, \T_CALLABLE])) { $type .= $tokens[$index]->getContent(); $index = $tokens->getNextMeaningfulToken($index); } if ('' === $type) { break; } $types[] = $type; if (!$tokens[$index]->isGivenKind([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION])) { break; } $index = $tokens->getNextMeaningfulToken($index); } return [ 'types' => $types, 'allows_null' => $allowsNull, ]; } /** * @param _TypeInfo $info * @param null|non-empty-string $namespace * @param array<string, string> $symbolShortNames */ private function annotationIsSuperfluous( Annotation $annotation, array $info, ?string $namespace, ?string $currentSymbol, array $symbolShortNames ): bool { if ('param' === $annotation->getTag()->getName()) { $regex = '{\*\h*@param(?:\h+'.TypeExpression::REGEX_TYPES.')?(?!\S)(?:\h+(?:\&\h*)?(?:\.{3}\h*)?\$\S+)?(?:\s+(?<description>(?!\*+\/)\S+))?}s'; } elseif ('var' === $annotation->getTag()->getName()) { $regex = '{\*\h*@var(?:\h+'.TypeExpression::REGEX_TYPES.')?(?!\S)(?:\h+\$\S+)?(?:\s+(?<description>(?!\*\/)\S+))?}s'; } else { $regex = '{\*\h*@return(?:\h+'.TypeExpression::REGEX_TYPES.')?(?!\S)(?:\s+(?<description>(?!\*\/)\S+))?}s'; } if (!Preg::match($regex, $annotation->getContent(), $matches)) { // Unable to match the annotation, it must be malformed or has unsupported format. // Either way we don't want to tinker with it. return false; } if (isset($matches['description'])) { return false; } if (!isset($matches['types']) || '' === $matches['types']) { // If there's no type info in the annotation, further checks make no sense, exit early. return true; } $annotationTypes = $this->toComparableNames($annotation->getTypes(), $namespace, $currentSymbol, $symbolShortNames); if (['null'] === $annotationTypes && ['null'] !== $info['types']) { return false; } if (['mixed'] === $annotationTypes && [] === $info['types']) { return false === $this->configuration['allow_mixed']; } $actualTypes = $info['types']; if ($info['allows_null']) { $actualTypes[] = 'null'; } $actualTypes = $this->toComparableNames($actualTypes, $namespace, $currentSymbol, $symbolShortNames); if ($annotationTypes === $actualTypes) { return true; } // retry comparison with annotation type unioned with null // phpstan implies the null presence from the native type $annotationTypes = array_merge($annotationTypes, ['null']); sort($annotationTypes); return $actualTypes === $annotationTypes; } /** * Normalizes types to make them comparable. * * Converts given types to lowercase, replaces imports aliases with * their matching FQCN, and finally sorts the result. * * @param list<string> $types The types to normalize * @param null|non-empty-string $namespace * @param array<string, string> $symbolShortNames The imports aliases * * @return list<string> The normalized types */ private function toComparableNames(array $types, ?string $namespace, ?string $currentSymbol, array $symbolShortNames): array { if (isset($types[0][0]) && '?' === $types[0][0]) { $types = [ substr($types[0], 1), 'null', ]; } $normalized = array_map( function (string $type) use ($namespace, $currentSymbol, $symbolShortNames): string { if (str_contains($type, '&')) { $intersects = explode('&', $type); $intersects = $this->toComparableNames($intersects, $namespace, $currentSymbol, $symbolShortNames); return implode('&', $intersects); } if ('self' === $type && null !== $currentSymbol) { $type = $currentSymbol; } $type = strtolower($type); if (isset($symbolShortNames[$type])) { return $symbolShortNames[$type]; // always FQCN /wo leading backslash and in lower-case } if (str_starts_with($type, '\\')) { return substr($type, 1); } if (null !== $namespace && !(new TypeAnalysis($type))->isReservedType()) { $type = strtolower($namespace).'\\'.$type; } return $type; }, $types, ); sort($normalized); return $normalized; } private function removeSuperfluousInheritDoc(string $docComment): string { return Preg::replace('~ # $1: before @inheritDoc tag ( # beginning of comment or a PHPDoc tag (?: ^/\*\* (?: \R [ \t]*(?:\*[ \t]*)? )*? | @\N+ ) # empty comment lines (?: \R [ \t]*(?:\*[ \t]*?)? )* ) # spaces before @inheritDoc tag [ \t]* # @inheritDoc tag (?:@inheritDocs?|\{@inheritDocs?\}) # $2: after @inheritDoc tag ( # empty comment lines (?: \R [ \t]*(?:\*[ \t]*)? )* # a PHPDoc tag or end of comment (?: @\N+ | (?: \R [ \t]*(?:\*[ \t]*)? )* [ \t]*\*/$ ) ) ~ix', '$1$2', $docComment); } /** * @param _DocumentElement $element */ private function removeSuperfluousModifierAnnotation(DocBlock $docBlock, array $element): void { foreach (['abstract' => \T_ABSTRACT, 'final' => \T_FINAL] as $annotationType => $modifierToken) { $annotations = $docBlock->getAnnotationsOfType($annotationType); foreach ($element['modifiers'] as $token) { if ($token->isGivenKind($modifierToken)) { foreach ($annotations as $annotation) { $annotation->remove(); } } } } } }
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/Phpdoc/PhpdocSummaryFixer.php
src/Fixer/Phpdoc/PhpdocSummaryFixer.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\Phpdoc; use PhpCsFixer\AbstractFixer; use PhpCsFixer\DocBlock\DocBlock; use PhpCsFixer\DocBlock\ShortDescription; 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 Graham Campbell <hello@gjcampbell.co.uk> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocSummaryFixer extends AbstractFixer implements WhitespacesAwareFixerInterface { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'PHPDoc summary should end in either a full stop, exclamation mark, or question mark.', [ new CodeSample( <<<'PHP' <?php /** * Foo function is great */ function foo () {} PHP, ), ], ); } /** * {@inheritdoc} * * Must run before PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 0; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } 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()); $end = (new ShortDescription($doc))->getEnd(); if (null !== $end) { $line = $doc->getLine($end); $content = rtrim($line->getContent()); if ( // final line of Description is NOT properly formatted !$this->isCorrectlyFormatted($content) // and first line of Description, if different than final line, does NOT indicate a list && (1 === $end || ($doc->isMultiLine() && ':' !== substr(rtrim($doc->getLine(1)->getContent()), -1))) ) { $line->setContent($content.'.'.$this->whitespacesConfig->getLineEnding()); $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); } } } } /** * Is the last line of the short description correctly formatted? */ private function isCorrectlyFormatted(string $content): bool { if (str_contains(strtolower($content), strtolower('{@inheritdoc}'))) { return true; } return $content !== rtrim($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/Phpdoc/PhpdocInlineTagNormalizerFixer.php
src/Fixer/Phpdoc/PhpdocInlineTagNormalizerFixer.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\Phpdoc; 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{ * tags?: list<string>, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * tags: list<string>, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocInlineTagNormalizerFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Fixes PHPDoc inline tags.', [ new CodeSample( "<?php\n/**\n * @{TUTORIAL}\n * {{ @link }}\n * @inheritDoc\n */\n", ), new CodeSample( "<?php\n/**\n * @{TUTORIAL}\n * {{ @link }}\n * @inheritDoc\n */\n", ['tags' => ['TUTORIAL']], ), ], ); } /** * {@inheritdoc} * * Must run before PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 0; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { if (0 === \count($this->configuration['tags'])) { return; } foreach ($tokens as $index => $token) { if (!$token->isGivenKind(\T_DOC_COMMENT)) { continue; } // Move `@` inside tag, for example @{tag} -> {@tag}, replace multiple curly brackets, // remove spaces between '{' and '@', remove white space between end // of text and closing bracket and between the tag and inline comment. $content = Preg::replaceCallback( \sprintf( '#(?:@{+|{+\h*@)\h*(%s)\b([^}]*)(?:}+)#i', implode('|', array_map(static fn (string $tag): string => preg_quote($tag, '/'), $this->configuration['tags'])), ), static function (array $matches): string { $doc = trim($matches[2]); if ('' === $doc) { return '{@'.$matches[1].'}'; } return '{@'.$matches[1].' '.$doc.'}'; }, $token->getContent(), ); $tokens[$index] = new Token([\T_DOC_COMMENT, $content]); } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('tags', 'The list of tags to normalize.')) ->setAllowedTypes(['string[]']) ->setDefault(['example', 'id', 'internal', 'inheritdoc', 'inheritdocs', 'link', 'source', 'toc', 'tutorial']) ->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/Phpdoc/PhpdocAlignFixer.php
src/Fixer/Phpdoc/PhpdocAlignFixer.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\Phpdoc; use PhpCsFixer\AbstractFixer; use PhpCsFixer\DocBlock\DocBlock; 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\Token; use PhpCsFixer\Tokenizer\Tokens; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * align?: 'left'|'vertical', * spacing?: array<string, int>|int, * tags?: list<string>, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * align: 'left'|'vertical', * spacing: array<string, int>|int, * tags: list<string>, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @author Fabien Potencier <fabien@symfony.com> * @author Jordi Boggiano <j.boggiano@seld.be> * @author Sebastiaan Stok <s.stok@rollerscapes.net> * @author Graham Campbell <hello@gjcampbell.co.uk> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * @author Jakub Kwaśniewski <jakub@zero-85.pl> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocAlignFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; /** * @internal */ public const ALIGN_LEFT = 'left'; /** * @internal */ public const ALIGN_VERTICAL = 'vertical'; private const DEFAULT_TAGS = [ 'method', 'param', 'property', 'return', 'throws', 'type', 'var', ]; private const TAGS_WITH_NAME = [ 'param', 'property', 'property-read', 'property-write', 'phpstan-param', 'phpstan-property', 'phpstan-property-read', 'phpstan-property-write', 'phpstan-assert', 'phpstan-assert-if-true', 'phpstan-assert-if-false', 'psalm-param', 'psalm-param-out', 'psalm-property', 'psalm-property-read', 'psalm-property-write', 'psalm-assert', 'psalm-assert-if-true', 'psalm-assert-if-false', ]; private const TAGS_WITH_METHOD_SIGNATURE = [ 'method', 'phpstan-method', 'psalm-method', ]; private const DEFAULT_SPACING = 1; private const DEFAULT_SPACING_KEY = '_default'; private string $regex; private string $regexCommentLine; private string $align; /** * same spacing for all or specific for different tags. * * @var array<string, int>|int */ private $spacing = 1; public function getDefinition(): FixerDefinitionInterface { $code = <<<'EOF' <?php /** * @param EngineInterface $templating * @param string $format * @param int $code an HTTP response status code * @param bool $debug * @param mixed &$reference a parameter passed by reference * * @return Foo description foo * * @throws Foo description foo * description foo * */ EOF; return new FixerDefinition( 'All items of the given PHPDoc tags must be either left-aligned or (by default) aligned vertically.', [ new CodeSample($code), new CodeSample($code, ['align' => self::ALIGN_VERTICAL]), new CodeSample($code, ['align' => self::ALIGN_LEFT]), new CodeSample($code, ['align' => self::ALIGN_LEFT, 'spacing' => 2]), new CodeSample($code, ['align' => self::ALIGN_LEFT, 'spacing' => ['param' => 2]]), ], ); } /** * {@inheritdoc} * * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAnnotationWithoutDotFixer, PhpdocArrayTypeFixer, PhpdocIndentFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocListTypeFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocScalarFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagNoNamedArgumentsFixer, PhpdocTagTypeFixer, PhpdocToCommentFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. */ public function getPriority(): int { /* * Should be run after all other docblock fixers. This because they * modify other annotations to change their type and or separation * which totally change the behaviour of this fixer. It's important that * annotations are of the correct type, and are grouped correctly * before running this fixer. */ return -42; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } protected function configurePostNormalisation(): void { $tagsWithNameToAlign = array_intersect($this->configuration['tags'], self::TAGS_WITH_NAME); $tagsWithMethodSignatureToAlign = array_intersect($this->configuration['tags'], self::TAGS_WITH_METHOD_SIGNATURE); $tagsWithoutNameToAlign = array_diff($this->configuration['tags'], $tagsWithNameToAlign, $tagsWithMethodSignatureToAlign); $indentRegex = '^(?P<indent>(?:\ {2}|\t)*)\ ?'; $types = []; // e.g. @param <hint> <$var> if ([] !== $tagsWithNameToAlign) { $types[] = '(?P<tag>'.implode('|', $tagsWithNameToAlign).')\s+(?P<hint>(?:'.TypeExpression::REGEX_TYPES.')?)\s*(?P<var>(?:&|\.{3})?\$\S+)'; } // e.g. @return <hint> if ([] !== $tagsWithoutNameToAlign) { $types[] = '(?P<tag2>'.implode('|', $tagsWithoutNameToAlign).')\s+(?P<hint2>(?:'.TypeExpression::REGEX_TYPES.')?)'; } // e.g. @method <hint> <signature> if ([] !== $tagsWithMethodSignatureToAlign) { $types[] = '(?P<tag3>'.implode('|', $tagsWithMethodSignatureToAlign).')(\s+(?P<static>static))?(\s+(?P<hint3>(?:'.TypeExpression::REGEX_TYPES.')?))\s+(?P<signature>.+\))'; } // optional <desc> $desc = '(?:\s+(?P<desc>\V*))'; $this->regex = '/'.$indentRegex.'\*\h*@(?J)(?:'.implode('|', $types).')'.$desc.'\h*\r?$/'; $this->regexCommentLine = '/'.$indentRegex.'\*(?!\h?+@)(?:\s+(?P<desc>\V+))(?<!\*\/)\r?$/'; $this->align = $this->configuration['align']; $this->spacing = $this->configuration['spacing']; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(\T_DOC_COMMENT)) { continue; } $content = $token->getContent(); $docBlock = new DocBlock($content); $this->fixDocBlock($docBlock); $newContent = $docBlock->getContent(); if ($newContent !== $content) { $tokens[$index] = new Token([\T_DOC_COMMENT, $newContent]); } } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { $allowPositiveIntegers = static function ($value) { $spacings = \is_array($value) ? $value : [$value]; foreach ($spacings as $val) { if (\is_int($val) && $val <= 0) { throw new InvalidOptionsException('The option "spacing" is invalid. All spacings must be greater than zero.'); } } return true; }; $tags = new FixerOptionBuilder( 'tags', 'The tags that should be aligned. Allowed values are tags with name (`\''.implode('\', \'', self::TAGS_WITH_NAME).'\'`), tags with method signature (`\''.implode('\', \'', self::TAGS_WITH_METHOD_SIGNATURE).'\'`) and any custom tag with description (e.g. `@tag <desc>`).', ); $tags ->setAllowedTypes(['string[]']) ->setDefault(self::DEFAULT_TAGS) ; $align = new FixerOptionBuilder('align', 'How comments should be aligned.'); $align ->setAllowedTypes(['string']) ->setAllowedValues([self::ALIGN_LEFT, self::ALIGN_VERTICAL]) ->setDefault(self::ALIGN_VERTICAL) ; $spacing = new FixerOptionBuilder( 'spacing', 'Spacing between tag, hint, comment, signature, etc. You can set same spacing for all tags using a positive integer or different spacings for different tags using an associative array of positive integers `[\'tagA\' => spacingForA, \'tagB\' => spacingForB]`. If you want to define default spacing to more than 1 space use `_default` key in config array, e.g.: `[\'tagA\' => spacingForA, \'tagB\' => spacingForB, \'_default\' => spacingForAllOthers]`.', ); $spacing->setAllowedTypes(['int', 'array<string, int>']) ->setAllowedValues([$allowPositiveIntegers]) ->setDefault(self::DEFAULT_SPACING) ; return new FixerConfigurationResolver([$tags->getOption(), $align->getOption(), $spacing->getOption()]); } private function fixDocBlock(DocBlock $docBlock): void { $lineEnding = $this->whitespacesConfig->getLineEnding(); for ($i = 0, $l = \count($docBlock->getLines()); $i < $l; ++$i) { $matches = $this->getMatches($docBlock->getLine($i)->getContent()); if (null === $matches) { continue; } $current = $i; $items = [$matches]; while (true) { if (null === $docBlock->getLine(++$i)) { break 2; } $matches = $this->getMatches($docBlock->getLine($i)->getContent(), true); if (null === $matches) { break; } $items[] = $matches; } // compute the max length of the tag, hint and variables $hasStatic = false; $tagMax = 0; $hintMax = 0; $varMax = 0; foreach ($items as $item) { if (null === $item['tag']) { continue; } $hasStatic = $hasStatic || '' !== $item['static']; $tagMax = max($tagMax, \strlen($item['tag'])); $hintMax = max($hintMax, \strlen($item['hint'])); $varMax = max($varMax, \strlen($item['var'])); } $itemOpeningLine = null; $currTag = null; $spacingForTag = $this->spacingForTag($currTag); // update foreach ($items as $j => $item) { if (null === $item['tag']) { if ('@' === $item['desc'][0]) { $line = $item['indent'].' * '.$item['desc']; $docBlock->getLine($current + $j)->setContent($line.$lineEnding); continue; } $extraIndent = 2 * $spacingForTag; if (\in_array($itemOpeningLine['tag'], self::TAGS_WITH_NAME, true) || \in_array($itemOpeningLine['tag'], self::TAGS_WITH_METHOD_SIGNATURE, true)) { $extraIndent += $varMax + $spacingForTag; } if ($hasStatic) { $extraIndent += 7; // \strlen('static '); } $line = $item['indent'] .' * ' .('' !== $itemOpeningLine['hint'] ? ' ' : '') .$this->getIndent( $tagMax + $hintMax + $extraIndent, $this->getLeftAlignedDescriptionIndent($items, $j), ) .$item['desc']; $docBlock->getLine($current + $j)->setContent($line.$lineEnding); continue; } $currTag = $item['tag']; $spacingForTag = $this->spacingForTag($currTag); $itemOpeningLine = $item; $line = $item['indent'] .' * @' .$item['tag']; if ($hasStatic) { $line .= $this->getIndent( $tagMax - \strlen($item['tag']) + $spacingForTag, '' !== $item['static'] ? $spacingForTag : 0, ) .('' !== $item['static'] ? $item['static'] : $this->getIndent(6 /* \strlen('static') */, 0)); $hintVerticalAlignIndent = $spacingForTag; } else { $hintVerticalAlignIndent = $tagMax - \strlen($item['tag']) + $spacingForTag; } $line .= $this->getIndent( $hintVerticalAlignIndent, '' !== $item['hint'] ? $spacingForTag : 0, ) .$item['hint']; if ('' !== $item['var']) { $line .= $this->getIndent((0 !== $hintMax ? $hintMax : -1) - mb_strlen($item['hint']) + $spacingForTag, $spacingForTag) .$item['var'] .( '' !== $item['desc'] ? $this->getIndent($varMax - \strlen($item['var']) + $spacingForTag, $spacingForTag).$item['desc'] : '' ); } elseif ('' !== $item['desc']) { $line .= $this->getIndent($hintMax - \strlen($item['hint']) + $spacingForTag, $spacingForTag).$item['desc']; } $docBlock->getLine($current + $j)->setContent($line.$lineEnding); } } } private function spacingForTag(?string $tag): int { return (\is_int($this->spacing)) ? $this->spacing : ($this->spacing[$tag] ?? $this->spacing[self::DEFAULT_SPACING_KEY] ?? self::DEFAULT_SPACING); } /** * @TODO Introduce proper DTO instead of an array * * @return null|array{indent: null|string, tag: null|string, hint: string, var: null|string, static: string, desc?: null|string} */ private function getMatches(string $line, bool $matchCommentOnly = false): ?array { if (Preg::match($this->regex, $line, $matches)) { if (isset($matches['tag2']) && '' !== $matches['tag2']) { $matches['tag'] = $matches['tag2']; $matches['hint'] = $matches['hint2']; $matches['var'] = ''; } if (isset($matches['tag3']) && '' !== $matches['tag3']) { $matches['tag'] = $matches['tag3']; $matches['hint'] = $matches['hint3']; $matches['var'] = $matches['signature']; // Since static can be both a return type declaration & a keyword that defines static methods // we assume it's a type declaration when only one value is present if ('' === $matches['hint'] && '' !== $matches['static']) { $matches['hint'] = $matches['static']; $matches['static'] = ''; } } if (isset($matches['hint'])) { $matches['hint'] = trim($matches['hint']); } $matches['static'] ??= ''; return $matches; } if ($matchCommentOnly && Preg::match($this->regexCommentLine, $line, $matches)) { $matches['tag'] = null; $matches['var'] = ''; $matches['hint'] = ''; $matches['static'] = ''; return $matches; } return null; } private function getIndent(int $verticalAlignIndent, int $leftAlignIndent = 1): string { $indent = self::ALIGN_VERTICAL === $this->align ? $verticalAlignIndent : $leftAlignIndent; return str_repeat(' ', $indent); } /** * @param non-empty-list<array{indent: null|string, tag: null|string, hint: string, var: null|string, static: string, desc?: null|string}> $items */ private function getLeftAlignedDescriptionIndent(array $items, int $index): int { if (self::ALIGN_LEFT !== $this->align) { return 0; } // Find last tagged line: $item = null; for (; $index >= 0; --$index) { $item = $items[$index]; if (null !== $item['tag']) { break; } } // No last tag found — no indent: if (null === $item) { return 0; } $spacingForTag = $this->spacingForTag($item['tag']); // Indent according to existing values: return $this->getSentenceIndent($item['static'], $spacingForTag) + $this->getSentenceIndent($item['tag'], $spacingForTag) + $this->getSentenceIndent($item['hint'], $spacingForTag) + $this->getSentenceIndent($item['var'], $spacingForTag); } /** * Get indent for sentence. */ private function getSentenceIndent(?string $sentence, int $spacingForTag = 1): int { if (null === $sentence) { return 0; } $length = \strlen($sentence); return 0 === $length ? 0 : $length + $spacingForTag; } }
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/Phpdoc/PhpdocAddMissingParamAnnotationFixer.php
src/Fixer/Phpdoc/PhpdocAddMissingParamAnnotationFixer.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\Phpdoc; use PhpCsFixer\AbstractFixer; use PhpCsFixer\DocBlock\DocBlock; use PhpCsFixer\DocBlock\Line; 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\ArgumentsAnalyzer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * only_untyped?: bool, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * only_untyped: 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 PhpdocAddMissingParamAnnotationFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'PHPDoc should contain `@param` for all params.', [ new CodeSample( <<<'PHP' <?php /** * @param int $bar * * @return void */ function f9(string $foo, $bar, $baz) {} PHP, ), new CodeSample( <<<'PHP' <?php /** * @param int $bar * * @return void */ function f9(string $foo, $bar, $baz) {} PHP, ['only_untyped' => true], ), new CodeSample( <<<'PHP' <?php /** * @param int $bar * * @return void */ function f9(string $foo, $bar, $baz) {} PHP, ['only_untyped' => false], ), ], ); } /** * {@inheritdoc} * * Must run before NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer, PhpdocOrderFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, GeneralPhpdocTagRenameFixer, PhpdocIndentFixer, PhpdocNoAliasTagFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 10; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $argumentsAnalyzer = new ArgumentsAnalyzer(); for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) { $token = $tokens[$index]; if (!$token->isGivenKind(\T_DOC_COMMENT)) { continue; } $tokenContent = $token->getContent(); if (str_contains(strtolower($tokenContent), strtolower('inheritdoc'))) { continue; } // ignore one-line phpdocs like `/** foo */`, as there is no place to put new annotations if (!str_contains($tokenContent, "\n")) { continue; } $mainIndex = $index; $index = $tokens->getNextMeaningfulToken($index); if (null === $index) { return; } while ($tokens[$index]->isGivenKind([ \T_ABSTRACT, \T_FINAL, \T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC, ])) { $index = $tokens->getNextMeaningfulToken($index); } if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { continue; } $openIndex = $tokens->getNextTokenOfKind($index, ['(']); $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); $arguments = []; foreach ($argumentsAnalyzer->getArguments($tokens, $openIndex, $index) as $start => $end) { $argumentInfo = $this->prepareArgumentInformation($tokens, $start, $end); if (false === $this->configuration['only_untyped'] || '' === $argumentInfo['type']) { $arguments[$argumentInfo['name']] = $argumentInfo; } } if (0 === \count($arguments)) { continue; } $doc = new DocBlock($tokenContent); $lastParamLine = null; foreach ($doc->getAnnotationsOfType('param') as $annotation) { $pregMatched = Preg::match('/^[^$]+(\$\w+).*$/s', $annotation->getContent(), $matches); if ($pregMatched) { unset($arguments[$matches[1]]); } $lastParamLine = max($lastParamLine, $annotation->getEnd()); } if (0 === \count($arguments)) { continue; } $lines = $doc->getLines(); $linesCount = \count($lines); Preg::match('/^(\s*).*$/', $lines[$linesCount - 1]->getContent(), $matches); $indent = $matches[1]; $newLines = []; foreach ($arguments as $argument) { $type = '' !== $argument['type'] ? $argument['type'] : 'mixed'; if (!str_starts_with($type, '?') && 'null' === strtolower($argument['default'])) { $type = 'null|'.$type; } $newLines[] = new Line(\sprintf( '%s* @param %s %s%s', $indent, $type, $argument['name'], $this->whitespacesConfig->getLineEnding(), )); } array_splice( $lines, $lastParamLine > 0 ? $lastParamLine + 1 : $linesCount - 1, 0, $newLines, ); $tokens[$mainIndex] = new Token([\T_DOC_COMMENT, implode('', $lines)]); } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('only_untyped', 'Whether to add missing `@param` annotations for untyped parameters only.')) ->setDefault(true) ->setAllowedTypes(['bool']) ->getOption(), ]); } /** * @return array{default: string, name: string, type: string} */ private function prepareArgumentInformation(Tokens $tokens, int $start, int $end): array { $info = [ 'default' => '', 'name' => '', 'type' => '', ]; $sawName = false; for ($index = $start; $index <= $end; ++$index) { $token = $tokens[$index]; if ( $token->isComment() || $token->isWhitespace() || $token->isGivenKind([ CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET, ]) ) { continue; } if ($token->isGivenKind(\T_VARIABLE)) { $sawName = true; $info['name'] = $token->getContent(); continue; } if ($token->equals('=')) { continue; } if ($sawName) { $info['default'] .= $token->getContent(); } elseif (!$token->equals('&')) { if ($token->isGivenKind(\T_ELLIPSIS)) { if ('' === $info['type']) { $info['type'] = 'array'; } else { $info['type'] .= '[]'; } } else { $info['type'] .= $token->getContent(); } } } return $info; } }
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/Phpdoc/PhpdocNoPackageFixer.php
src/Fixer/Phpdoc/PhpdocNoPackageFixer.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\Phpdoc; use PhpCsFixer\AbstractProxyFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; /** * @author Graham Campbell <hello@gjcampbell.co.uk> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocNoPackageFixer extends AbstractProxyFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( '`@package` and `@subpackage` annotations must be removed from PHPDoc.', [ new CodeSample( <<<'PHP' <?php /** * @internal * @package Foo * subpackage Bar */ class Baz { } PHP, ), ], ); } /** * {@inheritdoc} * * Must run before NoEmptyPhpdocFixer, PhpdocAlignFixer, PhpdocSeparationFixer, PhpdocTrimFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return parent::getPriority(); } protected function createProxyFixers(): array { $fixer = new GeneralPhpdocAnnotationRemoveFixer(); $fixer->configure([ 'annotations' => ['package', 'subpackage'], 'case_sensitive' => 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/Phpdoc/PhpdocVarWithoutNameFixer.php
src/Fixer/Phpdoc/PhpdocVarWithoutNameFixer.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\Phpdoc; use PhpCsFixer\AbstractFixer; use PhpCsFixer\DocBlock\DocBlock; use PhpCsFixer\DocBlock\Line; use PhpCsFixer\DocBlock\TypeExpression; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Preg; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @author Graham Campbell <hello@gjcampbell.co.uk> * @author Dave van der Brugge <dmvdbrugge@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocVarWithoutNameFixer extends AbstractFixer { private const PROPERTY_MODIFIER_KINDS = [\T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_VAR, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET]; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( '`@var` and `@type` annotations of classy properties should not contain the name.', [ new CodeSample( <<<'PHP' <?php final class Foo { /** * @var int $bar */ public $bar; /** * @type $baz float */ public $baz; } PHP, ), ], ); } /** * {@inheritdoc} * * Must run before PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 0; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT) && $tokens->isAnyTokenKindsFound([\T_CLASS, \T_TRAIT]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(\T_DOC_COMMENT)) { continue; } $nextIndex = $tokens->getNextMeaningfulToken($index); if (null === $nextIndex) { continue; } // For people writing "static public $foo" instead of "public static $foo" if ($tokens[$nextIndex]->isGivenKind(\T_STATIC)) { $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); } // We want only doc blocks that are for properties and thus have specified access modifiers next if (!$tokens[$nextIndex]->isGivenKind(self::PROPERTY_MODIFIER_KINDS)) { continue; } $doc = new DocBlock($token->getContent()); $firstLevelLines = $this->getFirstLevelLines($doc); $annotations = $doc->getAnnotationsOfType(['type', 'var']); foreach ($annotations as $annotation) { if (isset($firstLevelLines[$annotation->getStart()])) { $this->fixLine($firstLevelLines[$annotation->getStart()]); } } $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); } } private function fixLine(Line $line): void { Preg::matchAll('/ \$'.TypeExpression::REGEX_IDENTIFIER.'(?<!\$this)/', $line->getContent(), $matches); foreach ($matches[0] as $match) { $line->setContent(str_replace($match, '', $line->getContent())); } } /** * @return array<int, Line> */ private function getFirstLevelLines(DocBlock $docBlock): array { $nested = 0; $lines = $docBlock->getLines(); foreach ($lines as $index => $line) { $content = $line->getContent(); if (Preg::match('/\s*\*\s*}$/', $content)) { --$nested; } if ($nested > 0) { unset($lines[$index]); } if (Preg::match('/\s\{$/', $content)) { ++$nested; } } return $lines; } }
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/Phpdoc/GeneralPhpdocAnnotationRemoveFixer.php
src/Fixer/Phpdoc/GeneralPhpdocAnnotationRemoveFixer.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\Phpdoc; use PhpCsFixer\AbstractFixer; use PhpCsFixer\DocBlock\Annotation; 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\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * annotations?: list<string>, * case_sensitive?: bool, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * annotations: list<string>, * case_sensitive: bool, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @author Graham Campbell <hello@gjcampbell.co.uk> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class GeneralPhpdocAnnotationRemoveFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Removes configured annotations from PHPDoc.', [ new CodeSample( <<<'PHP' <?php /** * @internal * @author John Doe * @AuThOr Jane Doe */ function foo() {} PHP, ['annotations' => ['author']], ), new CodeSample( <<<'PHP' <?php /** * @internal * @author John Doe * @AuThOr Jane Doe */ function foo() {} PHP, ['annotations' => ['author'], 'case_sensitive' => false], ), new CodeSample( <<<'PHP' <?php /** * @author John Doe * @package ACME API * @subpackage Authorization * @version 1.0 */ function foo() {} PHP, ['annotations' => ['package', 'subpackage']], ), ], ); } /** * {@inheritdoc} * * Must run before NoEmptyPhpdocFixer, PhpdocAlignFixer, PhpdocLineSpanFixer, PhpdocSeparationFixer, PhpdocTrimFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 10; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { if (0 === \count($this->configuration['annotations'])) { return; } foreach ($tokens as $index => $token) { if (!$token->isGivenKind(\T_DOC_COMMENT)) { continue; } $doc = new DocBlock($token->getContent()); $annotations = $this->getAnnotationsToRemove($doc); // nothing to do if there are no annotations if (0 === \count($annotations)) { continue; } foreach ($annotations as $annotation) { $annotation->remove(); } if ('' === $doc->getContent()) { $tokens->clearTokenAndMergeSurroundingWhitespace($index); } else { $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); } } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('annotations', 'List of annotations to remove, e.g. `["author"]`.')) ->setAllowedTypes(['string[]']) ->setDefault([]) ->getOption(), (new FixerOptionBuilder('case_sensitive', 'Should annotations be case sensitive.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), ]); } /** * @return list<Annotation> */ private function getAnnotationsToRemove(DocBlock $doc): array { if (true === $this->configuration['case_sensitive']) { return $doc->getAnnotationsOfType($this->configuration['annotations']); } $typesToSearchFor = array_map(static fn (string $type): string => strtolower($type), $this->configuration['annotations']); $annotations = []; foreach ($doc->getAnnotations() as $annotation) { $tagName = strtolower($annotation->getTag()->getName()); if (\in_array($tagName, $typesToSearchFor, true)) { $annotations[] = $annotation; } } return $annotations; } }
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/Phpdoc/PhpdocScalarFixer.php
src/Fixer/Phpdoc/PhpdocScalarFixer.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\Phpdoc; use PhpCsFixer\AbstractPhpdocTypesFixer; 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\Future; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * types?: list<'boolean'|'callback'|'double'|'integer'|'never-return'|'never-returns'|'no-return'|'real'|'str'>, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * types: list<'boolean'|'callback'|'double'|'integer'|'never-return'|'never-returns'|'no-return'|'real'|'str'>, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @author Graham Campbell <hello@gjcampbell.co.uk> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocScalarFixer extends AbstractPhpdocTypesFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; /** * The types to fix. */ private const TYPES_MAP = [ 'boolean' => 'bool', 'callback' => 'callable', 'double' => 'float', 'integer' => 'int', 'never-return' => 'never', 'never-returns' => 'never', 'no-return' => 'never', 'real' => 'float', 'str' => 'string', ]; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Scalar types should always be written in the same form. `int` not `integer`, `bool` not `boolean`, `float` not `real` or `double`.', [ new CodeSample( <<<'PHP' <?php /** * @param integer $a * @param boolean $b * @param real $c * * @return double */ function sample($a, $b, $c) { return sample2($a, $b, $c); } PHP, ), new CodeSample( <<<'PHP' <?php /** * @param integer $a * @param boolean $b * @param real $c */ function sample($a, $b, $c) { return sample2($a, $b, $c); } PHP, ['types' => ['boolean']], ), ], ); } /** * {@inheritdoc} * * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocArrayTypeFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocListTypeFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagNoNamedArgumentsFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. * Must run after PhpdocTypesFixer. */ public function getPriority(): int { /* * Should be run before all other docblock fixers apart from the * phpdoc_to_comment and phpdoc_indent fixer to make sure all fixers * apply correct indentation to new code they add. This should run * before alignment of params is done since this fixer might change * the type and thereby un-aligning the params. We also must run after * the phpdoc_types_fixer because it can convert types to things that * we can fix. */ return 15; } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { $defaultTypes = ['boolean', 'callback', 'double', 'integer', 'real', 'str']; $allowedTypes = array_keys(self::TYPES_MAP); return new FixerConfigurationResolver([ (new FixerOptionBuilder('types', 'A list of types to fix.')) ->setAllowedValues([new AllowedValueSubset($allowedTypes)]) ->setDefault(Future::getV4OrV3($allowedTypes, $defaultTypes)) ->getOption(), ]); } protected function normalize(string $type): string { $suffix = ''; while (str_ends_with($type, '[]')) { $type = substr($type, 0, -2); $suffix .= '[]'; } if (\in_array($type, $this->configuration['types'], true)) { $type = self::TYPES_MAP[$type]; } return $type.$suffix; } }
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/Phpdoc/PhpdocNoAliasTagFixer.php
src/Fixer/Phpdoc/PhpdocNoAliasTagFixer.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\Phpdoc; use PhpCsFixer\AbstractProxyFixer; use PhpCsFixer\ConfigurationException\InvalidConfigurationException; 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\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Future; use PhpCsFixer\Preg; /** * Case-sensitive tag replace fixer (does not process inline tags like {@inheritdoc}). * * @phpstan-type _AutogeneratedInputConfiguration array{ * replacements?: array<string, string>, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * replacements: array<string, string>, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @author Graham Campbell <hello@gjcampbell.co.uk> * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocNoAliasTagFixer extends AbstractProxyFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'No alias PHPDoc tags should be used.', [ new CodeSample( <<<'PHP' <?php /** * @property string $foo * @property-read string $bar * * @link baz */ final class Example { } PHP, ), new CodeSample( <<<'PHP' <?php /** * @property string $foo * @property-read string $bar * * @link baz */ final class Example { } PHP, ['replacements' => ['link' => 'website']], ), ], ); } /** * {@inheritdoc} * * Must run before PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocSingleLineVarSpacingFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return parent::getPriority(); } protected function configurePostNormalisation(): void { /** @var GeneralPhpdocTagRenameFixer $generalPhpdocTagRenameFixer */ $generalPhpdocTagRenameFixer = $this->proxyFixers['general_phpdoc_tag_rename']; try { $generalPhpdocTagRenameFixer->configure([ 'fix_annotation' => true, 'fix_inline' => false, 'replacements' => $this->configuration['replacements'], 'case_sensitive' => true, ]); } catch (InvalidConfigurationException $exception) { throw new InvalidFixerConfigurationException( $this->getName(), Preg::replace('/^\[.+?\] /', '', $exception->getMessage()), $exception, ); } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('replacements', 'Mapping between replaced annotations with new ones.')) ->setAllowedTypes(['array<string, string>']) ->setDefault( Future::getV4OrV3(['const' => 'var'], []) + [ 'property-read' => 'property', 'property-write' => 'property', 'type' => 'var', 'link' => 'see', ], ) ->getOption(), ]); } protected function createProxyFixers(): array { return [new GeneralPhpdocTagRenameFixer()]; } }
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/Phpdoc/PhpdocTagTypeFixer.php
src/Fixer/Phpdoc/PhpdocTagTypeFixer.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\Phpdoc; 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; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; use Symfony\Component\OptionsResolver\Options; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * tags?: array<string, 'annotation'|'inline'>, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * tags: array<string, 'annotation'|'inline'>, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocTagTypeFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; private const TAG_REGEX = '/^(?: (?<tag> (?:@(?<tag_name>.+?)(?:\s.+)?) ) | {(?<inlined_tag> (?:@(?<inlined_tag_name>.+?)(?:\s.+)?) )} )$/x'; public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Forces PHPDoc tags to be either regular annotations or inline.', [ new CodeSample( "<?php\n/**\n * {@api}\n */\n", ), new CodeSample( "<?php\n/**\n * @inheritdoc\n */\n", ['tags' => ['inheritdoc' => 'inline']], ), ], ); } /** * {@inheritdoc} * * Must run before PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 0; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { if (0 === \count($this->configuration['tags'])) { return; } $regularExpression = \sprintf( '/({?@(?:%s).*?(?:(?=\s\*\/)|(?=\n)}?))/i', implode('|', array_map( static fn (string $tag): string => preg_quote($tag, '/'), array_keys($this->configuration['tags']), )), ); foreach ($tokens as $index => $token) { if (!$token->isGivenKind(\T_DOC_COMMENT)) { continue; } $parts = Preg::split( $regularExpression, $token->getContent(), -1, \PREG_SPLIT_DELIM_CAPTURE, ); for ($i = 1, $max = \count($parts) - 1; $i < $max; $i += 2) { if (!Preg::match(self::TAG_REGEX, $parts[$i], $matches)) { continue; } if ('' !== $matches['tag']) { $tag = $matches['tag']; $tagName = $matches['tag_name']; } else { $tag = $matches['inlined_tag']; $tagName = $matches['inlined_tag_name']; } $tagName = strtolower($tagName); if (!isset($this->configuration['tags'][$tagName])) { continue; } if ('inline' === $this->configuration['tags'][$tagName]) { $parts[$i] = '{'.$tag.'}'; continue; } if (!$this->tagIsSurroundedByText($parts, $i)) { $parts[$i] = $tag; } } $tokens[$index] = new Token([\T_DOC_COMMENT, implode('', $parts)]); } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('tags', 'The list of tags to fix.')) ->setAllowedTypes(["array<string, 'annotation'|'inline'>"]) ->setAllowedValues([static function (array $value): bool { foreach ($value as $type) { if (!\in_array($type, ['annotation', 'inline'], true)) { throw new InvalidOptionsException("Unknown tag type \"{$type}\"."); } } return true; }]) ->setDefault([ 'api' => 'annotation', 'author' => 'annotation', 'copyright' => 'annotation', 'deprecated' => 'annotation', 'example' => 'annotation', 'global' => 'annotation', 'inheritDoc' => 'annotation', 'internal' => 'annotation', 'license' => 'annotation', 'method' => 'annotation', 'package' => 'annotation', 'param' => 'annotation', 'property' => 'annotation', 'return' => 'annotation', 'see' => 'annotation', 'since' => 'annotation', 'throws' => 'annotation', 'todo' => 'annotation', 'uses' => 'annotation', 'var' => 'annotation', 'version' => 'annotation', ]) ->setNormalizer(static function (Options $options, array $value): array { $normalized = []; foreach ($value as $tag => $type) { $normalized[strtolower($tag)] = $type; } return $normalized; }) ->getOption(), ]); } /** * @param array<int,string> $parts */ private function tagIsSurroundedByText(array $parts, int $index): bool { return Preg::match('/(^|\R)\h*[^@\s]\N*/', $this->cleanComment($parts[$index - 1])) || Preg::match('/^.*?\R\s*[^@\s]/', $this->cleanComment($parts[$index + 1])); } private function cleanComment(string $comment): string { $comment = Preg::replace('/^\/\*\*|\*\/$/', '', $comment); return Preg::replace('/(\R)(\h*\*)?\h*/', '$1', $comment); } }
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/Phpdoc/PhpdocLineSpanFixer.php
src/Fixer/Phpdoc/PhpdocLineSpanFixer.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\Phpdoc; use PhpCsFixer\AbstractFixer; 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\Tokenizer\Analyzer\WhitespacesAnalyzer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; use PhpCsFixer\Tokenizer\TokensAnalyzer; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * const?: 'multi'|'single'|null, * method?: 'multi'|'single'|null, * property?: 'multi'|'single'|null, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * const: 'multi'|'single'|null, * method: 'multi'|'single'|null, * property: 'multi'|'single'|null, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @author Gert de Pagter <BackEndTea@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocLineSpanFixer extends AbstractFixer implements WhitespacesAwareFixerInterface, ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; private const PROPERTY_PART_KINDS = [ \T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_FINAL, \T_ABSTRACT, \T_COMMENT, \T_VAR, \T_STATIC, \T_STRING, \T_NS_SEPARATOR, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, CT::T_ARRAY_TYPEHINT, CT::T_NULLABLE_TYPE, FCT::T_ATTRIBUTE, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET, ]; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Changes doc blocks from single to multi line, or reversed. Works for class constants, properties and methods only.', [ new CodeSample("<?php\n\nclass Foo{\n /** @var bool */\n public \$var;\n}\n"), new CodeSample( "<?php\n\nclass Foo{\n /**\n * @var bool\n */\n public \$var;\n}\n", ['property' => 'single'], ), ], ); } /** * {@inheritdoc} * * Must run before NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, GeneralPhpdocAnnotationRemoveFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 7; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('const', 'Whether const blocks should be single or multi line.')) ->setAllowedValues(['single', 'multi', null]) ->setDefault('multi') ->getOption(), (new FixerOptionBuilder('property', 'Whether property doc blocks should be single or multi line.')) ->setAllowedValues(['single', 'multi', null]) ->setDefault('multi') ->getOption(), (new FixerOptionBuilder('method', 'Whether method doc blocks should be single or multi line.')) ->setAllowedValues(['single', 'multi', null]) ->setDefault('multi') ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $analyzer = new TokensAnalyzer($tokens); foreach ($analyzer->getClassyElements() as $index => $element) { $type = $element['type']; $type = 'promoted_property' === $type ? 'property' : $type; if (!isset($this->configuration[$type])) { continue; } if (!$this->hasDocBlock($tokens, $index)) { continue; } $docIndex = $this->getDocBlockIndex($tokens, $index); $doc = new DocBlock($tokens[$docIndex]->getContent()); if ('multi' === $this->configuration[$type]) { $doc->makeMultiLine(WhitespacesAnalyzer::detectIndent($tokens, $docIndex), $this->whitespacesConfig->getLineEnding()); } elseif ('single' === $this->configuration[$type]) { $doc->makeSingleLine(); } $tokens->offsetSet($docIndex, new Token([\T_DOC_COMMENT, $doc->getContent()])); } } private function hasDocBlock(Tokens $tokens, int $index): bool { $docBlockIndex = $this->getDocBlockIndex($tokens, $index); return $tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT); } 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::PROPERTY_PART_KINDS)); 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/Phpdoc/PhpdocTypesOrderFixer.php
src/Fixer/Phpdoc/PhpdocTypesOrderFixer.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\Phpdoc; use PhpCsFixer\AbstractFixer; use PhpCsFixer\DocBlock\Annotation; use PhpCsFixer\DocBlock\DocBlock; use PhpCsFixer\DocBlock\TypeExpression; 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{ * 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> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpdocTypesOrderFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Sorts PHPDoc types.', [ new CodeSample( <<<'PHP' <?php /** * @param string|null $bar */ PHP, ), new CodeSample( <<<'PHP' <?php /** * @param null|string $bar */ PHP, ['null_adjustment' => 'always_last'], ), new CodeSample( <<<'PHP' <?php /** * @param null|string|int|\Foo $bar */ PHP, ['sort_algorithm' => 'alpha'], ), new CodeSample( <<<'PHP' <?php /** * @param null|string|int|\Foo $bar */ PHP, [ 'sort_algorithm' => 'alpha', 'null_adjustment' => 'always_last', ], ), new CodeSample( <<<'PHP' <?php /** * @param null|string|int|\Foo $bar */ PHP, [ 'sort_algorithm' => 'alpha', 'null_adjustment' => 'none', ], ), new CodeSample( <<<'PHP' <?php /** * @param Aaa|AA $bar */ PHP, ['case_sensitive' => true], ), ], ); } /** * {@inheritdoc} * * Must run before PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocArrayTypeFixer, PhpdocIndentFixer, PhpdocListTypeFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return 0; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('sort_algorithm', 'The sorting algorithm to apply.')) ->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('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 { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(\T_DOC_COMMENT)) { continue; } $doc = new DocBlock($token->getContent()); $annotations = $doc->getAnnotationsOfType(Annotation::TAGS_WITH_TYPES); if (0 === \count($annotations)) { continue; } foreach ($annotations as $annotation) { // fix main types if (null !== $annotation->getTypeExpression()) { $annotation->setTypes( $this->sortTypes( $annotation->getTypeExpression(), ), ); } // fix @method parameters types $line = $doc->getLine($annotation->getStart()); $line->setContent(Preg::replaceCallback('/\*\h*@method\h+'.TypeExpression::REGEX_TYPES.'\h+\K(?&callable)/', function (array $matches) { $typeExpression = new TypeExpression($matches[0], null, []); return implode('|', $this->sortTypes($typeExpression)); }, $line->getContent())); } $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); } } /** * @return list<string> */ private function sortTypes(TypeExpression $typeExpression): array { $normalizeType = static fn (string $type): string => Preg::replace('/^\(*\??\\\?/', '', $type); $sortedTypeExpression = $typeExpression->sortTypes( function (TypeExpression $a, TypeExpression $b) use ($normalizeType): int { $a = $normalizeType($a->toString()); $b = $normalizeType($b->toString()); $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 $sortedTypeExpression->getTypes(); } }
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/Phpdoc/GeneralPhpdocTagRenameFixer.php
src/Fixer/Phpdoc/GeneralPhpdocTagRenameFixer.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\Phpdoc; 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; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; use Symfony\Component\OptionsResolver\Options; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * case_sensitive?: bool, * fix_annotation?: bool, * fix_inline?: bool, * replacements?: array<string, string>, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * case_sensitive: bool, * fix_annotation: bool, * fix_inline: bool, * replacements: array<string, string>, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class GeneralPhpdocTagRenameFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Renames PHPDoc tags.', [ new CodeSample("<?php\n/**\n * @inheritDocs\n * {@inheritdocs}\n */\n", [ 'replacements' => [ 'inheritDocs' => 'inheritDoc', ], ]), new CodeSample("<?php\n/**\n * @inheritDocs\n * {@inheritdocs}\n */\n", [ 'replacements' => [ 'inheritDocs' => 'inheritDoc', ], 'fix_annotation' => false, ]), new CodeSample("<?php\n/**\n * @inheritDocs\n * {@inheritdocs}\n */\n", [ 'replacements' => [ 'inheritDocs' => 'inheritDoc', ], 'fix_inline' => false, ]), new CodeSample("<?php\n/**\n * @inheritDocs\n * {@inheritdocs}\n */\n", [ 'replacements' => [ 'inheritDocs' => 'inheritDoc', ], 'case_sensitive' => true, ]), ], ); } /** * {@inheritdoc} * * Must run before PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { // must be run before PhpdocAddMissingParamAnnotationFixer return 11; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('fix_annotation', 'Whether annotation tags should be fixed.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), (new FixerOptionBuilder('fix_inline', 'Whether inline tags should be fixed.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), (new FixerOptionBuilder('replacements', 'A map of tags to replace.')) ->setAllowedTypes(['array<string, string>']) ->setNormalizer(static function (Options $options, array $value): array { $normalizedValue = []; foreach ($value as $from => $to) { if (!\is_string($from)) { throw new InvalidOptionsException('Tag to replace must be a string.'); } if (!Preg::match('#^\S+$#', $to) || str_contains($to, '*/')) { throw new InvalidOptionsException(\sprintf( 'Tag "%s" cannot be replaced by invalid tag "%s".', $from, $to, )); } $from = trim($from); $to = trim($to); if (false === $options['case_sensitive']) { $lowercaseFrom = strtolower($from); if (isset($normalizedValue[$lowercaseFrom]) && $normalizedValue[$lowercaseFrom] !== $to) { throw new InvalidOptionsException(\sprintf( 'Tag "%s" cannot be configured to be replaced with several different tags when case sensitivity is off.', $from, )); } $from = $lowercaseFrom; } $normalizedValue[$from] = $to; } foreach ($normalizedValue as $from => $to) { if (isset($normalizedValue[$to]) && $normalizedValue[$to] !== $to) { throw new InvalidOptionsException(\sprintf( 'Cannot change tag "%1$s" to tag "%2$s", as the tag "%2$s" is configured to be replaced to "%3$s".', $from, $to, $normalizedValue[$to], )); } } return $normalizedValue; }) ->setDefault([]) ->getOption(), (new FixerOptionBuilder('case_sensitive', 'Whether tags should be replaced only if they have exact same casing.')) ->setAllowedTypes(['bool']) ->setDefault(false) ->getOption(), ]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { if (0 === \count($this->configuration['replacements'])) { return; } if (true === $this->configuration['fix_annotation']) { $regex = true === $this->configuration['fix_inline'] ? '/(["\'])[^\1]*\1(*SKIP)(*FAIL)|\b(?<=@)(?P<tag>%s)\b/' : '/(["\'])[^\1]*\1(*SKIP)(*FAIL)|(?<!\{@)(?<=@)(?P<tag>%s)(?!\})/'; } else { $regex = '/(?<={@)(?P<tag>%s)(?=[ \t}])/'; } $caseInsensitive = false === $this->configuration['case_sensitive']; $replacements = $this->configuration['replacements']; $regex = \sprintf($regex, implode('|', array_keys($replacements))); if ($caseInsensitive) { $regex .= 'i'; } foreach ($tokens as $index => $token) { if (!$token->isGivenKind(\T_DOC_COMMENT)) { continue; } $tokens[$index] = new Token([\T_DOC_COMMENT, Preg::replaceCallback( $regex, static function (array $matches) use ($caseInsensitive, $replacements) { \assert(isset($matches['tag'])); if ($caseInsensitive) { $matches['tag'] = strtolower($matches['tag']); } return $replacements[$matches['tag']]; }, $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/Phpdoc/PhpdocTrimConsecutiveBlankLineSeparationFixer.php
src/Fixer/Phpdoc/PhpdocTrimConsecutiveBlankLineSeparationFixer.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\Phpdoc; use PhpCsFixer\AbstractFixer; use PhpCsFixer\DocBlock\DocBlock; use PhpCsFixer\DocBlock\Line; use PhpCsFixer\DocBlock\ShortDescription; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @author Nobu Funaki <nobu.funaki@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 PhpdocTrimConsecutiveBlankLineSeparationFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Removes extra blank lines after summary and after description in PHPDoc.', [ new CodeSample( <<<'PHP' <?php /** * Summary. * * * Description that contain 4 lines, * * * while 2 of them are blank! * * * @param string $foo * * * @dataProvider provideFixCases */ function fnc($foo) {} PHP, ), ], ); } /** * {@inheritdoc} * * Must run before PhpdocAlignFixer. * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpUnitAttributesFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. */ public function getPriority(): int { return -41; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_DOC_COMMENT); } 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()); $summaryEnd = (new ShortDescription($doc))->getEnd(); if (null !== $summaryEnd) { $this->fixSummary($doc, $summaryEnd); $this->fixDescription($doc, $summaryEnd); } $this->fixAllTheRest($doc); $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); } } private function fixSummary(DocBlock $doc, int $summaryEnd): void { $nonBlankLineAfterSummary = $this->findNonBlankLine($doc, $summaryEnd); $this->removeExtraBlankLinesBetween($doc, $summaryEnd, $nonBlankLineAfterSummary); } private function fixDescription(DocBlock $doc, int $summaryEnd): void { $annotationStart = $this->findFirstAnnotationOrEnd($doc); // assuming the end of the Description appears before the first Annotation $descriptionEnd = $this->reverseFindLastUsefulContent($doc, $annotationStart); if (null === $descriptionEnd || $summaryEnd === $descriptionEnd) { return; // no Description } if ($annotationStart === \count($doc->getLines()) - 1) { return; // no content after Description } $this->removeExtraBlankLinesBetween($doc, $descriptionEnd, $annotationStart); } private function fixAllTheRest(DocBlock $doc): void { $annotationStart = $this->findFirstAnnotationOrEnd($doc); $lastLine = $this->reverseFindLastUsefulContent($doc, \count($doc->getLines()) - 1); if (null !== $lastLine && $annotationStart !== $lastLine) { $this->removeExtraBlankLinesBetween($doc, $annotationStart, $lastLine); } } private function removeExtraBlankLinesBetween(DocBlock $doc, int $from, int $to): void { for ($index = $from + 1; $index < $to; ++$index) { $line = $doc->getLine($index); $next = $doc->getLine($index + 1); $this->removeExtraBlankLine($line, $next); } } private function removeExtraBlankLine(Line $current, Line $next): void { if (!$current->isTheEnd() && !$current->containsUsefulContent() && !$next->isTheEnd() && !$next->containsUsefulContent()) { $current->remove(); } } private function findNonBlankLine(DocBlock $doc, int $after): ?int { foreach ($doc->getLines() as $index => $line) { if ($index <= $after) { continue; } if ($line->containsATag() || $line->containsUsefulContent() || $line->isTheEnd()) { return $index; } } return null; } private function findFirstAnnotationOrEnd(DocBlock $doc): int { foreach ($doc->getLines() as $index => $line) { if ($line->containsATag()) { return $index; } } if (!isset($index)) { throw new \LogicException('PHPDoc has empty lines collection.'); } return $index; // no Annotation, return the last line } private function reverseFindLastUsefulContent(DocBlock $doc, int $from): ?int { for ($index = $from - 1; $index >= 0; --$index) { if ($doc->getLine($index)->containsUsefulContent()) { return $index; } } return 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/Phpdoc/AlignMultilineCommentFixer.php
src/Fixer/Phpdoc/AlignMultilineCommentFixer.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\Phpdoc; 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\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @phpstan-type _AutogeneratedInputConfiguration array{ * comment_type?: 'all_multiline'|'phpdocs_like'|'phpdocs_only', * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * comment_type: 'all_multiline'|'phpdocs_like'|'phpdocs_only', * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @author Filippo Tessarotto <zoeslam@gmail.com> * @author Julien Falque <julien.falque@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class AlignMultilineCommentFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; /** * @var null|non-empty-list<int> */ private ?array $tokenKinds = null; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Each line of multi-line DocComments must have an asterisk [PSR-5] and must be aligned with the first one.', [ new CodeSample( <<<'PHP' <?php /** * This is a DOC Comment with a line not prefixed with asterisk */ PHP, ), new CodeSample( <<<'PHP' <?php /* * This is a doc-like multiline comment */ PHP, ['comment_type' => 'phpdocs_like'], ), new CodeSample( <<<'PHP' <?php /* * This is a doc-like multiline comment with a line not prefixed with asterisk */ PHP, ['comment_type' => 'all_multiline'], ), ], ); } /** * {@inheritdoc} * * Must run before CommentToPhpdocFixer, GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocAnnotationWithoutDotFixer, PhpdocArrayTypeFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocListTypeFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReadonlyClassCommentToKeywordFixer, PhpdocReturnSelfReferenceFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagNoNamedArgumentsFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. * Must run after ArrayIndentationFixer. */ public function getPriority(): int { return 27; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound($this->tokenKinds); } protected function configurePostNormalisation(): void { $this->tokenKinds = [\T_DOC_COMMENT]; if ('phpdocs_only' !== $this->configuration['comment_type']) { $this->tokenKinds[] = \T_COMMENT; } } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $lineEnding = $this->whitespacesConfig->getLineEnding(); foreach ($tokens as $index => $token) { if (!$token->isGivenKind($this->tokenKinds)) { continue; } $whitespace = ''; $previousIndex = $index - 1; if ($tokens[$previousIndex]->isWhitespace()) { $whitespace = $tokens[$previousIndex]->getContent(); --$previousIndex; } if ($tokens[$previousIndex]->isGivenKind(\T_OPEN_TAG)) { $whitespace = Preg::replace('/\S/', '', $tokens[$previousIndex]->getContent()).$whitespace; } if (!Preg::match('/\R(\h*)$/', $whitespace, $matches)) { continue; } if ($token->isGivenKind(\T_COMMENT) && 'all_multiline' !== $this->configuration['comment_type'] && Preg::match('/\R(?:\R|\s*[^\s\*])/', $token->getContent())) { continue; } $indentation = $matches[1]; $lines = Preg::split('/\R/u', $token->getContent()); foreach ($lines as $lineNumber => $line) { if (0 === $lineNumber) { continue; } $line = ltrim($line); if ($token->isGivenKind(\T_COMMENT) && (!isset($line[0]) || '*' !== $line[0])) { continue; } if (!isset($line[0])) { $line = '*'; } elseif ('*' !== $line[0]) { $line = '* '.$line; } $lines[$lineNumber] = $indentation.' '.$line; } $tokens[$index] = new Token([$token->getId(), implode($lineEnding, $lines)]); } } protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('comment_type', 'Whether to fix PHPDoc comments only (`phpdocs_only`), any multi-line comment whose lines all start with an asterisk (`phpdocs_like`) or any multi-line comment (`all_multiline`).')) ->setAllowedValues(['phpdocs_only', 'phpdocs_like', 'all_multiline']) ->setDefault('phpdocs_only') ->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/ReturnNotation/NoUselessReturnFixer.php
src/Fixer/ReturnNotation/NoUselessReturnFixer.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\ReturnNotation; 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 NoUselessReturnFixer extends AbstractFixer { public function isCandidate(Tokens $tokens): bool { return $tokens->isAllTokenKindsFound([\T_FUNCTION, \T_RETURN]); } public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'There should not be an empty `return` statement at the end of a function.', [ new CodeSample( <<<'PHP' <?php function example($b) { if ($b) { return; } return; } PHP, ), ], ); } /** * {@inheritdoc} * * Must run before BlankLineBeforeStatementFixer, NoExtraBlankLinesFixer, NoWhitespaceInBlankLineFixer, SingleLineCommentStyleFixer, SingleLineEmptyBodyFixer. * Must run after NoEmptyStatementFixer, NoUnneededBracesFixer, NoUnneededCurlyBracesFixer, NoUselessElseFixer, SimplifiedNullReturnFixer. */ public function getPriority(): int { return -18; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(\T_FUNCTION)) { continue; } $index = $tokens->getNextTokenOfKind($index, [';', '{']); if ($tokens[$index]->equals('{')) { $this->fixFunction($tokens, $index, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index)); } } } /** * @param int $start Token index of the opening brace token of the function * @param int $end Token index of the closing brace token of the function */ private function fixFunction(Tokens $tokens, int $start, int $end): void { for ($index = $end; $index > $start; --$index) { if (!$tokens[$index]->isGivenKind(\T_RETURN)) { continue; } $nextAt = $tokens->getNextMeaningfulToken($index); if (!$tokens[$nextAt]->equals(';')) { continue; } if ($tokens->getNextMeaningfulToken($nextAt) !== $end) { continue; } $previous = $tokens->getPrevMeaningfulToken($index); if ($tokens[$previous]->equalsAny([[\T_ELSE], ')'])) { continue; } $tokens->clearTokenAndMergeSurroundingWhitespace($index); $tokens->clearTokenAndMergeSurroundingWhitespace($nextAt); } } }
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/ReturnNotation/ReturnAssignmentFixer.php
src/Fixer/ReturnNotation/ReturnAssignmentFixer.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\ReturnNotation; 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; /** * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ReturnAssignmentFixer extends AbstractFixer { private TokensAnalyzer $tokensAnalyzer; public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Local, dynamic and directly referenced variables should not be assigned and directly returned by a function or method.', [new CodeSample("<?php\nfunction a() {\n \$a = 1;\n return \$a;\n}\n")], ); } /** * {@inheritdoc} * * Must run before BlankLineBeforeStatementFixer. * Must run after NoEmptyStatementFixer, NoUnneededBracesFixer, NoUnneededCurlyBracesFixer. */ public function getPriority(): int { return -15; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAllTokenKindsFound([\T_FUNCTION, \T_RETURN, \T_VARIABLE]); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $tokenCount = \count($tokens); $this->tokensAnalyzer = new TokensAnalyzer($tokens); for ($index = 1; $index < $tokenCount; ++$index) { if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { continue; } $next = $tokens->getNextMeaningfulToken($index); if ($tokens[$next]->isGivenKind(CT::T_RETURN_REF)) { continue; } $functionOpenIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); if ($tokens[$functionOpenIndex]->equals(';')) { // abstract function $index = $functionOpenIndex - 1; continue; } $functionCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $functionOpenIndex); $totalTokensAdded = 0; do { $tokensAdded = $this->fixFunction( $tokens, $index, $functionOpenIndex, $functionCloseIndex, ); $functionCloseIndex += $tokensAdded; $totalTokensAdded += $tokensAdded; } while ($tokensAdded > 0); $index = $functionCloseIndex; $tokenCount += $totalTokensAdded; } } /** * @param int $functionIndex token index of T_FUNCTION * @param int $functionOpenIndex token index of the opening brace token of the function * @param int $functionCloseIndex token index of the closing brace token of the function * * @return int >= 0 number of tokens inserted into the Tokens collection */ private function fixFunction(Tokens $tokens, int $functionIndex, int $functionOpenIndex, int $functionCloseIndex): int { $inserted = 0; $candidates = []; $isRisky = false; if ($tokens[$tokens->getNextMeaningfulToken($functionIndex)]->isGivenKind(CT::T_RETURN_REF)) { $isRisky = true; } // go through the function declaration and check if references are passed // - check if it will be risky to fix return statements of this function for ($index = $functionIndex + 1; $index < $functionOpenIndex; ++$index) { if ($tokens[$index]->equals('&')) { $isRisky = true; break; } } // go through all the tokens of the body of the function: // - check if it will be risky to fix return statements of this function // - check nested functions; fix when found and update the upper limit + number of inserted token // - check for return statements that might be fixed (based on if fixing will be risky, which is only know after analyzing the whole function) for ($index = $functionOpenIndex + 1; $index < $functionCloseIndex; ++$index) { if ($tokens[$index]->isGivenKind(\T_FUNCTION)) { $nestedFunctionOpenIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); if ($tokens[$nestedFunctionOpenIndex]->equals(';')) { // abstract function $index = $nestedFunctionOpenIndex - 1; continue; } $nestedFunctionCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nestedFunctionOpenIndex); $tokensAdded = $this->fixFunction( $tokens, $index, $nestedFunctionOpenIndex, $nestedFunctionCloseIndex, ); $index = $nestedFunctionCloseIndex + $tokensAdded; $functionCloseIndex += $tokensAdded; $inserted += $tokensAdded; } if ($isRisky) { continue; // don't bother to look into anything else than nested functions as the current is risky already } if ($tokens[$index]->equals('&')) { $isRisky = true; continue; } if ($tokens[$index]->isGivenKind(\T_RETURN)) { $candidates[] = $index; continue; } // test if there is anything in the function body that might // change global state or indirect changes (like through references, eval, etc.) if ($tokens[$index]->isGivenKind([ CT::T_DYNAMIC_VAR_BRACE_OPEN, // "$h = ${$g};" case \T_EVAL, // "$c = eval('return $this;');" case \T_GLOBAL, \T_INCLUDE, // loading additional symbols we cannot analyse here \T_INCLUDE_ONCE, // " \T_REQUIRE, // " \T_REQUIRE_ONCE, // " ])) { $isRisky = true; continue; } if ($tokens[$index]->isGivenKind(\T_STATIC)) { $nextIndex = $tokens->getNextMeaningfulToken($index); if (!$tokens[$nextIndex]->isGivenKind(\T_FUNCTION)) { $isRisky = true; // "static $a" case continue; } } if ($tokens[$index]->equals('$')) { $nextIndex = $tokens->getNextMeaningfulToken($index); if ($tokens[$nextIndex]->isGivenKind(\T_VARIABLE)) { $isRisky = true; // "$$a" case continue; } } if ($this->tokensAnalyzer->isSuperGlobal($index)) { $isRisky = true; continue; } } if ($isRisky) { return $inserted; } // fix the candidates in reverse order when applicable for ($i = \count($candidates) - 1; $i >= 0; --$i) { $index = $candidates[$i]; // Check if returning only a variable (i.e. not the result of an expression, function call etc.) $returnVarIndex = $tokens->getNextMeaningfulToken($index); if (!$tokens[$returnVarIndex]->isGivenKind(\T_VARIABLE)) { continue; // example: "return 1;" } $endReturnVarIndex = $tokens->getNextMeaningfulToken($returnVarIndex); if (!$tokens[$endReturnVarIndex]->equalsAny([';', [\T_CLOSE_TAG]])) { continue; // example: "return $a + 1;" } // Check that the variable is assigned just before it is returned $assignVarEndIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$assignVarEndIndex]->equals(';')) { continue; // example: "? return $a;" } // Note: here we are @ "; return $a;" (or "; return $a ? >") while (true) { $prevMeaningful = $tokens->getPrevMeaningfulToken($assignVarEndIndex); if (!$tokens[$prevMeaningful]->equals(')')) { break; } $assignVarEndIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $prevMeaningful); } $assignVarOperatorIndex = $tokens->getPrevTokenOfKind( $assignVarEndIndex, ['=', ';', '{', '}', [\T_OPEN_TAG], [\T_OPEN_TAG_WITH_ECHO]], ); if ($tokens[$assignVarOperatorIndex]->equals('}')) { $startIndex = $this->isCloseBracePartOfDefinition($tokens, $assignVarOperatorIndex); // test for `anonymous class`, `lambda` and `match` if (null === $startIndex) { continue; } $assignVarOperatorIndex = $tokens->getPrevMeaningfulToken($startIndex); } if (!$tokens[$assignVarOperatorIndex]->equals('=')) { continue; } // Note: here we are @ "= [^;{<? ? >] ; return $a;" $assignVarIndex = $tokens->getPrevMeaningfulToken($assignVarOperatorIndex); if (!$tokens[$assignVarIndex]->equals($tokens[$returnVarIndex], false)) { continue; } // Note: here we are @ "$a = [^;{<? ? >] ; return $a;" $beforeAssignVarIndex = $tokens->getPrevMeaningfulToken($assignVarIndex); if (!$tokens[$beforeAssignVarIndex]->equalsAny([';', '{', '}'])) { continue; } // Check if there is a `catch` or `finally` block between the assignment and the return if ($this->isUsedInCatchOrFinally($tokens, $returnVarIndex, $functionOpenIndex, $functionCloseIndex)) { continue; } // Note: here we are @ "[;{}] $a = [^;{<? ? >] ; return $a;" $inserted += $this->simplifyReturnStatement( $tokens, $assignVarIndex, $assignVarOperatorIndex, $index, $endReturnVarIndex, ); } return $inserted; } /** * @return int >= 0 number of tokens inserted into the Tokens collection */ private function simplifyReturnStatement( Tokens $tokens, int $assignVarIndex, int $assignVarOperatorIndex, int $returnIndex, int $returnVarEndIndex ): int { $inserted = 0; $originalIndent = $tokens[$assignVarIndex - 1]->isWhitespace() ? $tokens[$assignVarIndex - 1]->getContent() : null; // remove the return statement if ($tokens[$returnVarEndIndex]->equals(';')) { // do not remove PHP close tags $tokens->clearTokenAndMergeSurroundingWhitespace($returnVarEndIndex); } for ($i = $returnIndex; $i <= $returnVarEndIndex - 1; ++$i) { $this->clearIfSave($tokens, $i); } // remove no longer needed indentation of the old/remove return statement if ($tokens[$returnIndex - 1]->isWhitespace()) { $content = $tokens[$returnIndex - 1]->getContent(); $fistLinebreakPos = strrpos($content, "\n"); $content = false === $fistLinebreakPos ? ' ' : substr($content, $fistLinebreakPos); $tokens[$returnIndex - 1] = new Token([\T_WHITESPACE, $content]); } // remove the variable and the assignment for ($i = $assignVarIndex; $i <= $assignVarOperatorIndex; ++$i) { $this->clearIfSave($tokens, $i); } // insert new return statement $tokens->insertAt($assignVarIndex, new Token([\T_RETURN, 'return'])); ++$inserted; // use the original indent of the var assignment for the new return statement if ( null !== $originalIndent && $tokens[$assignVarIndex - 1]->isWhitespace() && $originalIndent !== $tokens[$assignVarIndex - 1]->getContent() ) { $tokens[$assignVarIndex - 1] = new Token([\T_WHITESPACE, $originalIndent]); } // remove trailing space after the new return statement which might be added during the cleanup process $nextIndex = $tokens->getNonEmptySibling($assignVarIndex, 1); if (!$tokens[$nextIndex]->isWhitespace()) { $tokens->insertAt($nextIndex, new Token([\T_WHITESPACE, ' '])); ++$inserted; } return $inserted; } private function clearIfSave(Tokens $tokens, int $index): void { if ($tokens[$index]->isComment()) { return; } if ($tokens[$index]->isWhitespace() && $tokens[$tokens->getPrevNonWhitespace($index)]->isComment()) { return; } $tokens->clearTokenAndMergeSurroundingWhitespace($index); } /** * @param int $index open brace index * * @return null|int index of the first token of a definition (lambda, anonymous class or match) or `null` if not an anonymous */ private function isCloseBracePartOfDefinition(Tokens $tokens, int $index): ?int { $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); $candidateIndex = $this->isOpenBraceOfLambda($tokens, $index); if (null !== $candidateIndex) { return $candidateIndex; } $candidateIndex = $this->isOpenBraceOfAnonymousClass($tokens, $index); return $candidateIndex ?? $this->isOpenBraceOfMatch($tokens, $index); } /** * @param int $index open brace index * * @return null|int index of T_NEW of anonymous class or `null` if not an anonymous */ private function isOpenBraceOfAnonymousClass(Tokens $tokens, int $index): ?int { do { $index = $tokens->getPrevMeaningfulToken($index); } while ($tokens[$index]->equalsAny([',', [\T_STRING], [\T_IMPLEMENTS], [\T_EXTENDS], [\T_NS_SEPARATOR]])); if ($tokens[$index]->equals(')')) { // skip constructor braces and content within $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); $index = $tokens->getPrevMeaningfulToken($index); } if (!$tokens[$index]->isGivenKind(\T_CLASS) || !$this->tokensAnalyzer->isAnonymousClass($index)) { return null; } return $tokens->getPrevTokenOfKind($index, [[\T_NEW]]); } /** * @param int $index open brace index * * @return null|int index of T_FUNCTION or T_STATIC of lambda or `null` if not a lambda */ private function isOpenBraceOfLambda(Tokens $tokens, int $index): ?int { $index = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$index]->equals(')')) { return null; } $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); $index = $tokens->getPrevMeaningfulToken($index); if ($tokens[$index]->isGivenKind(CT::T_USE_LAMBDA)) { $index = $tokens->getPrevTokenOfKind($index, [')']); $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); $index = $tokens->getPrevMeaningfulToken($index); } if ($tokens[$index]->isGivenKind(CT::T_RETURN_REF)) { $index = $tokens->getPrevMeaningfulToken($index); } if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { return null; } $staticCandidate = $tokens->getPrevMeaningfulToken($index); return $tokens[$staticCandidate]->isGivenKind(\T_STATIC) ? $staticCandidate : $index; } /** * @param int $index open brace index * * @return null|int index of T_MATCH or `null` if not a `match` */ private function isOpenBraceOfMatch(Tokens $tokens, int $index): ?int { if (!$tokens->isTokenKindFound(FCT::T_MATCH)) { return null; } $index = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$index]->equals(')')) { return null; } $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); $index = $tokens->getPrevMeaningfulToken($index); return $tokens[$index]->isGivenKind(\T_MATCH) ? $index : null; } private function isUsedInCatchOrFinally(Tokens $tokens, int $returnVarIndex, int $functionOpenIndex, int $functionCloseIndex): bool { // Find try $tryIndex = $tokens->getPrevTokenOfKind($returnVarIndex, [[\T_TRY]]); if (null === $tryIndex || $tryIndex <= $functionOpenIndex) { return false; } $tryOpenIndex = $tokens->getNextTokenOfKind($tryIndex, ['{']); $tryCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $tryOpenIndex); // Find catch or finally $nextIndex = $tokens->getNextMeaningfulToken($tryCloseIndex); if (null === $nextIndex) { return false; } // Find catches while ($tokens[$nextIndex]->isGivenKind(\T_CATCH)) { $catchOpenIndex = $tokens->getNextTokenOfKind($nextIndex, ['{']); $catchCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $catchOpenIndex); if ($catchCloseIndex >= $functionCloseIndex) { return false; } $varIndex = $tokens->getNextTokenOfKind($catchOpenIndex, [$tokens[$returnVarIndex]]); // Check if the variable is used in the finally block if (null !== $varIndex && $varIndex < $catchCloseIndex) { return true; } $nextIndex = $tokens->getNextMeaningfulToken($catchCloseIndex); if (null === $nextIndex) { return false; } } if (!$tokens[$nextIndex]->isGivenKind(\T_FINALLY)) { return false; } $finallyIndex = $nextIndex; if ($finallyIndex >= $functionCloseIndex) { return false; } $finallyOpenIndex = $tokens->getNextTokenOfKind($finallyIndex, ['{']); $finallyCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $finallyOpenIndex); $varIndex = $tokens->getNextTokenOfKind($finallyOpenIndex, [$tokens[$returnVarIndex]]); // Check if the variable is used in the finally block if (null !== $varIndex && $varIndex < $finallyCloseIndex) { 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/ReturnNotation/SimplifiedNullReturnFixer.php
src/Fixer/ReturnNotation/SimplifiedNullReturnFixer.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\ReturnNotation; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\CT; 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 SimplifiedNullReturnFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'A return statement wishing to return `void` should not return `null`.', [ new CodeSample("<?php return null;\n"), new CodeSample( <<<'EOT' <?php function foo() { return null; } function bar(): int { return null; } function baz(): ?int { return null; } function xyz(): void { return null; } EOT, ), ], ); } /** * {@inheritdoc} * * Must run before NoUselessReturnFixer, VoidReturnFixer. */ public function getPriority(): int { return 16; } public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_RETURN); } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ($tokens as $index => $token) { if (!$token->isGivenKind(\T_RETURN)) { continue; } if ($this->needFixing($tokens, $index)) { $this->clear($tokens, $index); } } } /** * Clear the return statement located at a given index. */ private function clear(Tokens $tokens, int $index): void { while (!$tokens[++$index]->equalsAny([';', [\T_CLOSE_TAG]])) { if ($this->shouldClearToken($tokens, $index)) { $tokens->clearAt($index); } } } /** * Does the return statement located at a given index need fixing? */ private function needFixing(Tokens $tokens, int $index): bool { if ($this->isStrictOrNullableReturnTypeFunction($tokens, $index)) { return false; } $content = ''; while (!$tokens[$index]->equalsAny([';', [\T_CLOSE_TAG]])) { $index = $tokens->getNextMeaningfulToken($index); $content .= $tokens[$index]->getContent(); } $lastTokenContent = $tokens[$index]->getContent(); $content = substr($content, 0, -\strlen($lastTokenContent)); $content = ltrim($content, '('); $content = rtrim($content, ')'); return 'null' === strtolower($content); } /** * Is the return within a function with a non-void or nullable return type? * * @param int $returnIndex Current return token index */ private function isStrictOrNullableReturnTypeFunction(Tokens $tokens, int $returnIndex): bool { $functionIndex = $returnIndex; do { $functionIndex = $tokens->getPrevTokenOfKind($functionIndex, [[\T_FUNCTION]]); if (null === $functionIndex) { return false; } $openingCurlyBraceIndex = $tokens->getNextTokenOfKind($functionIndex, ['{']); $closingCurlyBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openingCurlyBraceIndex); } while ($closingCurlyBraceIndex < $returnIndex); $possibleVoidIndex = $tokens->getPrevMeaningfulToken($openingCurlyBraceIndex); $isStrictReturnType = $tokens[$possibleVoidIndex]->isGivenKind([\T_STRING, CT::T_ARRAY_TYPEHINT]) && 'void' !== $tokens[$possibleVoidIndex]->getContent(); $nullableTypeIndex = $tokens->getNextTokenOfKind($functionIndex, [[CT::T_NULLABLE_TYPE]]); $isNullableReturnType = null !== $nullableTypeIndex && $nullableTypeIndex < $openingCurlyBraceIndex; return $isStrictReturnType || $isNullableReturnType; } /** * Should we clear the specific token? * * We'll leave it alone if * - token is a comment * - token is whitespace that is immediately before a comment * - token is whitespace that is immediately before the PHP close tag * - token is whitespace that is immediately after a comment and before a semicolon */ private function shouldClearToken(Tokens $tokens, int $index): bool { $token = $tokens[$index]; if ($token->isComment()) { return false; } if (!$token->isWhitespace()) { return true; } if ( $tokens[$index + 1]->isComment() || $tokens[$index + 1]->isGivenKind(\T_CLOSE_TAG) || ($tokens[$index - 1]->isComment() && $tokens[$index + 1]->equals(';')) ) { 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/Strict/StrictComparisonFixer.php
src/Fixer/Strict/StrictComparisonFixer.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\Strict; 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 StrictComparisonFixer extends AbstractFixer { public function getDefinition(): FixerDefinitionInterface { return new FixerDefinition( 'Comparisons should be strict.', [new CodeSample("<?php\n\$a = 1== \$b;\n")], null, 'Changing comparisons to strict might change code behaviour.', ); } /** * {@inheritdoc} * * Must run before BinaryOperatorSpacesFixer, ModernizeStrposFixer. */ public function getPriority(): int { return 38; } public function isCandidate(Tokens $tokens): bool { return $tokens->isAnyTokenKindsFound([\T_IS_EQUAL, \T_IS_NOT_EQUAL]); } public function isRisky(): bool { return true; } protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ($tokens as $index => $token) { $newToken = [ \T_IS_EQUAL => [ 'id' => \T_IS_IDENTICAL, 'content' => '===', ], \T_IS_NOT_EQUAL => [ 'id' => \T_IS_NOT_IDENTICAL, 'content' => '!==', ], ][$token->getId()] ?? null; if (null !== $newToken) { $tokens[$index] = new Token([$newToken['id'], $newToken['content']]); } } } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false