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/Strict/StrictParamFixer.php | src/Fixer/Strict/StrictParamFixer.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\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\CT;
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 StrictParamFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Functions should be used with `$strict` param set to `true`.',
[new CodeSample("<?php\n\$a = array_keys(\$b);\n\$a = array_search(\$b, \$c);\n\$a = base64_decode(\$b);\n\$a = in_array(\$b, \$c);\n\$a = mb_detect_encoding(\$b, \$c);\n")],
'The functions "array_keys", "array_search", "base64_decode", "in_array" and "mb_detect_encoding" should be used with $strict param.',
'Risky when the fixed function is overridden or if the code relies on non-strict usage.',
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_STRING);
}
public function isRisky(): bool
{
return true;
}
/**
* {@inheritdoc}
*
* Must run before MethodArgumentSpaceFixer, NativeFunctionInvocationFixer.
*/
public function getPriority(): int
{
return 31;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$functionsAnalyzer = new FunctionsAnalyzer();
static $map = null;
if (null === $map) {
$trueToken = new Token([\T_STRING, 'true']);
$map = [
'array_keys' => [null, null, $trueToken],
'array_search' => [null, null, $trueToken],
'base64_decode' => [null, $trueToken],
'in_array' => [null, null, $trueToken],
'mb_detect_encoding' => [null, [new Token([\T_STRING, 'mb_detect_order']), new Token('('), new Token(')')], $trueToken],
];
}
for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
$token = $tokens[$index];
$nextIndex = $tokens->getNextMeaningfulToken($index);
if (null !== $nextIndex && !$tokens[$nextIndex]->equals('(')) {
continue;
}
$lowercaseContent = strtolower($token->getContent());
if (isset($map[$lowercaseContent]) && $functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) {
$this->fixFunction($tokens, $index, $map[$lowercaseContent]);
}
}
}
/**
* @param list<?Token> $functionParams
*/
private function fixFunction(Tokens $tokens, int $functionIndex, array $functionParams): void
{
$startBraceIndex = $tokens->getNextTokenOfKind($functionIndex, ['(']);
$endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startBraceIndex);
$paramsQuantity = 0;
$expectParam = true;
for ($index = $startBraceIndex + 1; $index < $endBraceIndex; ++$index) {
$token = $tokens[$index];
if ($expectParam && !$token->isWhitespace() && !$token->isComment()) {
++$paramsQuantity;
$expectParam = false;
}
if ($token->equals('(')) {
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
continue;
}
if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) {
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index);
continue;
}
if ($token->equals(',')) {
$expectParam = true;
continue;
}
}
$functionParamsQuantity = \count($functionParams);
if ($paramsQuantity === $functionParamsQuantity) {
return;
}
$tokensToInsert = [];
for ($i = $paramsQuantity; $i < $functionParamsQuantity; ++$i) {
// function call do not have all params that are required to set useStrict flag, exit from method!
if (null === $functionParams[$i]) {
return;
}
$tokensToInsert[] = new Token(',');
$tokensToInsert[] = new Token([\T_WHITESPACE, ' ']);
if (!\is_array($functionParams[$i])) {
$tokensToInsert[] = clone $functionParams[$i];
continue;
}
foreach ($functionParams[$i] as $param) {
$tokensToInsert[] = clone $param;
}
}
$beforeEndBraceIndex = $tokens->getPrevMeaningfulToken($endBraceIndex);
if ($tokens[$beforeEndBraceIndex]->equals(',')) {
array_shift($tokensToInsert);
$tokensToInsert[] = new Token(',');
}
$tokens->insertAt($beforeEndBraceIndex + 1, $tokensToInsert);
}
}
| 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/DeclareStrictTypesFixer.php | src/Fixer/Strict/DeclareStrictTypesFixer.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\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* preserve_existing_declaration?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* preserve_existing_declaration: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class DeclareStrictTypesFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Force strict types declaration in all files.',
[
new CodeSample(
"<?php\n",
),
new CodeSample(
"<?php\ndeclare(Strict_Types=0);\n",
['preserve_existing_declaration' => false],
),
new CodeSample(
"<?php\ndeclare(Strict_Types=0);\n",
['preserve_existing_declaration' => true],
),
],
null,
'Forcing strict types will stop non strict code from working.',
);
}
/**
* {@inheritdoc}
*
* Must run before BlankLineAfterOpeningTagFixer, DeclareEqualNormalizeFixer, HeaderCommentFixer.
*/
public function getPriority(): int
{
return 2;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isMonolithicPhp() && !$tokens->isTokenKindFound(\T_OPEN_TAG_WITH_ECHO);
}
public function isRisky(): bool
{
return true;
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('preserve_existing_declaration', 'Whether existing strict_types=? should be preserved and not overridden.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$openTagIndex = $tokens[0]->isGivenKind(\T_INLINE_HTML) ? 1 : 0;
$sequenceLocation = $this->getStrictTypesParentheses($tokens);
if (null === $sequenceLocation) {
$this->insertSequence($openTagIndex, $tokens); // declaration not found, insert one
return;
}
$this->fixStrictTypesCasingAndValue($tokens, $sequenceLocation);
}
/**
* @return null|array<int, Token>
*/
private function getStrictTypesParentheses(Tokens $tokens): ?array
{
foreach ($tokens->findGivenKind(\T_DECLARE) as $index => $token) {
$openParenthesis = $tokens->getNextMeaningfulToken($index);
$closeParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis);
$strictTypesSequence = $tokens->findSequence([[\T_STRING, 'strict_types'], '=', [\T_LNUMBER]], $openParenthesis, $closeParenthesis, false);
if (null === $strictTypesSequence) {
continue;
}
return $strictTypesSequence;
}
return null;
}
/**
* @param array<int, Token> $sequence
*/
private function fixStrictTypesCasingAndValue(Tokens $tokens, array $sequence): void
{
foreach ($sequence as $index => $token) {
if ($token->isGivenKind(\T_STRING)) {
$tokens[$index] = new Token([\T_STRING, strtolower($token->getContent())]);
continue;
}
if ($token->isGivenKind(\T_LNUMBER) && !$this->configuration['preserve_existing_declaration']) {
$tokens[$index] = new Token([\T_LNUMBER, '1']);
break;
}
}
}
private function insertSequence(int $openTagIndex, Tokens $tokens): void
{
$sequence = [
new Token([\T_DECLARE, 'declare']),
new Token('('),
new Token([\T_STRING, 'strict_types']),
new Token('='),
new Token([\T_LNUMBER, '1']),
new Token(')'),
new Token(';'),
];
$nextIndex = $openTagIndex + \count($sequence) + 1;
$tokens->insertAt($openTagIndex + 1, $sequence);
// transform "<?php" or "<?php\n" to "<?php " if needed
$content = $tokens[$openTagIndex]->getContent();
if (!str_contains($content, ' ') || str_contains($content, "\n")) {
$tokens[$openTagIndex] = new Token([$tokens[$openTagIndex]->getId(), trim($tokens[$openTagIndex]->getContent()).' ']);
}
if (\count($tokens) === $nextIndex) {
return; // no more tokens after sequence, single_blank_line_at_eof might add a line
}
$lineEnding = $this->whitespacesConfig->getLineEnding();
if ($tokens[$nextIndex]->isWhitespace()) {
$content = $tokens[$nextIndex]->getContent();
$tokens[$nextIndex] = new Token([\T_WHITESPACE, $lineEnding.ltrim($content, " \t")]);
} else {
$tokens->insertAt($nextIndex, new Token([\T_WHITESPACE, $lineEnding]));
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ClassUsage/DateTimeImmutableFixer.php | src/Fixer/ClassUsage/DateTimeImmutableFixer.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\ClassUsage;
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 Kuba Werłos <werlos@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class DateTimeImmutableFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Class `DateTimeImmutable` should be used instead of `DateTime`.',
[new CodeSample("<?php\nnew DateTime();\n")],
null,
'Risky when the code relies on modifying `DateTime` objects or if any of the `date_create*` functions are overridden.',
);
}
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();
$functionMap = [
'date_create' => 'date_create_immutable',
'date_create_from_format' => 'date_create_immutable_from_format',
];
$isInNamespace = false;
$isImported = false; // e.g. use DateTime;
for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) {
$token = $tokens[$index];
if ($token->isGivenKind(\T_NAMESPACE)) {
$isInNamespace = true;
continue;
}
if ($isInNamespace && $token->isGivenKind(\T_USE)) {
$nextIndex = $tokens->getNextMeaningfulToken($index);
if ('datetime' !== strtolower($tokens[$nextIndex]->getContent())) {
continue;
}
$nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex);
if ($tokens[$nextNextIndex]->equals(';')) {
$isImported = true;
}
$index = $nextNextIndex;
continue;
}
if (!$token->isGivenKind(\T_STRING)) {
continue;
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevIndex]->isGivenKind(\T_FUNCTION)) {
continue;
}
$lowercaseContent = strtolower($token->getContent());
if ('datetime' === $lowercaseContent) {
$this->fixClassUsage($tokens, $index, $isInNamespace, $isImported);
$limit = $tokens->count(); // update limit, as fixing class usage may insert new token
continue;
}
if (isset($functionMap[$lowercaseContent]) && $functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) {
$tokens[$index] = new Token([\T_STRING, $functionMap[$lowercaseContent]]);
}
}
}
private function fixClassUsage(Tokens $tokens, int $index, bool $isInNamespace, bool $isImported): void
{
$nextIndex = $tokens->getNextMeaningfulToken($index);
if ($tokens[$nextIndex]->isGivenKind(\T_DOUBLE_COLON)) {
$nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex);
if ($tokens[$nextNextIndex]->isGivenKind(\T_STRING)) {
$nextNextNextIndex = $tokens->getNextMeaningfulToken($nextNextIndex);
if (!$tokens[$nextNextNextIndex]->equals('(')) {
return;
}
}
}
$isUsedAlone = false; // e.g. new DateTime();
$isUsedWithLeadingBackslash = false; // e.g. new \DateTime();
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) {
$prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex);
if (!$tokens[$prevPrevIndex]->isGivenKind(\T_STRING)) {
$isUsedWithLeadingBackslash = true;
}
} elseif (!$tokens[$prevIndex]->isGivenKind(\T_DOUBLE_COLON) && !$tokens[$prevIndex]->isObjectOperator()) {
$isUsedAlone = true;
}
if ($isUsedWithLeadingBackslash || $isUsedAlone && ($isInNamespace && $isImported || !$isInNamespace)) {
$tokens[$index] = new Token([\T_STRING, \DateTimeImmutable::class]);
if ($isInNamespace && $isUsedAlone) {
$tokens->insertAt($index, new Token([\T_NS_SEPARATOR, '\\']));
}
}
}
}
| 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/PhpUnit/PhpUnitTestCaseStaticMethodCallsFixer.php | src/Fixer/PhpUnit/PhpUnitTestCaseStaticMethodCallsFixer.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\PhpUnit;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
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\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use PhpCsFixer\Utils;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* call_type?: 'self'|'static'|'this',
* methods?: array<string, string>,
* target?: '10.0'|'11.0'|'newest',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* call_type: 'self'|'static'|'this',
* methods: array<string, string>,
* target: '10.0'|'11.0'|'newest',
* }
*
* @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 PhpUnitTestCaseStaticMethodCallsFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @internal
*/
public const CALL_TYPE_THIS = 'this';
/**
* @internal
*/
public const CALL_TYPE_SELF = 'self';
/**
* @internal
*/
public const CALL_TYPE_STATIC = 'static';
/**
* @var array<string, true>
*/
private const METHODS = [
// Assert methods
'anything' => true,
'arrayHasKey' => true,
'assertArrayHasKey' => true,
'assertArrayIsEqualToArrayIgnoringListOfKeys' => true,
'assertArrayIsEqualToArrayOnlyConsideringListOfKeys' => true,
'assertArrayIsIdenticalToArrayIgnoringListOfKeys' => true,
'assertArrayIsIdenticalToArrayOnlyConsideringListOfKeys' => true,
'assertArrayNotHasKey' => true,
'assertArraySubset' => true,
'assertAttributeContains' => true,
'assertAttributeContainsOnly' => true,
'assertAttributeCount' => true,
'assertAttributeEmpty' => true,
'assertAttributeEquals' => true,
'assertAttributeGreaterThan' => true,
'assertAttributeGreaterThanOrEqual' => true,
'assertAttributeInstanceOf' => true,
'assertAttributeInternalType' => true,
'assertAttributeLessThan' => true,
'assertAttributeLessThanOrEqual' => true,
'assertAttributeNotContains' => true,
'assertAttributeNotContainsOnly' => true,
'assertAttributeNotCount' => true,
'assertAttributeNotEmpty' => true,
'assertAttributeNotEquals' => true,
'assertAttributeNotInstanceOf' => true,
'assertAttributeNotInternalType' => true,
'assertAttributeNotSame' => true,
'assertAttributeSame' => true,
'assertClassHasAttribute' => true,
'assertClassHasStaticAttribute' => true,
'assertClassNotHasAttribute' => true,
'assertClassNotHasStaticAttribute' => true,
'assertContains' => true,
'assertContainsEquals' => true,
'assertContainsNotOnlyArray' => true,
'assertContainsNotOnlyBool' => true,
'assertContainsNotOnlyCallable' => true,
'assertContainsNotOnlyClosedResource' => true,
'assertContainsNotOnlyFloat' => true,
'assertContainsNotOnlyInstancesOf' => true,
'assertContainsNotOnlyInt' => true,
'assertContainsNotOnlyIterable' => true,
'assertContainsNotOnlyNull' => true,
'assertContainsNotOnlyNumeric' => true,
'assertContainsNotOnlyObject' => true,
'assertContainsNotOnlyResource' => true,
'assertContainsNotOnlyScalar' => true,
'assertContainsNotOnlyString' => true,
'assertContainsOnly' => true,
'assertContainsOnlyArray' => true,
'assertContainsOnlyBool' => true,
'assertContainsOnlyCallable' => true,
'assertContainsOnlyClosedResource' => true,
'assertContainsOnlyFloat' => true,
'assertContainsOnlyInstancesOf' => true,
'assertContainsOnlyInt' => true,
'assertContainsOnlyIterable' => true,
'assertContainsOnlyNull' => true,
'assertContainsOnlyNumeric' => true,
'assertContainsOnlyObject' => true,
'assertContainsOnlyResource' => true,
'assertContainsOnlyScalar' => true,
'assertContainsOnlyString' => true,
'assertCount' => true,
'assertDirectoryDoesNotExist' => true,
'assertDirectoryExists' => true,
'assertDirectoryIsNotReadable' => true,
'assertDirectoryIsNotWritable' => true,
'assertDirectoryIsReadable' => true,
'assertDirectoryIsWritable' => true,
'assertDirectoryNotExists' => true,
'assertDirectoryNotIsReadable' => true,
'assertDirectoryNotIsWritable' => true,
'assertDoesNotMatchRegularExpression' => true,
'assertEmpty' => true,
'assertEquals' => true,
'assertEqualsCanonicalizing' => true,
'assertEqualsIgnoringCase' => true,
'assertEqualsWithDelta' => true,
'assertEqualXMLStructure' => true,
'assertFalse' => true,
'assertFileDoesNotExist' => true,
'assertFileEquals' => true,
'assertFileEqualsCanonicalizing' => true,
'assertFileEqualsIgnoringCase' => true,
'assertFileExists' => true,
'assertFileIsNotReadable' => true,
'assertFileIsNotWritable' => true,
'assertFileIsReadable' => true,
'assertFileIsWritable' => true,
'assertFileMatchesFormat' => true,
'assertFileMatchesFormatFile' => true,
'assertFileNotEquals' => true,
'assertFileNotEqualsCanonicalizing' => true,
'assertFileNotEqualsIgnoringCase' => true,
'assertFileNotExists' => true,
'assertFileNotIsReadable' => true,
'assertFileNotIsWritable' => true,
'assertFinite' => true,
'assertGreaterThan' => true,
'assertGreaterThanOrEqual' => true,
'assertInfinite' => true,
'assertInstanceOf' => true,
'assertInternalType' => true,
'assertIsArray' => true,
'assertIsBool' => true,
'assertIsCallable' => true,
'assertIsClosedResource' => true,
'assertIsFloat' => true,
'assertIsInt' => true,
'assertIsIterable' => true,
'assertIsList' => true,
'assertIsNotArray' => true,
'assertIsNotBool' => true,
'assertIsNotCallable' => true,
'assertIsNotClosedResource' => true,
'assertIsNotFloat' => true,
'assertIsNotInt' => true,
'assertIsNotIterable' => true,
'assertIsNotNumeric' => true,
'assertIsNotObject' => true,
'assertIsNotReadable' => true,
'assertIsNotResource' => true,
'assertIsNotScalar' => true,
'assertIsNotString' => true,
'assertIsNotWritable' => true,
'assertIsNumeric' => true,
'assertIsObject' => true,
'assertIsReadable' => true,
'assertIsResource' => true,
'assertIsScalar' => true,
'assertIsString' => true,
'assertIsWritable' => true,
'assertJson' => true,
'assertJsonFileEqualsJsonFile' => true,
'assertJsonFileNotEqualsJsonFile' => true,
'assertJsonStringEqualsJsonFile' => true,
'assertJsonStringEqualsJsonString' => true,
'assertJsonStringNotEqualsJsonFile' => true,
'assertJsonStringNotEqualsJsonString' => true,
'assertLessThan' => true,
'assertLessThanOrEqual' => true,
'assertMatchesRegularExpression' => true,
'assertNan' => true,
'assertNotContains' => true,
'assertNotContainsEquals' => true,
'assertNotContainsOnly' => true,
'assertNotCount' => true,
'assertNotEmpty' => true,
'assertNotEquals' => true,
'assertNotEqualsCanonicalizing' => true,
'assertNotEqualsIgnoringCase' => true,
'assertNotEqualsWithDelta' => true,
'assertNotFalse' => true,
'assertNotInstanceOf' => true,
'assertNotInternalType' => true,
'assertNotIsReadable' => true,
'assertNotIsWritable' => true,
'assertNotNull' => true,
'assertNotRegExp' => true,
'assertNotSame' => true,
'assertNotSameSize' => true,
'assertNotTrue' => true,
'assertNull' => true,
'assertObjectEquals' => true,
'assertObjectHasAttribute' => true,
'assertObjectHasProperty' => true,
'assertObjectNotEquals' => true,
'assertObjectNotHasAttribute' => true,
'assertObjectNotHasProperty' => true,
'assertRegExp' => true,
'assertSame' => true,
'assertSameSize' => true,
'assertStringContainsString' => true,
'assertStringContainsStringIgnoringCase' => true,
'assertStringContainsStringIgnoringLineEndings' => true,
'assertStringEndsNotWith' => true,
'assertStringEndsWith' => true,
'assertStringEqualsFile' => true,
'assertStringEqualsFileCanonicalizing' => true,
'assertStringEqualsFileIgnoringCase' => true,
'assertStringEqualsStringIgnoringLineEndings' => true,
'assertStringMatchesFormat' => true,
'assertStringMatchesFormatFile' => true,
'assertStringNotContainsString' => true,
'assertStringNotContainsStringIgnoringCase' => true,
'assertStringNotEqualsFile' => true,
'assertStringNotEqualsFileCanonicalizing' => true,
'assertStringNotEqualsFileIgnoringCase' => true,
'assertStringNotMatchesFormat' => true,
'assertStringNotMatchesFormatFile' => true,
'assertStringStartsNotWith' => true,
'assertStringStartsWith' => true,
'assertThat' => true,
'assertTrue' => true,
'assertXmlFileEqualsXmlFile' => true,
'assertXmlFileNotEqualsXmlFile' => true,
'assertXmlStringEqualsXmlFile' => true,
'assertXmlStringEqualsXmlString' => true,
'assertXmlStringNotEqualsXmlFile' => true,
'assertXmlStringNotEqualsXmlString' => true,
'attribute' => true,
'attributeEqualTo' => true,
'callback' => true,
'classHasAttribute' => true,
'classHasStaticAttribute' => true,
'contains' => true,
'containsEqual' => true,
'containsIdentical' => true,
'containsOnly' => true,
'containsOnlyArray' => true,
'containsOnlyBool' => true,
'containsOnlyCallable' => true,
'containsOnlyClosedResource' => true,
'containsOnlyFloat' => true,
'containsOnlyInstancesOf' => true,
'containsOnlyInt' => true,
'containsOnlyIterable' => true,
'containsOnlyNull' => true,
'containsOnlyNumeric' => true,
'containsOnlyObject' => true,
'containsOnlyResource' => true,
'containsOnlyScalar' => true,
'containsOnlyString' => true,
'countOf' => true,
'directoryExists' => true,
'equalTo' => true,
'equalToCanonicalizing' => true,
'equalToIgnoringCase' => true,
'equalToWithDelta' => true,
'fail' => true,
'fileExists' => true,
'getCount' => true,
'getObjectAttribute' => true,
'getStaticAttribute' => true,
'greaterThan' => true,
'greaterThanOrEqual' => true,
'identicalTo' => true,
'isArray' => true,
'isBool' => true,
'isCallable' => true,
'isClosedResource' => true,
'isEmpty' => true,
'isFalse' => true,
'isFinite' => true,
'isFloat' => true,
'isInfinite' => true,
'isInstanceOf' => true,
'isInt' => true,
'isIterable' => true,
'isJson' => true,
'isList' => true,
'isNan' => true,
'isNull' => true,
'isNumeric' => true,
'isObject' => true,
'isReadable' => true,
'isResource' => true,
'isScalar' => true,
'isString' => true,
'isTrue' => true,
'isType' => true,
'isWritable' => true,
'lessThan' => true,
'lessThanOrEqual' => true,
'logicalAnd' => true,
'logicalNot' => true,
'logicalOr' => true,
'logicalXor' => true,
'markTestIncomplete' => true,
'markTestSkipped' => true,
'matches' => true,
'matchesRegularExpression' => true,
'objectEquals' => true,
'objectHasAttribute' => true,
'readAttribute' => true,
'resetCount' => true,
'stringContains' => true,
'stringEndsWith' => true,
'stringEqualsStringIgnoringLineEndings' => true,
'stringStartsWith' => true,
// TestCase methods
'any' => true,
'at' => true,
'atLeast' => true,
'atLeastOnce' => true,
'atMost' => true,
'createStub' => true,
'createConfiguredStub' => true,
'createStubForIntersectionOfInterfaces' => true,
'exactly' => true,
'getStubBuilder' => true,
'never' => true,
'once' => true,
'onConsecutiveCalls' => true,
'returnArgument' => true,
'returnCallback' => true,
'returnSelf' => true,
'returnValue' => true,
'returnValueMap' => true,
'setUpBeforeClass' => true,
'tearDownAfterClass' => true,
'throwException' => true,
];
/**
* @var array<string, bool>
*/
private const ALLOWED_VALUES = [
self::CALL_TYPE_THIS => true,
self::CALL_TYPE_SELF => true,
self::CALL_TYPE_STATIC => true,
];
/**
* @var non-empty-array<string, non-empty-list<_PhpTokenArray>>
*/
private array $conversionMap = [
self::CALL_TYPE_THIS => [[\T_OBJECT_OPERATOR, '->'], [\T_VARIABLE, '$this']],
self::CALL_TYPE_SELF => [[\T_DOUBLE_COLON, '::'], [\T_STRING, 'self']],
self::CALL_TYPE_STATIC => [[\T_DOUBLE_COLON, '::'], [\T_STATIC, 'static']],
];
public function getDefinition(): FixerDefinitionInterface
{
$codeSample = <<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testMe()
{
$this->assertSame(1, 2);
self::assertSame(1, 2);
static::assertSame(1, 2);
static::assertTrue(false);
}
}
PHP;
return new FixerDefinition(
'Calls to `PHPUnit\Framework\TestCase` static methods must all be of the same type, either `$this->`, `self::` or `static::`.',
[
new CodeSample($codeSample),
new CodeSample($codeSample, ['call_type' => self::CALL_TYPE_THIS]),
new CodeSample($codeSample, ['methods' => ['assertTrue' => self::CALL_TYPE_THIS]]),
],
null,
'Risky when PHPUnit methods are overridden or not accessible, or when project has PHPUnit incompatibilities.',
);
}
/**
* {@inheritdoc}
*
* Must run before SelfStaticAccessorFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isRisky(): bool
{
return true;
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('call_type', 'The call type to use for referring to PHPUnit methods.'))
->setAllowedTypes(['string'])
->setAllowedValues(array_keys(self::ALLOWED_VALUES))
->setDefault(self::CALL_TYPE_STATIC)
->getOption(),
(new FixerOptionBuilder('methods', 'Dictionary of `method` => `call_type` values that differ from the default strategy.'))
->setAllowedTypes(['array<string, string>'])
->setAllowedValues([static function (array $option): bool {
foreach ($option as $method => $value) {
if (!isset(self::METHODS[$method])) {
throw new InvalidOptionsException(
\sprintf(
'Unexpected "methods" key, expected any of %s, got "%s".',
Utils::naturalLanguageJoin(array_keys(self::METHODS)),
\gettype($method).'#'.$method,
),
);
}
if (!isset(self::ALLOWED_VALUES[$value])) {
throw new InvalidOptionsException(
\sprintf(
'Unexpected value for method "%s", expected any of %s, got "%s".',
$method,
Utils::naturalLanguageJoin(array_keys(self::ALLOWED_VALUES)),
\is_object($value) ? \get_class($value) : (null === $value ? 'null' : \gettype($value).'#'.$value),
),
);
}
}
return true;
}])
->setDefault([])
->getOption(),
(new FixerOptionBuilder('target', 'Target version of PHPUnit.'))
->setAllowedTypes(['string'])
->setAllowedValues([
PhpUnitTargetVersion::VERSION_10_0,
PhpUnitTargetVersion::VERSION_11_0,
PhpUnitTargetVersion::VERSION_NEWEST,
])
->setDefault(Future::getV4OrV3(PhpUnitTargetVersion::VERSION_NEWEST, PhpUnitTargetVersion::VERSION_10_0))
->getOption(),
]);
}
protected function configurePostNormalisation(): void
{
$dynamicMethods = [];
if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_11_0)) {
$dynamicMethods = [
'any',
'atLeast',
'atLeastOnce',
'atMost',
'exactly',
'never',
'once',
'throwException',
];
}
if (PhpUnitTargetVersion::VERSION_11_0 === $this->configuration['target']) {
$dynamicMethods[] = 'onConsecutiveCalls';
$dynamicMethods[] = 'returnArgument';
$dynamicMethods[] = 'returnCallback';
$dynamicMethods[] = 'returnSelf';
$dynamicMethods[] = 'returnValue';
$dynamicMethods[] = 'returnValueMap';
}
foreach ($dynamicMethods as $method) {
if (isset($this->configuration['methods'][$method])) {
throw new InvalidFixerConfigurationException(
$this->getName(),
\sprintf('Configuration cannot contain method "%s" and target "%s", it is dynamic in that PHPUnit version.', $method, $this->configuration['target']),
);
}
$this->configuration['methods'][$method] = self::CALL_TYPE_THIS;
}
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$analyzer = new TokensAnalyzer($tokens);
for ($index = $startIndex; $index < $endIndex; ++$index) {
// skip anonymous classes
if ($tokens[$index]->isGivenKind(\T_CLASS)) {
$index = $this->findEndOfNextBlock($tokens, $index);
continue;
}
$callType = $this->configuration['call_type'];
if ($tokens[$index]->isGivenKind(\T_FUNCTION)) {
// skip lambda
if ($analyzer->isLambda($index)) {
$index = $this->findEndOfNextBlock($tokens, $index);
continue;
}
// do not change `self` to `this` in static methods
if (self::CALL_TYPE_THIS === $callType) {
$attributes = $analyzer->getMethodAttributes($index);
if (false !== $attributes['static']) {
$index = $this->findEndOfNextBlock($tokens, $index);
continue;
}
}
}
if (!$tokens[$index]->isGivenKind(\T_STRING) || !isset(self::METHODS[$tokens[$index]->getContent()])) {
continue;
}
$nextIndex = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$nextIndex]->equals('(')) {
$index = $nextIndex;
continue;
}
if ($tokens[$tokens->getNextMeaningfulToken($nextIndex)]->isGivenKind(CT::T_FIRST_CLASS_CALLABLE)) {
continue;
}
$methodName = $tokens[$index]->getContent();
if (isset($this->configuration['methods'][$methodName])) {
$callType = $this->configuration['methods'][$methodName];
}
$operatorIndex = $tokens->getPrevMeaningfulToken($index);
$referenceIndex = $tokens->getPrevMeaningfulToken($operatorIndex);
if (!$this->needsConversion($tokens, $index, $referenceIndex, $callType)) {
continue;
}
$tokens[$operatorIndex] = new Token($this->conversionMap[$callType][0]);
$tokens[$referenceIndex] = new Token($this->conversionMap[$callType][1]);
}
}
private function needsConversion(Tokens $tokens, int $index, int $referenceIndex, string $callType): bool
{
$functionsAnalyzer = new FunctionsAnalyzer();
return $functionsAnalyzer->isTheSameClassCall($tokens, $index)
&& !$tokens[$referenceIndex]->equals($this->conversionMap[$callType][1], false);
}
private function findEndOfNextBlock(Tokens $tokens, int $index): int
{
$nextIndex = $tokens->getNextTokenOfKind($index, [';', '{']);
return $tokens[$nextIndex]->equals('{')
? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nextIndex)
: $nextIndex;
}
}
| 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/PhpUnit/PhpUnitDedicateAssertInternalTypeFixer.php | src/Fixer/PhpUnit/PhpUnitDedicateAssertInternalTypeFixer.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\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
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{
* target?: '7.5'|'newest',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* target: '7.5'|'newest',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Filippo Tessarotto <zoeslam@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class PhpUnitDedicateAssertInternalTypeFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @var array<string, string>
*/
private array $typeToDedicatedAssertMap = [
'array' => 'assertIsArray',
'boolean' => 'assertIsBool',
'bool' => 'assertIsBool',
'double' => 'assertIsFloat',
'float' => 'assertIsFloat',
'integer' => 'assertIsInt',
'int' => 'assertIsInt',
'null' => 'assertNull',
'numeric' => 'assertIsNumeric',
'object' => 'assertIsObject',
'real' => 'assertIsFloat',
'resource' => 'assertIsResource',
'string' => 'assertIsString',
'scalar' => 'assertIsScalar',
'callable' => 'assertIsCallable',
'iterable' => 'assertIsIterable',
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'PHPUnit assertions like `assertIsArray` should be used over `assertInternalType`.',
[
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit\Framework\TestCase
{
public function testMe()
{
$this->assertInternalType("array", $var);
$this->assertInternalType("boolean", $var);
}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit\Framework\TestCase
{
public function testMe()
{
$this->assertInternalType("array", $var);
$this->assertInternalType("boolean", $var);
}
}
PHP,
['target' => PhpUnitTargetVersion::VERSION_7_5],
),
],
null,
'Risky when PHPUnit methods are overridden or when project has PHPUnit incompatibilities.',
);
}
public function isRisky(): bool
{
return true;
}
/**
* {@inheritdoc}
*
* Must run after NoBinaryStringFixer, NoUselessConcatOperatorFixer, PhpUnitDedicateAssertFixer.
*/
public function getPriority(): int
{
return -16;
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('target', 'Target version of PHPUnit.'))
->setAllowedTypes(['string'])
->setAllowedValues([PhpUnitTargetVersion::VERSION_7_5, PhpUnitTargetVersion::VERSION_NEWEST])
->setDefault(PhpUnitTargetVersion::VERSION_NEWEST)
->getOption(),
]);
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$anonymousClassIndices = [];
$tokenAnalyzer = new TokensAnalyzer($tokens);
for ($index = $startIndex; $index < $endIndex; ++$index) {
if (!$tokens[$index]->isGivenKind(\T_CLASS) || !$tokenAnalyzer->isAnonymousClass($index)) {
continue;
}
$openingBraceIndex = $tokens->getNextTokenOfKind($index, ['{']);
$closingBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openingBraceIndex);
$anonymousClassIndices[$closingBraceIndex] = $openingBraceIndex;
}
for ($index = $endIndex - 1; $index > $startIndex; --$index) {
if (isset($anonymousClassIndices[$index])) {
$index = $anonymousClassIndices[$index];
continue;
}
if (!$tokens[$index]->isGivenKind(\T_STRING)) {
continue;
}
$functionName = strtolower($tokens[$index]->getContent());
if ('assertinternaltype' !== $functionName && 'assertnotinternaltype' !== $functionName) {
continue;
}
$bracketTokenIndex = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$bracketTokenIndex]->equals('(')) {
continue;
}
$expectedTypeTokenIndex = $tokens->getNextMeaningfulToken($bracketTokenIndex);
$expectedTypeToken = $tokens[$expectedTypeTokenIndex];
if (!$expectedTypeToken->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) {
continue;
}
$expectedType = trim($expectedTypeToken->getContent(), '\'"');
if (!isset($this->typeToDedicatedAssertMap[$expectedType])) {
continue;
}
$commaTokenIndex = $tokens->getNextMeaningfulToken($expectedTypeTokenIndex);
if (!$tokens[$commaTokenIndex]->equals(',')) {
continue;
}
$newAssertion = $this->typeToDedicatedAssertMap[$expectedType];
if ('assertnotinternaltype' === $functionName) {
$newAssertion = str_replace('Is', 'IsNot', $newAssertion);
$newAssertion = str_replace('Null', 'NotNull', $newAssertion);
}
$nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($commaTokenIndex);
$tokens->overrideRange($index, $nextMeaningfulTokenIndex - 1, [
new Token([\T_STRING, $newAssertion]),
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/PhpUnit/PhpUnitStrictFixer.php | src/Fixer/PhpUnit/PhpUnitStrictFixer.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\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
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\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* assertions?: list<'assertAttributeEquals'|'assertAttributeNotEquals'|'assertEquals'|'assertNotEquals'>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* assertions: list<'assertAttributeEquals'|'assertAttributeNotEquals'|'assertEquals'|'assertNotEquals'>,
* }
*
* @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 PhpUnitStrictFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @var array<string, string>
*/
private const ASSERTION_MAP = [
'assertAttributeEquals' => 'assertAttributeSame',
'assertAttributeNotEquals' => 'assertAttributeNotSame',
'assertEquals' => 'assertSame',
'assertNotEquals' => 'assertNotSame',
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'PHPUnit methods like `assertSame` should be used instead of `assertEquals`.',
[
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testSomeTest()
{
$this->assertAttributeEquals(a(), b());
$this->assertAttributeNotEquals(a(), b());
$this->assertEquals(a(), b());
$this->assertNotEquals(a(), b());
}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testSomeTest()
{
$this->assertAttributeEquals(a(), b());
$this->assertAttributeNotEquals(a(), b());
$this->assertEquals(a(), b());
$this->assertNotEquals(a(), b());
}
}
PHP,
['assertions' => ['assertEquals']],
),
],
null,
'Risky when any of the functions are overridden or when testing object equality.',
);
}
public function isRisky(): bool
{
return true;
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$argumentsAnalyzer = new ArgumentsAnalyzer();
$functionsAnalyzer = new FunctionsAnalyzer();
foreach ($this->configuration['assertions'] as $methodBefore) {
$methodAfter = self::ASSERTION_MAP[$methodBefore];
for ($index = $startIndex; $index < $endIndex; ++$index) {
$methodIndex = $tokens->getNextTokenOfKind($index, [[\T_STRING, $methodBefore]]);
if (null === $methodIndex) {
break;
}
if (!$functionsAnalyzer->isTheSameClassCall($tokens, $methodIndex)) {
continue;
}
$openingParenthesisIndex = $tokens->getNextMeaningfulToken($methodIndex);
$argumentsCount = $argumentsAnalyzer->countArguments(
$tokens,
$openingParenthesisIndex,
$tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openingParenthesisIndex),
);
if (2 === $argumentsCount || 3 === $argumentsCount) {
$tokens[$methodIndex] = new Token([\T_STRING, $methodAfter]);
}
$index = $methodIndex;
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('assertions', 'List of assertion methods to fix.'))
->setAllowedTypes(['string[]'])
->setAllowedValues([new AllowedValueSubset(array_keys(self::ASSERTION_MAP))])
->setDefault([
'assertAttributeEquals',
'assertAttributeNotEquals',
'assertEquals',
'assertNotEquals',
])
->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/PhpUnit/PhpUnitMethodCasingFixer.php | src/Fixer/PhpUnit/PhpUnitMethodCasingFixer.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\PhpUnit;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\DocBlock\Line;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use PhpCsFixer\Utils;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* case?: 'camel_case'|'snake_case',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* case: 'camel_case'|'snake_case',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Filippo Tessarotto <zoeslam@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class PhpUnitMethodCasingFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @internal
*/
public const CAMEL_CASE = 'camel_case';
/**
* @internal
*/
public const SNAKE_CASE = 'snake_case';
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Enforce camel (or snake) case for PHPUnit test methods, following configuration.',
[
new CodeSample(
<<<'PHP'
<?php
class MyTest extends \PhpUnit\FrameWork\TestCase
{
public function test_my_code() {}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
class MyTest extends \PhpUnit\FrameWork\TestCase
{
public function testMyCode() {}
}
PHP,
['case' => self::SNAKE_CASE],
),
new VersionSpecificCodeSample(
<<<'PHP'
<?php
use \PHPUnit\Framework\Attributes\Test;
class MyTest extends \PhpUnit\FrameWork\TestCase
{
#[PHPUnit\Framework\Attributes\Test]
public function test_my_code() {}
}
PHP,
new VersionSpecification(8_00_00),
),
new VersionSpecificCodeSample(
<<<'PHP'
<?php
use \PHPUnit\Framework\Attributes\Test;
class MyTest extends \PhpUnit\FrameWork\TestCase
{
#[PHPUnit\Framework\Attributes\Test]
public function testMyCode() {}
}
PHP,
new VersionSpecification(8_00_00),
['case' => self::SNAKE_CASE],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after PhpUnitTestAnnotationFixer.
*/
public function getPriority(): int
{
return 0;
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('case', 'Apply camel or snake case to test methods.'))
->setAllowedValues([self::CAMEL_CASE, self::SNAKE_CASE])
->setDefault(self::CAMEL_CASE)
->getOption(),
]);
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$existingFunctionNamesLowercase = [];
for ($index = $endIndex - 1; $index > $startIndex; --$index) {
if (!$this->isMethod($tokens, $index)) {
continue;
}
$functionNameIndex = $tokens->getNextMeaningfulToken($index);
$existingFunctionNamesLowercase[strtolower($tokens[$functionNameIndex]->getContent())] = null;
}
unset($index);
for ($index = $endIndex - 1; $index > $startIndex; --$index) {
if (!$this->isTestMethod($tokens, $index)) {
continue;
}
$functionNameIndex = $tokens->getNextMeaningfulToken($index);
$functionName = $tokens[$functionNameIndex]->getContent();
$functionNameLowercase = strtolower($functionName);
$newFunctionName = $this->updateMethodCasing($functionName);
$newFunctionNameLowercase = strtolower($newFunctionName);
if (
\array_key_exists($newFunctionNameLowercase, $existingFunctionNamesLowercase)
&& $functionNameLowercase !== $newFunctionNameLowercase
) {
continue;
}
$existingFunctionNamesLowercase[$newFunctionNameLowercase] = null;
if ($newFunctionName !== $functionName) {
$tokens[$functionNameIndex] = new Token([\T_STRING, $newFunctionName]);
}
$docBlockIndex = $this->getDocBlockIndex($tokens, $index);
if ($tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT)) {
$this->updateDocBlock($tokens, $docBlockIndex);
}
}
}
private function updateMethodCasing(string $functionName): string
{
$parts = explode('::', $functionName);
$functionNamePart = array_pop($parts);
if (self::CAMEL_CASE === $this->configuration['case']) {
$newFunctionNamePart = $functionNamePart;
$newFunctionNamePart = ucwords($newFunctionNamePart, '_');
$newFunctionNamePart = str_replace('_', '', $newFunctionNamePart);
$newFunctionNamePart = lcfirst($newFunctionNamePart);
} else {
$newFunctionNamePart = Utils::camelCaseToUnderscore($functionNamePart);
}
$parts[] = $newFunctionNamePart;
return implode('::', $parts);
}
private function isTestMethod(Tokens $tokens, int $index): bool
{
// Check if we are dealing with a (non-abstract, non-lambda) function
if (!$this->isMethod($tokens, $index)) {
return false;
}
// if the function name starts with test it's a test
$functionNameIndex = $tokens->getNextMeaningfulToken($index);
$functionName = $tokens[$functionNameIndex]->getContent();
if (str_starts_with($functionName, 'test')) {
return true;
}
if ($this->isTestAttributePresent($tokens, $index)) {
return true;
}
$docBlockIndex = $this->getDocBlockIndex($tokens, $index);
return
$tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT) // If the function doesn't have test in its name, and no doc block, it's not a test
&& str_contains($tokens[$docBlockIndex]->getContent(), '@test');
}
private function isMethod(Tokens $tokens, int $index): bool
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
return $tokens[$index]->isGivenKind(\T_FUNCTION) && !$tokensAnalyzer->isLambda($index);
}
private function updateDocBlock(Tokens $tokens, int $docBlockIndex): void
{
$doc = new DocBlock($tokens[$docBlockIndex]->getContent());
$lines = $doc->getLines();
$docBlockNeedsUpdate = false;
for ($inc = 0; $inc < \count($lines); ++$inc) {
$lineContent = $lines[$inc]->getContent();
if (!str_contains($lineContent, '@depends')) {
continue;
}
$newLineContent = Preg::replaceCallback('/(@depends\s+)(.+)(\b)/', fn (array $matches): string => \sprintf(
'%s%s%s',
$matches[1],
$this->updateMethodCasing($matches[2]),
$matches[3],
), $lineContent);
if ($newLineContent !== $lineContent) {
$lines[$inc] = new Line($newLineContent);
$docBlockNeedsUpdate = true;
}
}
if ($docBlockNeedsUpdate) {
$lines = implode('', $lines);
$tokens[$docBlockIndex] = new Token([\T_DOC_COMMENT, $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/PhpUnit/PhpUnitTestClassRequiresCoversFixer.php | src/Fixer/PhpUnit/PhpUnitTestClassRequiresCoversFixer.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\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class PhpUnitTestClassRequiresCoversFixer extends AbstractPhpUnitFixer implements WhitespacesAwareFixerInterface
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Adds a default `@coversNothing` annotation to PHPUnit test classes that have no `@covers*` annotation.',
[
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testSomeTest()
{
$this->assertSame(a(), b());
}
}
PHP,
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before PhpUnitAttributesFixer, PhpdocSeparationFixer.
*/
public function getPriority(): int
{
return 9;
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$classIndex = $tokens->getPrevTokenOfKind($startIndex, [[\T_CLASS]]);
$tokensAnalyzer = new TokensAnalyzer($tokens);
$modifiers = $tokensAnalyzer->getClassyModifiers($classIndex);
if (isset($modifiers['abstract'])) {
return; // don't add `@covers` annotation for abstract base classes
}
$this->ensureIsDocBlockWithAnnotation(
$tokens,
$classIndex,
'coversNothing',
[
'covers',
'coversDefaultClass',
'coversNothing',
],
[
'phpunit\framework\attributes\coversclass',
'phpunit\framework\attributes\coversnothing',
'phpunit\framework\attributes\coversmethod',
'phpunit\framework\attributes\coversfunction',
'phpunit\framework\attributes\coverstrait',
],
);
}
}
| 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/PhpUnit/PhpUnitExpectationFixer.php | src/Fixer/PhpUnit/PhpUnitExpectationFixer.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\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
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\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* target?: '5.2'|'5.6'|'8.4'|'newest',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* target: '5.2'|'5.6'|'8.4'|'newest',
* }
*
* @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 PhpUnitExpectationFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @var array<string, string>
*/
private array $methodMap = [];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Usages of `->setExpectedException*` methods MUST be replaced by `->expectException*` methods.',
[
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testFoo()
{
$this->setExpectedException("RuntimeException", "Msg", 123);
foo();
}
public function testBar()
{
$this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123);
bar();
}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testFoo()
{
$this->setExpectedException("RuntimeException", null, 123);
foo();
}
public function testBar()
{
$this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123);
bar();
}
}
PHP,
['target' => PhpUnitTargetVersion::VERSION_8_4],
),
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testFoo()
{
$this->setExpectedException("RuntimeException", null, 123);
foo();
}
public function testBar()
{
$this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123);
bar();
}
}
PHP,
['target' => PhpUnitTargetVersion::VERSION_5_6],
),
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testFoo()
{
$this->setExpectedException("RuntimeException", "Msg", 123);
foo();
}
public function testBar()
{
$this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123);
bar();
}
}
PHP,
['target' => PhpUnitTargetVersion::VERSION_5_2],
),
],
null,
'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.',
);
}
/**
* {@inheritdoc}
*
* Must run after PhpUnitNoExpectationAnnotationFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isRisky(): bool
{
return true;
}
protected function configurePostNormalisation(): void
{
$this->methodMap = [
'setExpectedException' => 'expectExceptionMessage',
];
if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_6)) {
$this->methodMap['setExpectedExceptionRegExp'] = 'expectExceptionMessageRegExp';
}
if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_8_4)) {
$this->methodMap['setExpectedExceptionRegExp'] = 'expectExceptionMessageMatches';
$this->methodMap['expectExceptionMessageRegExp'] = 'expectExceptionMessageMatches';
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('target', 'Target version of PHPUnit.'))
->setAllowedTypes(['string'])
->setAllowedValues([PhpUnitTargetVersion::VERSION_5_2, PhpUnitTargetVersion::VERSION_5_6, PhpUnitTargetVersion::VERSION_8_4, PhpUnitTargetVersion::VERSION_NEWEST])
->setDefault(PhpUnitTargetVersion::VERSION_NEWEST)
->getOption(),
]);
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
foreach (Token::getObjectOperatorKinds() as $objectOperator) {
$this->applyPhpUnitClassFixWithObjectOperator($tokens, $startIndex, $endIndex, $objectOperator);
}
}
private function applyPhpUnitClassFixWithObjectOperator(Tokens $tokens, int $startIndex, int $endIndex, int $objectOperator): void
{
$argumentsAnalyzer = new ArgumentsAnalyzer();
$oldMethodSequence = [
[\T_VARIABLE, '$this'],
[$objectOperator],
[\T_STRING],
];
for ($index = $startIndex; $startIndex < $endIndex; ++$index) {
$match = $tokens->findSequence($oldMethodSequence, $index);
if (null === $match) {
return;
}
[$thisIndex, , $index] = array_keys($match);
if (!isset($this->methodMap[$tokens[$index]->getContent()])) {
continue;
}
$openIndex = $tokens->getNextTokenOfKind($index, ['(']);
$closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex);
$commaIndex = $tokens->getPrevMeaningfulToken($closeIndex);
if ($tokens[$commaIndex]->equals(',')) {
$tokens->removeTrailingWhitespace($commaIndex);
$tokens->clearAt($commaIndex);
}
$arguments = $argumentsAnalyzer->getArguments($tokens, $openIndex, $closeIndex);
$argumentsCnt = \count($arguments);
$argumentsReplacements = ['expectException', $this->methodMap[$tokens[$index]->getContent()], 'expectExceptionCode'];
$indent = $this->whitespacesConfig->getLineEnding().WhitespacesAnalyzer::detectIndent($tokens, $thisIndex);
$isMultilineWhitespace = false;
for ($cnt = $argumentsCnt - 1; $cnt >= 1; --$cnt) {
$argStart = array_keys($arguments)[$cnt];
$argBefore = $tokens->getPrevMeaningfulToken($argStart);
if (!isset($argumentsReplacements[$cnt])) {
throw new \LogicException(\sprintf('Unexpected index %d to find replacement method.', $cnt));
}
if ('expectExceptionMessage' === $argumentsReplacements[$cnt]) {
$paramIndicatorIndex = $tokens->getNextMeaningfulToken($argBefore);
$afterParamIndicatorIndex = $tokens->getNextMeaningfulToken($paramIndicatorIndex);
if (
$tokens[$paramIndicatorIndex]->equals([\T_STRING, 'null'], false)
&& $tokens[$afterParamIndicatorIndex]->equals(')')
) {
if ($tokens[$argBefore + 1]->isWhitespace()) {
$tokens->clearTokenAndMergeSurroundingWhitespace($argBefore + 1);
}
$tokens->clearTokenAndMergeSurroundingWhitespace($argBefore);
$tokens->clearTokenAndMergeSurroundingWhitespace($paramIndicatorIndex);
continue;
}
}
$isMultilineWhitespace = $isMultilineWhitespace || ($tokens[$argStart]->isWhitespace() && !$tokens[$argStart]->isWhitespace(" \t"));
$tokensOverrideArgStart = [
new Token([\T_WHITESPACE, $indent]),
new Token([\T_VARIABLE, '$this']),
new Token([\T_OBJECT_OPERATOR, '->']),
new Token([\T_STRING, $argumentsReplacements[$cnt]]),
new Token('('),
];
$tokensOverrideArgBefore = [
new Token(')'),
new Token(';'),
];
if ($isMultilineWhitespace) {
$tokensOverrideArgStart[] = new Token([\T_WHITESPACE, $indent.$this->whitespacesConfig->getIndent()]);
array_unshift($tokensOverrideArgBefore, new Token([\T_WHITESPACE, $indent]));
}
if ($tokens[$argStart]->isWhitespace()) {
$tokens->overrideRange($argStart, $argStart, $tokensOverrideArgStart);
} else {
$tokens->insertAt($argStart, $tokensOverrideArgStart);
}
$tokens->overrideRange($argBefore, $argBefore, $tokensOverrideArgBefore);
}
$methodName = 'expectException';
if ('expectExceptionMessageRegExp' === $tokens[$index]->getContent()) {
$methodName = $this->methodMap[$tokens[$index]->getContent()];
}
$tokens[$index] = new Token([\T_STRING, $methodName]);
}
}
}
| 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/PhpUnit/PhpUnitTestAnnotationFixer.php | src/Fixer/PhpUnit/PhpUnitTestAnnotationFixer.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\PhpUnit;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\DocBlock\Line;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* style?: 'annotation'|'prefix',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* style: 'annotation'|'prefix',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Gert de Pagter
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class PhpUnitTestAnnotationFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function isRisky(): bool
{
return true;
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Adds or removes @test annotations from tests, following configuration.',
[
new CodeSample(
<<<'PHP'
<?php
class Test extends \PhpUnit\FrameWork\TestCase
{
/**
* @test
*/
public function itDoesSomething() {} }
PHP.$this->whitespacesConfig->getLineEnding(),
),
new CodeSample(
<<<'PHP'
<?php
class Test extends \PhpUnit\FrameWork\TestCase
{
public function testItDoesSomething() {}}
PHP.$this->whitespacesConfig->getLineEnding(),
['style' => 'annotation'],
),
],
null,
'This fixer may change the name of your tests, and could cause incompatibility with'
.' abstract classes or interfaces.',
);
}
/**
* {@inheritdoc}
*
* Must run before NoEmptyPhpdocFixer, PhpUnitMethodCasingFixer, PhpdocTrimFixer.
*/
public function getPriority(): int
{
return 10;
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
if ('annotation' === $this->configuration['style']) {
$this->applyTestAnnotation($tokens, $startIndex, $endIndex);
} else {
$this->applyTestPrefix($tokens, $startIndex, $endIndex);
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('style', 'Whether to use the @test annotation or not.'))
->setAllowedValues(['prefix', 'annotation'])
->setDefault('prefix')
->getOption(),
]);
}
private function applyTestAnnotation(Tokens $tokens, int $startIndex, int $endIndex): void
{
for ($i = $endIndex - 1; $i > $startIndex; --$i) {
if (!$this->isTestMethod($tokens, $i)) {
continue;
}
$functionNameIndex = $tokens->getNextMeaningfulToken($i);
$functionName = $tokens[$functionNameIndex]->getContent();
if ($this->hasTestPrefix($functionName) && !$this->hasProperTestAnnotation($tokens, $i)) {
$newFunctionName = $this->removeTestPrefix($functionName);
$tokens[$functionNameIndex] = new Token([\T_STRING, $newFunctionName]);
}
$docBlockIndex = $this->getDocBlockIndex($tokens, $i);
if ($tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT)) {
$lines = $this->updateDocBlock($tokens, $docBlockIndex);
$lines = $this->addTestAnnotation($lines, $tokens, $docBlockIndex);
$lines = implode('', $lines);
$tokens[$docBlockIndex] = new Token([\T_DOC_COMMENT, $lines]);
} else {
// Create a new docblock if it didn't have one before;
$this->createDocBlock($tokens, $docBlockIndex, 'test');
}
}
}
private function applyTestPrefix(Tokens $tokens, int $startIndex, int $endIndex): void
{
for ($i = $endIndex - 1; $i > $startIndex; --$i) {
// We explicitly check again if the function has a doc block to save some time.
if (!$this->isTestMethod($tokens, $i)) {
continue;
}
$docBlockIndex = $this->getDocBlockIndex($tokens, $i);
if (!$tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT)) {
continue;
}
$lines = $this->updateDocBlock($tokens, $docBlockIndex);
$lines = implode('', $lines);
$tokens[$docBlockIndex] = new Token([\T_DOC_COMMENT, $lines]);
$functionNameIndex = $tokens->getNextMeaningfulToken($i);
$functionName = $tokens[$functionNameIndex]->getContent();
if ($this->hasTestPrefix($functionName)) {
continue;
}
$newFunctionName = $this->addTestPrefix($functionName);
$tokens[$functionNameIndex] = new Token([\T_STRING, $newFunctionName]);
}
}
private function isTestMethod(Tokens $tokens, int $index): bool
{
// Check if we are dealing with a (non-abstract, non-lambda) function
if (!$this->isMethod($tokens, $index)) {
return false;
}
// if the function name starts with test it is a test
$functionNameIndex = $tokens->getNextMeaningfulToken($index);
$functionName = $tokens[$functionNameIndex]->getContent();
if ($this->hasTestPrefix($functionName)) {
return true;
}
$docBlockIndex = $this->getDocBlockIndex($tokens, $index);
// If the function doesn't have test in its name, and no doc block, it is not a test
return
$tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT)
&& str_contains($tokens[$docBlockIndex]->getContent(), '@test');
}
private function isMethod(Tokens $tokens, int $index): bool
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
return $tokens[$index]->isGivenKind(\T_FUNCTION) && !$tokensAnalyzer->isLambda($index);
}
private function hasTestPrefix(string $functionName): bool
{
return str_starts_with($functionName, 'test');
}
private function hasProperTestAnnotation(Tokens $tokens, int $index): bool
{
$docBlockIndex = $this->getDocBlockIndex($tokens, $index);
$doc = $tokens[$docBlockIndex]->getContent();
return Preg::match('/\*\s+@test\b/', $doc);
}
private function removeTestPrefix(string $functionName): string
{
$remainder = Preg::replace('/^test(?=[A-Z_])_?/', '', $functionName);
if ('' === $remainder) {
return $functionName;
}
return lcfirst($remainder);
}
private function addTestPrefix(string $functionName): string
{
return 'test'.ucfirst($functionName);
}
/**
* @return list<Line>
*/
private function updateDocBlock(Tokens $tokens, int $docBlockIndex): array
{
$doc = new DocBlock($tokens[$docBlockIndex]->getContent());
$lines = $doc->getLines();
return $this->updateLines($lines, $tokens, $docBlockIndex);
}
/**
* @param list<Line> $lines
*
* @return list<Line>
*/
private function updateLines(array $lines, Tokens $tokens, int $docBlockIndex): array
{
$needsAnnotation = 'annotation' === $this->configuration['style'];
$doc = new DocBlock($tokens[$docBlockIndex]->getContent());
foreach ($lines as $i => $line) {
// If we need to add test annotation and it is a single line comment we need to deal with that separately
if ($needsAnnotation && ($line->isTheStart() && $line->isTheEnd())) {
if (!$this->doesDocBlockContainTest($doc)) {
$lines = $this->splitUpDocBlock($lines, $tokens, $docBlockIndex);
return $this->updateLines($lines, $tokens, $docBlockIndex);
}
// One we split it up, we run the function again, so we deal with other things in a proper way
}
if (!$needsAnnotation
&& str_contains($line->getContent(), ' @test')
&& !str_contains($line->getContent(), '@testWith')
&& !str_contains($line->getContent(), '@testdox')
) {
// We remove @test from the doc block
$lines[$i] = $line = new Line(str_replace(' @test', '', $line->getContent()));
}
// ignore the line if it isn't @depends
if (!str_contains($line->getContent(), '@depends')) {
continue;
}
$lines[$i] = $this->updateDependsAnnotation($line);
}
return $lines;
}
/**
* Take a one line doc block, and turn it into a multi line doc block.
*
* @param non-empty-list<Line> $lines
*
* @return non-empty-list<Line>
*/
private function splitUpDocBlock(array $lines, Tokens $tokens, int $docBlockIndex): array
{
$lineContent = $this->getSingleLineDocBlockEntry($lines);
$lineEnd = $this->whitespacesConfig->getLineEnding();
$originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex));
return [
new Line('/**'.$lineEnd),
new Line($originalIndent.' * '.$lineContent.$lineEnd),
new Line($originalIndent.' */'),
];
}
/**
* @TODO check whether it's doable to use \PhpCsFixer\DocBlock\DocBlock::getSingleLineDocBlockEntry instead
*
* @param non-empty-list<Line> $lines
*/
private function getSingleLineDocBlockEntry(array $lines): string
{
$line = $lines[0];
$line = str_replace('*/', '', $line->getContent());
$line = trim($line);
$line = str_split($line);
$i = \count($line);
do {
--$i;
} while ('*' !== $line[$i] && '*' !== $line[$i - 1] && '/' !== $line[$i - 2]);
if (' ' === $line[$i]) {
++$i;
}
$line = \array_slice($line, $i);
return implode('', $line);
}
/**
* Updates the depends tag on the current doc block.
*/
private function updateDependsAnnotation(Line $line): Line
{
if ('annotation' === $this->configuration['style']) {
return $this->removeTestPrefixFromDependsAnnotation($line);
}
return $this->addTestPrefixToDependsAnnotation($line);
}
private function removeTestPrefixFromDependsAnnotation(Line $line): Line
{
$line = str_split($line->getContent());
$dependsIndex = $this->findWhereDependsFunctionNameStarts($line);
$dependsFunctionName = implode('', \array_slice($line, $dependsIndex));
if ($this->hasTestPrefix($dependsFunctionName)) {
$dependsFunctionName = $this->removeTestPrefix($dependsFunctionName);
}
array_splice($line, $dependsIndex);
return new Line(implode('', $line).$dependsFunctionName);
}
private function addTestPrefixToDependsAnnotation(Line $line): Line
{
$line = str_split($line->getContent());
$dependsIndex = $this->findWhereDependsFunctionNameStarts($line);
$dependsFunctionName = implode('', \array_slice($line, $dependsIndex));
if (!$this->hasTestPrefix($dependsFunctionName)) {
$dependsFunctionName = $this->addTestPrefix($dependsFunctionName);
}
array_splice($line, $dependsIndex);
return new Line(implode('', $line).$dependsFunctionName);
}
/**
* Helps to find where the function name in the doc block starts.
*
* @param list<string> $line
*/
private function findWhereDependsFunctionNameStarts(array $line): int
{
$index = (int) stripos(implode('', $line), '@depends') + 8;
while (' ' === $line[$index]) {
++$index;
}
return $index;
}
/**
* @param list<Line> $lines
*
* @return list<Line>
*/
private function addTestAnnotation(array $lines, Tokens $tokens, int $docBlockIndex): array
{
$doc = new DocBlock($tokens[$docBlockIndex]->getContent());
if (!$this->doesDocBlockContainTest($doc)) {
$originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $docBlockIndex);
$lineEnd = $this->whitespacesConfig->getLineEnding();
array_splice($lines, -1, 0, [new Line($originalIndent.' *'.$lineEnd.$originalIndent.' * @test'.$lineEnd)]);
\assert(array_is_list($lines)); // we know it's list, but we need to tell PHPStan
}
return $lines;
}
private function doesDocBlockContainTest(DocBlock $doc): bool
{
return 0 !== \count($doc->getAnnotationsOfType('test'));
}
}
| 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/PhpUnit/PhpUnitSetUpTearDownVisibilityFixer.php | src/Fixer/PhpUnit/PhpUnitSetUpTearDownVisibilityFixer.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\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @author Gert de Pagter
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class PhpUnitSetUpTearDownVisibilityFixer extends AbstractPhpUnitFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Changes the visibility of the `setUp()` and `tearDown()` functions of PHPUnit to `protected`, to match the PHPUnit TestCase.',
[
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
private $hello;
public function setUp()
{
$this->hello = "hello";
}
public function tearDown()
{
$this->hello = null;
}
}
PHP,
),
],
null,
'This fixer may change functions named `setUp()` or `tearDown()` outside of PHPUnit tests, '
.'when a class is wrongly seen as a PHPUnit test.',
);
}
public function isRisky(): bool
{
return true;
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$counter = 0;
$tokensAnalyzer = new TokensAnalyzer($tokens);
$slicesToInsert = [];
for ($index = $startIndex + 1; $index < $endIndex; ++$index) {
if (2 === $counter) {
break; // we've seen both methods we are interested in, so stop analyzing this class
}
if ($tokens[$index]->equals('{')) {
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
continue;
}
if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) {
continue;
}
$functionNameIndex = $tokens->getNextMeaningfulToken($index);
$functionName = strtolower($tokens[$functionNameIndex]->getContent());
if ('setup' !== $functionName && 'teardown' !== $functionName) {
continue;
}
++$counter;
$visibility = $tokensAnalyzer->getMethodAttributes($index)['visibility'];
if (\T_PUBLIC === $visibility) {
$visibilityIndex = $tokens->getPrevTokenOfKind($index, [[\T_PUBLIC]]);
$tokens[$visibilityIndex] = new Token([\T_PROTECTED, 'protected']);
continue;
}
if (null === $visibility) {
$slicesToInsert[$index] = [new Token([\T_PROTECTED, 'protected']), new Token([\T_WHITESPACE, ' '])];
}
}
$tokens->insertSlices($slicesToInsert);
}
}
| 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/PhpUnit/PhpUnitInternalClassFixer.php | src/Fixer/PhpUnit/PhpUnitInternalClassFixer.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\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* types?: list<'abstract'|'final'|'normal'>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* types: list<'abstract'|'final'|'normal'>,
* }
*
* @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 PhpUnitInternalClassFixer extends AbstractPhpUnitFixer implements WhitespacesAwareFixerInterface, ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'All PHPUnit test classes should be marked as internal.',
[
new CodeSample("<?php\nclass MyTest extends TestCase {}\n"),
new CodeSample(
"<?php\nclass MyTest extends TestCase {}\nfinal class FinalTest extends TestCase {}\nabstract class AbstractTest extends TestCase {}\n",
['types' => ['final']],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before FinalInternalClassFixer, PhpdocSeparationFixer.
*/
public function getPriority(): int
{
return 68;
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
$types = ['normal', 'final', 'abstract'];
return new FixerConfigurationResolver([
(new FixerOptionBuilder('types', 'What types of classes to mark as internal.'))
->setAllowedValues([new AllowedValueSubset($types)])
->setAllowedTypes(['string[]'])
->setDefault(['normal', 'final'])
->getOption(),
]);
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$classIndex = $tokens->getPrevTokenOfKind($startIndex, [[\T_CLASS]]);
$prevIndex = $tokens->getPrevMeaningfulToken($classIndex);
if ($tokens[$prevIndex]->isGivenKind(\T_NEW)) {
return; // Skip instantiation of anonymous classes
}
if (!$this->isAllowedByConfiguration($tokens, $classIndex)) {
return;
}
$this->ensureIsDocBlockWithAnnotation(
$tokens,
$classIndex,
'internal',
['internal'],
[],
);
}
private function isAllowedByConfiguration(Tokens $tokens, int $index): bool
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
$modifiers = $tokensAnalyzer->getClassyModifiers($index);
if (isset($modifiers['final'])) {
return \in_array('final', $this->configuration['types'], true);
}
if (isset($modifiers['abstract'])) {
return \in_array('abstract', $this->configuration['types'], true);
}
return \in_array('normal', $this->configuration['types'], 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/PhpUnit/PhpUnitDataProviderMethodOrderFixer.php | src/Fixer/PhpUnit/PhpUnitDataProviderMethodOrderFixer.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\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ClassNotation\OrderedClassElementsFixer;
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\DataProviderAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* placement?: 'after'|'before',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* placement: 'after'|'before',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @phpstan-import-type _ClassElement from OrderedClassElementsFixer
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class PhpUnitDataProviderMethodOrderFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Data provider method must be placed after/before the last/first test where used.',
[
new CodeSample(
<<<'PHP'
<?php
class FooTest extends TestCase {
public function dataProvider() {}
/**
* @dataProvider dataProvider
*/
public function testSomething($expected, $actual) {}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
class FooTest extends TestCase {
/**
* @dataProvider dataProvider
*/
public function testSomething($expected, $actual) {}
public function dataProvider() {}
}
PHP,
[
'placement' => 'before',
],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before ClassAttributesSeparationFixer, NoBlankLinesAfterClassOpeningFixer.
* Must run after OrderedClassElementsFixer.
*/
public function getPriority(): int
{
return 64;
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('placement', 'Where to place the data provider relative to the test where used.'))
->setAllowedValues(['after', 'before'])
->setDefault('after')
->getOption(),
]);
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$elements = $this->getElements($tokens, $startIndex);
if (0 === \count($elements)) {
return;
}
$endIndex = $elements[array_key_last($elements)]['end'];
$dataProvidersWithUsagePairs = $this->getDataProvidersWithUsagePairs($tokens, $startIndex, $endIndex);
$origUsageDataProviderOrderPairs = $this->getOrigUsageDataProviderOrderPairs($dataProvidersWithUsagePairs);
$sorted = $elements;
$providersPlaced = [];
if ('before' === $this->configuration['placement']) {
foreach ($origUsageDataProviderOrderPairs as [$usageName, $providerName]) {
if (!isset($providersPlaced[$providerName])) {
$providersPlaced[$providerName] = true;
$sorted = $this->moveMethodElement($sorted, $usageName, $providerName, false);
}
}
} else {
$sameUsageName = false;
$sameProviderName = false;
foreach ($origUsageDataProviderOrderPairs as [$usageName, $providerName]) {
if (!isset($providersPlaced[$providerName])) {
$providersPlaced[$providerName] = true;
$sortedBefore = $sorted;
$sorted = $this->moveMethodElement(
$sorted,
$usageName === $sameUsageName // @phpstan-ignore argument.type (https://github.com/phpstan/phpstan/issues/12482)
? $sameProviderName
: $usageName,
$providerName,
true,
);
// honour multiple providers order for one test
$sameUsageName = $usageName;
$sameProviderName = $providerName;
// keep placement after the first test
if ($sortedBefore !== $sorted) {
unset($providersPlaced[$providerName]);
}
}
}
}
if ($sorted !== $elements) {
$this->sortTokens($tokens, $startIndex, $endIndex, $sorted);
}
}
/**
* @return list<_ClassElement>
*/
private function getElements(Tokens $tokens, int $startIndex): array
{
$methodOrderFixer = new OrderedClassElementsFixer();
return \Closure::bind(static fn () => $methodOrderFixer->getElements($tokens, $startIndex), null, OrderedClassElementsFixer::class)();
}
/**
* @param list<_ClassElement> $elements
*/
private function sortTokens(Tokens $tokens, int $startIndex, int $endIndex, array $elements): void
{
$methodOrderFixer = new OrderedClassElementsFixer();
\Closure::bind(static fn () => $methodOrderFixer->sortTokens($tokens, $startIndex, $endIndex, $elements), null, OrderedClassElementsFixer::class)();
}
/**
* @param list<_ClassElement> $elements
*
* @return list<_ClassElement>
*/
private function moveMethodElement(array $elements, string $nameKeep, string $nameToMove, bool $after): array
{
$i = 0;
$iKeep = false;
$iToMove = false;
foreach ($elements as $element) {
if ('method' === $element['type']) {
if ($element['name'] === $nameKeep) {
$iKeep = $i;
} elseif ($element['name'] === $nameToMove) {
$iToMove = $i;
}
}
++$i;
}
\assert(false !== $iKeep);
\assert(false !== $iToMove);
if ($iToMove === $iKeep + ($after ? 1 : -1)) {
return $elements;
}
$elementToMove = $elements[$iToMove]; // @phpstan-ignore offsetAccess.notFound
unset($elements[$iToMove]);
$c = $iKeep
+ ($after ? 1 : 0)
+ ($iToMove < $iKeep ? -1 : 0);
return [
...\array_slice($elements, 0, $c),
$elementToMove,
...\array_slice($elements, $c),
];
}
/**
* @return list<array{
* array{int, string},
* non-empty-array<int, array{int, string, int}>
* }>
*/
private function getDataProvidersWithUsagePairs(Tokens $tokens, int $startIndex, int $endIndex): array
{
$dataProvidersWithUsagePairs = [];
$dataProviderAnalyzer = new DataProviderAnalyzer();
foreach ($dataProviderAnalyzer->getDataProviders($tokens, $startIndex, $endIndex) as $dataProviderAnalysis) {
$usages = [];
foreach ($dataProviderAnalysis->getUsageIndices() as $usageIndex) {
$methodNameTokens = $tokens->findSequence([[\T_FUNCTION], [\T_STRING]], $usageIndex[0], $endIndex);
if (null === $methodNameTokens) {
continue;
}
$usages[array_key_last($methodNameTokens)] = [
array_key_last($methodNameTokens),
end($methodNameTokens)->getContent(),
$usageIndex[1],
];
}
\assert([] !== $usages);
$dataProvidersWithUsagePairs[] = [
[$dataProviderAnalysis->getNameIndex(), $dataProviderAnalysis->getName()],
$usages,
];
}
return $dataProvidersWithUsagePairs;
}
/**
* @param list<array{
* array{int, string},
* non-empty-array<int, array{int, string, int}>
* }> $dataProvidersWithUsagePairs
*
* @return list<array{string, string}>
*/
private function getOrigUsageDataProviderOrderPairs(array $dataProvidersWithUsagePairs): array
{
$origUsagesOrderPairs = [];
foreach ($dataProvidersWithUsagePairs as [$dataProviderPair, $usagePairs]) {
foreach ($usagePairs as $usagePair) {
$origUsagesOrderPairs[] = [$usagePair, $dataProviderPair[1]];
}
}
uasort($origUsagesOrderPairs, static function (array $a, array $b): int {
$cmp = $a[0][0] <=> $b[0][0];
return 0 !== $cmp
? $cmp
: $a[0][2] <=> $b[0][2];
});
$origUsageDataProviderOrderPairs = [];
foreach (array_map(static fn (array $v): array => [$v[0][1], $v[1]], $origUsagesOrderPairs) as [$usageName, $providerName]) {
$origUsageDataProviderOrderPairs[] = [$usageName, $providerName];
}
return $origUsageDataProviderOrderPairs;
}
}
| 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/PhpUnit/PhpUnitDataProviderNameFixer.php | src/Fixer/PhpUnit/PhpUnitDataProviderNameFixer.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\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\DataProviderAnalyzer;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* prefix?: string,
* suffix?: string,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* prefix: string,
* suffix: string,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Kuba Werłos <werlos@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class PhpUnitDataProviderNameFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Data provider names must match the name of the test.',
[
new CodeSample(
<<<'PHP'
<?php
class FooTest extends TestCase {
/**
* @dataProvider dataProvider
*/
public function testSomething($expected, $actual) {}
public function dataProvider() {}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
class FooTest extends TestCase {
/**
* @dataProvider dt_prvdr_ftr
*/
public function test_feature($expected, $actual) {}
public function dt_prvdr_ftr() {}
}
PHP,
[
'prefix' => 'data_',
'suffix' => '',
],
),
new CodeSample(
<<<'PHP'
<?php
class FooTest extends TestCase {
/**
* @dataProvider dataProviderUsedInMultipleTests
*/
public function testA($expected, $actual) {}
/**
* @dataProvider dataProviderUsedInMultipleTests
*/
public function testB($expected, $actual) {}
/**
* @dataProvider dataProviderUsedInSingleTest
*/
public function testC($expected, $actual) {}
/**
* @dataProvider dataProviderUsedAsFirstInTest
* @dataProvider dataProviderUsedAsSecondInTest
*/
public function testD($expected, $actual) {}
public function dataProviderUsedInMultipleTests() {}
public function dataProviderUsedInSingleTest() {}
public function dataProviderUsedAsFirstInTest() {}
public function dataProviderUsedAsSecondInTest() {}
}
PHP,
[
'prefix' => 'provides',
'suffix' => 'Data',
],
),
],
null,
'Fixer could be risky if one is calling data provider by name as function.',
);
}
public function isRisky(): bool
{
return true;
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('prefix', 'Prefix that replaces "test".'))
->setAllowedTypes(['string'])
->setDefault('provide')
->getOption(),
(new FixerOptionBuilder('suffix', 'Suffix to be present at the end.'))
->setAllowedTypes(['string'])
->setDefault('Cases')
->getOption(),
]);
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$dataProviders = (new DataProviderAnalyzer())->getDataProviders($tokens, $startIndex, $endIndex);
$methodsProviders = [];
$providersMethods = [];
foreach ($dataProviders as $dataProviderAnalysis) {
foreach ($dataProviderAnalysis->getUsageIndices() as [$usageIndex]) {
$methodIndex = $tokens->getNextTokenOfKind($usageIndex, [[\T_FUNCTION]]);
$methodsProviders[$methodIndex][$dataProviderAnalysis->getName()] = $usageIndex;
$providersMethods[$dataProviderAnalysis->getName()][$methodIndex] = $usageIndex;
}
}
foreach ($dataProviders as $dataProviderAnalysis) {
// @phpstan-ignore offsetAccess.notFound
if (\count($providersMethods[$dataProviderAnalysis->getName()]) > 1) {
continue;
}
$methodIndex = $tokens->getNextTokenOfKind($dataProviderAnalysis->getUsageIndices()[0][0], [[\T_FUNCTION]]);
// @phpstan-ignore offsetAccess.notFound
if (\count($methodsProviders[$methodIndex]) > 1) {
continue;
}
$dataProviderNewName = $this->getDataProviderNameForUsageIndex($tokens, $methodIndex);
if (null !== $tokens->findSequence([[\T_FUNCTION], [\T_STRING, $dataProviderNewName]], $startIndex, $endIndex)) {
continue;
}
foreach ($dataProviderAnalysis->getUsageIndices() as [$usageIndex]) {
$tokens[$dataProviderAnalysis->getNameIndex()] = new Token([\T_STRING, $dataProviderNewName]);
$newContent = $tokens[$usageIndex]->isGivenKind(\T_DOC_COMMENT)
? Preg::replace(
\sprintf('/(@dataProvider\s+)%s/', $dataProviderAnalysis->getName()),
\sprintf('$1%s', $dataProviderNewName),
$tokens[$usageIndex]->getContent(),
)
: \sprintf('%1$s%2$s%1$s', $tokens[$usageIndex]->getContent()[0], $dataProviderNewName);
$tokens[$usageIndex] = new Token([$tokens[$usageIndex]->getId(), $newContent]);
}
}
}
private function getDataProviderNameForUsageIndex(Tokens $tokens, int $index): string
{
do {
if ($tokens[$index]->isGivenKind(FCT::T_ATTRIBUTE)) {
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index);
}
$index = $tokens->getNextMeaningfulToken($index);
} while (!$tokens[$index]->isGivenKind(\T_STRING));
$name = $tokens[$index]->getContent();
$name = Preg::replace('/^test_*/i', '', $name);
if ('' === $this->configuration['prefix']) {
$name = lcfirst($name);
} elseif ('_' !== substr($this->configuration['prefix'], -1)) {
$name = ucfirst($name);
}
return $this->configuration['prefix'].$name.$this->configuration['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/PhpUnit/PhpUnitNamespacedFixer.php | src/Fixer/PhpUnit/PhpUnitNamespacedFixer.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\PhpUnit;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\ClassyAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* target?: '4.8'|'5.7'|'6.0'|'newest',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* target: '4.8'|'5.7'|'6.0'|'newest',
* }
*
* @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 PhpUnitNamespacedFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private string $originalClassRegEx;
/**
* Class Mappings.
*
* * [original classname => new classname] Some classes which match the
* original class regular expression do not have a same-compound name-
* space class and need a dedicated translation table. This trans-
* lation table is defined in @see configure.
*
* @var array<string, string> Class Mappings
*/
private array $classMap;
public function getDefinition(): FixerDefinitionInterface
{
$codeSample = <<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testSomething()
{
PHPUnit_Framework_Assert::assertTrue(true);
}
}
PHP;
return new FixerDefinition(
'PHPUnit classes MUST be used in namespaced version, e.g. `\PHPUnit\Framework\TestCase` instead of `\PHPUnit_Framework_TestCase`.',
[
new CodeSample($codeSample),
new CodeSample($codeSample, ['target' => PhpUnitTargetVersion::VERSION_4_8]),
],
"PHPUnit v6 has finally fully switched to namespaces.\n"
."You could start preparing the upgrade by switching from non-namespaced TestCase to namespaced one.\n"
.'Forward compatibility layer (`\PHPUnit\Framework\TestCase` class) was backported to PHPUnit v4.8.35 and PHPUnit v5.4.0.'."\n"
.'Extended forward compatibility layer (`PHPUnit\Framework\Assert`, `PHPUnit\Framework\BaseTestListener`, `PHPUnit\Framework\TestListener` classes) was introduced in v5.7.0.'."\n",
'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.',
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_STRING);
}
/**
* {@inheritdoc}
*
* Must run before NoUnneededImportAliasFixer.
*/
public function getPriority(): int
{
return 2;
}
public function isRisky(): bool
{
return true;
}
protected function configurePostNormalisation(): void
{
if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_6_0)) {
$this->originalClassRegEx = '/^PHPUnit_\w+$/i';
// @noinspection ClassConstantCanBeUsedInspection
$this->classMap = [
'PHPUnit_Extensions_PhptTestCase' => 'PHPUnit\Runner\PhptTestCase',
'PHPUnit_Framework_Constraint' => 'PHPUnit\Framework\Constraint\Constraint',
'PHPUnit_Framework_Constraint_StringMatches' => 'PHPUnit\Framework\Constraint\StringMatchesFormatDescription',
'PHPUnit_Framework_Constraint_JsonMatches_ErrorMessageProvider' => 'PHPUnit\Framework\Constraint\JsonMatchesErrorMessageProvider',
'PHPUnit_Framework_Constraint_PCREMatch' => 'PHPUnit\Framework\Constraint\RegularExpression',
'PHPUnit_Framework_Constraint_ExceptionMessageRegExp' => 'PHPUnit\Framework\Constraint\ExceptionMessageRegularExpression',
'PHPUnit_Framework_Constraint_And' => 'PHPUnit\Framework\Constraint\LogicalAnd',
'PHPUnit_Framework_Constraint_Or' => 'PHPUnit\Framework\Constraint\LogicalOr',
'PHPUnit_Framework_Constraint_Not' => 'PHPUnit\Framework\Constraint\LogicalNot',
'PHPUnit_Framework_Constraint_Xor' => 'PHPUnit\Framework\Constraint\LogicalXor',
'PHPUnit_Framework_Error' => 'PHPUnit\Framework\Error\Error',
'PHPUnit_Framework_TestSuite_DataProvider' => 'PHPUnit\Framework\DataProviderTestSuite',
'PHPUnit_Framework_MockObject_Invocation_Static' => 'PHPUnit\Framework\MockObject\Invocation\StaticInvocation',
'PHPUnit_Framework_MockObject_Invocation_Object' => 'PHPUnit\Framework\MockObject\Invocation\ObjectInvocation',
'PHPUnit_Framework_MockObject_Stub_Return' => 'PHPUnit\Framework\MockObject\Stub\ReturnStub',
'PHPUnit_Runner_Filter_Group_Exclude' => 'PHPUnit\Runner\Filter\ExcludeGroupFilterIterator',
'PHPUnit_Runner_Filter_Group_Include' => 'PHPUnit\Runner\Filter\IncludeGroupFilterIterator',
'PHPUnit_Runner_Filter_Test' => 'PHPUnit\Runner\Filter\NameFilterIterator',
'PHPUnit_Util_PHP' => 'PHPUnit\Util\PHP\AbstractPhpProcess',
'PHPUnit_Util_PHP_Default' => 'PHPUnit\Util\PHP\DefaultPhpProcess',
'PHPUnit_Util_PHP_Windows' => 'PHPUnit\Util\PHP\WindowsPhpProcess',
'PHPUnit_Util_Regex' => 'PHPUnit\Util\RegularExpression',
'PHPUnit_Util_TestDox_ResultPrinter_XML' => 'PHPUnit\Util\TestDox\XmlResultPrinter',
'PHPUnit_Util_TestDox_ResultPrinter_HTML' => 'PHPUnit\Util\TestDox\HtmlResultPrinter',
'PHPUnit_Util_TestDox_ResultPrinter_Text' => 'PHPUnit\Util\TestDox\TextResultPrinter',
'PHPUnit_Util_TestSuiteIterator' => 'PHPUnit\Framework\TestSuiteIterator',
'PHPUnit_Util_XML' => 'PHPUnit\Util\Xml',
];
} elseif (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_7)) {
$this->originalClassRegEx = '/^PHPUnit_Framework_(TestCase|Assert|BaseTestListener|TestListener)+$/i';
$this->classMap = [];
} else {
$this->originalClassRegEx = '/^PHPUnit_Framework_TestCase$/i';
$this->classMap = [];
}
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$importedOriginalClassesMap = [];
$currIndex = 0;
while (true) {
$currIndex = $tokens->getNextTokenOfKind($currIndex, [[\T_STRING]]);
if (null === $currIndex) {
break;
}
$prevIndex = $tokens->getPrevMeaningfulToken($currIndex);
if ($tokens[$prevIndex]->isGivenKind([\T_CONST, \T_DOUBLE_COLON])) {
continue;
}
$originalClass = $tokens[$currIndex]->getContent();
$allowedReplacementScenarios = (new ClassyAnalyzer())->isClassyInvocation($tokens, $currIndex)
|| $this->isImport($tokens, $currIndex);
if (!$allowedReplacementScenarios || !Preg::match($this->originalClassRegEx, $originalClass)) {
++$currIndex;
continue;
}
$substituteTokens = $this->generateReplacement($originalClass);
$tokens->clearAt($currIndex);
$tokens->insertAt(
$currIndex,
isset($importedOriginalClassesMap[$originalClass]) ? $substituteTokens[$substituteTokens->getSize() - 1] : $substituteTokens,
);
$prevIndex = $tokens->getPrevMeaningfulToken($currIndex);
if ($tokens[$prevIndex]->isGivenKind(\T_USE)) {
$importedOriginalClassesMap[$originalClass] = true;
} elseif ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) {
$prevIndex = $tokens->getPrevMeaningfulToken($prevIndex);
if ($tokens[$prevIndex]->isGivenKind(\T_USE)) {
$importedOriginalClassesMap[$originalClass] = true;
}
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('target', 'Target version of PHPUnit.'))
->setAllowedTypes(['string'])
->setAllowedValues([PhpUnitTargetVersion::VERSION_4_8, PhpUnitTargetVersion::VERSION_5_7, PhpUnitTargetVersion::VERSION_6_0, PhpUnitTargetVersion::VERSION_NEWEST])
->setDefault(PhpUnitTargetVersion::VERSION_NEWEST)
->getOption(),
]);
}
private function generateReplacement(string $originalClassName): Tokens
{
$delimiter = '_';
$string = $originalClassName;
$map = array_change_key_case($this->classMap);
if (isset($map[strtolower($originalClassName)])) {
$delimiter = '\\';
$string = $map[strtolower($originalClassName)];
}
$parts = explode($delimiter, $string);
$tokensArray = [];
while ([] !== $parts) {
$tokensArray[] = new Token([\T_STRING, array_shift($parts)]);
if ([] !== $parts) {
$tokensArray[] = new Token([\T_NS_SEPARATOR, '\\']);
}
}
return Tokens::fromArray($tokensArray);
}
private function isImport(Tokens $tokens, int $currIndex): bool
{
$prevIndex = $tokens->getPrevMeaningfulToken($currIndex);
if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) {
$prevIndex = $tokens->getPrevMeaningfulToken($prevIndex);
}
return $tokens[$prevIndex]->isGivenKind(\T_USE);
}
}
| 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/PhpUnit/PhpUnitDataProviderReturnTypeFixer.php | src/Fixer/PhpUnit/PhpUnitDataProviderReturnTypeFixer.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\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\DataProviderAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Kuba Werłos <werlos@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class PhpUnitDataProviderReturnTypeFixer extends AbstractPhpUnitFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'The return type of PHPUnit data provider must be `iterable`.',
[
new CodeSample(
<<<'PHP'
<?php
class FooTest extends TestCase {
/**
* @dataProvider provideSomethingCases
*/
public function testSomething($expected, $actual) {}
public function provideSomethingCases(): array {}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
class FooTest extends TestCase {
/**
* @dataProvider provideSomethingCases
*/
public function testSomething($expected, $actual) {}
public function provideSomethingCases() {}
}
PHP,
),
],
'Data provider must return `iterable`, either an array of arrays or an object that implements the `Traversable` interface.',
'Risky when relying on signature of the data provider.',
);
}
/**
* {@inheritdoc}
*
* Must run before ReturnToYieldFromFixer, ReturnTypeDeclarationFixer.
* Must run after CleanNamespaceFixer.
*/
public function getPriority(): int
{
return 9;
}
public function isRisky(): bool
{
return true;
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$dataProviderAnalyzer = new DataProviderAnalyzer();
$functionsAnalyzer = new FunctionsAnalyzer();
foreach (array_reverse($dataProviderAnalyzer->getDataProviders($tokens, $startIndex, $endIndex)) as $dataProviderAnalysis) {
$typeAnalysis = $functionsAnalyzer->getFunctionReturnType($tokens, $dataProviderAnalysis->getNameIndex());
if (null === $typeAnalysis) {
$argumentsStart = $tokens->getNextTokenOfKind($dataProviderAnalysis->getNameIndex(), ['(']);
$argumentsEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $argumentsStart);
$tokens->insertAt(
$argumentsEnd + 1,
[
new Token([CT::T_TYPE_COLON, ':']),
new Token([\T_WHITESPACE, ' ']),
new Token([\T_STRING, 'iterable']),
],
);
continue;
}
if ('iterable' === $typeAnalysis->getName()) {
continue;
}
$typeStartIndex = $tokens->getNextMeaningfulToken($typeAnalysis->getStartIndex() - 1);
$typeEndIndex = $typeAnalysis->getEndIndex();
// @TODO: drop condition and it's body when PHP 8+ is required
if ($tokens->generatePartialCode($typeStartIndex, $typeEndIndex) !== $typeAnalysis->getName()) {
continue;
}
$tokens->overrideRange($typeStartIndex, $typeEndIndex, [new Token([\T_STRING, 'iterable'])]);
}
}
}
| 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/PhpUnit/PhpUnitDedicateAssertFixer.php | src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.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\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
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\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* target?: '3.0'|'3.5'|'5.0'|'5.6'|'newest',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* target: '3.0'|'3.5'|'5.0'|'5.6'|'newest',
* }
*
* @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 PhpUnitDedicateAssertFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @var array<string, array{positive: string, negative: false|string, argument_count?: int, swap_arguments?: true}|true>
*/
private const FIX_MAP = [
'array_key_exists' => [
'positive' => 'assertArrayHasKey',
'negative' => 'assertArrayNotHasKey',
'argument_count' => 2,
],
'empty' => [
'positive' => 'assertEmpty',
'negative' => 'assertNotEmpty',
],
'file_exists' => [
'positive' => 'assertFileExists',
'negative' => 'assertFileNotExists',
],
'is_array' => true,
'is_bool' => true,
'is_callable' => true,
'is_dir' => [
'positive' => 'assertDirectoryExists',
'negative' => 'assertDirectoryNotExists',
],
'is_double' => true,
'is_float' => true,
'is_infinite' => [
'positive' => 'assertInfinite',
'negative' => 'assertFinite',
],
'is_int' => true,
'is_integer' => true,
'is_long' => true,
'is_nan' => [
'positive' => 'assertNan',
'negative' => false,
],
'is_null' => [
'positive' => 'assertNull',
'negative' => 'assertNotNull',
],
'is_numeric' => true,
'is_object' => true,
'is_readable' => [
'positive' => 'assertIsReadable',
'negative' => 'assertNotIsReadable',
],
'is_real' => true,
'is_resource' => true,
'is_scalar' => true,
'is_string' => true,
'is_writable' => [
'positive' => 'assertIsWritable',
'negative' => 'assertNotIsWritable',
],
'str_contains' => [ // since 7.5
'positive' => 'assertStringContainsString',
'negative' => 'assertStringNotContainsString',
'argument_count' => 2,
'swap_arguments' => true,
],
'str_ends_with' => [ // since 3.4
'positive' => 'assertStringEndsWith',
'negative' => 'assertStringEndsNotWith',
'argument_count' => 2,
'swap_arguments' => true,
],
'str_starts_with' => [ // since 3.4
'positive' => 'assertStringStartsWith',
'negative' => 'assertStringStartsNotWith',
'argument_count' => 2,
'swap_arguments' => true,
],
];
/**
* @var list<string>
*/
private array $functions = [];
public function isRisky(): bool
{
return true;
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'PHPUnit assertions like `assertInternalType`, `assertFileExists`, should be used over `assertTrue`.',
[
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testSomeTest()
{
$this->assertTrue(is_float( $a), "my message");
$this->assertTrue(is_nan($a));
}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testSomeTest()
{
$this->assertTrue(is_dir($a));
$this->assertTrue(is_writable($a));
$this->assertTrue(is_readable($a));
}
}
PHP,
['target' => PhpUnitTargetVersion::VERSION_5_6],
),
],
null,
'Fixer could be risky if one is overriding PHPUnit\'s native methods.',
);
}
/**
* {@inheritdoc}
*
* Must run before NoUnusedImportsFixer, PhpUnitAssertNewNamesFixer, PhpUnitDedicateAssertInternalTypeFixer.
* Must run after ModernizeStrposFixer, NoAliasFunctionsFixer, PhpUnitConstructFixer.
*/
public function getPriority(): int
{
return -9;
}
protected function configurePostNormalisation(): void
{
// assertions added in 3.0: assertArrayNotHasKey assertArrayHasKey assertFileNotExists assertFileExists assertNotNull, assertNull
$this->functions = [
'array_key_exists',
'file_exists',
'is_null',
'str_ends_with',
'str_starts_with',
];
if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_3_5)) {
// assertions added in 3.5: assertInternalType assertNotEmpty assertEmpty
$this->functions = array_merge($this->functions, [
'empty',
'is_array',
'is_bool',
'is_boolean',
'is_callable',
'is_double',
'is_float',
'is_int',
'is_integer',
'is_long',
'is_numeric',
'is_object',
'is_real',
'is_scalar',
'is_string',
]);
}
if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_0)) {
// assertions added in 5.0: assertFinite assertInfinite assertNan
$this->functions = array_merge($this->functions, [
'is_infinite',
'is_nan',
]);
}
if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_6)) {
// assertions added in 5.6: assertDirectoryExists assertDirectoryNotExists assertIsReadable assertNotIsReadable assertIsWritable assertNotIsWritable
$this->functions = array_merge($this->functions, [
'is_dir',
'is_readable',
'is_writable',
]);
}
if (PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_7_5)) {
$this->functions = array_merge($this->functions, [
'str_contains',
]);
}
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$argumentsAnalyzer = new ArgumentsAnalyzer();
foreach ($this->getPreviousAssertCall($tokens, $startIndex, $endIndex) as $assertCall) {
// test and fix for assertTrue/False to dedicated asserts
if (\in_array($assertCall['loweredName'], ['asserttrue', 'assertfalse'], true)) {
$this->fixAssertTrueFalse($tokens, $argumentsAnalyzer, $assertCall);
continue;
}
if (\in_array(
$assertCall['loweredName'],
['assertsame', 'assertnotsame', 'assertequals', 'assertnotequals'],
true,
)) {
$this->fixAssertSameEquals($tokens, $assertCall);
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('target', 'Target version of PHPUnit.'))
->setAllowedTypes(['string'])
->setAllowedValues([
PhpUnitTargetVersion::VERSION_3_0,
PhpUnitTargetVersion::VERSION_3_5,
PhpUnitTargetVersion::VERSION_5_0,
PhpUnitTargetVersion::VERSION_5_6,
PhpUnitTargetVersion::VERSION_NEWEST,
])
->setDefault(PhpUnitTargetVersion::VERSION_NEWEST)
->getOption(),
]);
}
/**
* @param array{
* index: int,
* loweredName: string,
* openBraceIndex: int,
* closeBraceIndex: int,
* } $assertCall
*/
private function fixAssertTrueFalse(Tokens $tokens, ArgumentsAnalyzer $argumentsAnalyzer, array $assertCall): void
{
$testDefaultNamespaceTokenIndex = null;
$testIndex = $tokens->getNextMeaningfulToken($assertCall['openBraceIndex']);
if (!$tokens[$testIndex]->isGivenKind([\T_EMPTY, \T_STRING])) {
if ($this->fixAssertTrueFalseInstanceof($tokens, $assertCall, $testIndex)) {
return;
}
if (!$tokens[$testIndex]->isGivenKind(\T_NS_SEPARATOR)) {
return;
}
$testDefaultNamespaceTokenIndex = $testIndex;
$testIndex = $tokens->getNextMeaningfulToken($testIndex);
}
$testOpenIndex = $tokens->getNextMeaningfulToken($testIndex);
if (!$tokens[$testOpenIndex]->equals('(')) {
return;
}
$testCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $testOpenIndex);
$assertCallCloseIndex = $tokens->getNextMeaningfulToken($testCloseIndex);
if (!$tokens[$assertCallCloseIndex]->equalsAny([')', ','])) {
return;
}
$content = strtolower($tokens[$testIndex]->getContent());
if (!\in_array($content, $this->functions, true)) {
return;
}
$arguments = $argumentsAnalyzer->getArguments($tokens, $testOpenIndex, $testCloseIndex);
$isPositive = 'asserttrue' === $assertCall['loweredName'];
if (isset(self::FIX_MAP[$content]) && \is_array(self::FIX_MAP[$content])) {
$fixDetails = self::FIX_MAP[$content];
$expectedCount = $fixDetails['argument_count'] ?? 1;
if ($expectedCount !== \count($arguments)) {
return;
}
$isPositive = $isPositive ? 'positive' : 'negative';
if (false === $fixDetails[$isPositive]) {
return;
}
$tokens[$assertCall['index']] = new Token([\T_STRING, $fixDetails[$isPositive]]);
$this->removeFunctionCall($tokens, $testDefaultNamespaceTokenIndex, $testIndex, $testOpenIndex, $testCloseIndex);
if ($fixDetails['swap_arguments'] ?? false) {
if (2 !== $expectedCount) {
throw new \RuntimeException('Can only swap two arguments, please update map or logic.');
}
$this->swapArguments($tokens, $arguments);
}
return;
}
if (1 !== \count($arguments)) {
return;
}
$type = substr($content, 3);
$tokens[$assertCall['index']] = new Token([\T_STRING, $isPositive ? 'assertInternalType' : 'assertNotInternalType']);
$tokens[$testIndex] = new Token([\T_CONSTANT_ENCAPSED_STRING, "'".$type."'"]);
$tokens[$testOpenIndex] = new Token(',');
$tokens->clearTokenAndMergeSurroundingWhitespace($testCloseIndex);
$commaIndex = $tokens->getPrevMeaningfulToken($testCloseIndex);
if ($tokens[$commaIndex]->equals(',')) {
$tokens->removeTrailingWhitespace($commaIndex);
$tokens->clearAt($commaIndex);
}
if (!$tokens[$testOpenIndex + 1]->isWhitespace()) {
$tokens->insertAt($testOpenIndex + 1, new Token([\T_WHITESPACE, ' ']));
}
if (null !== $testDefaultNamespaceTokenIndex) {
$tokens->clearTokenAndMergeSurroundingWhitespace($testDefaultNamespaceTokenIndex);
}
}
/**
* @param array{
* index: int,
* loweredName: string,
* openBraceIndex: int,
* closeBraceIndex: int,
* } $assertCall
*/
private function fixAssertTrueFalseInstanceof(Tokens $tokens, array $assertCall, int $testIndex): bool
{
$isPositiveAssertion = 'asserttrue' === $assertCall['loweredName'];
if ($tokens[$testIndex]->equals('!')) {
$variableIndex = $tokens->getNextMeaningfulToken($testIndex);
$isPositiveCondition = false;
} else {
$variableIndex = $testIndex;
$isPositiveCondition = true;
}
if (!$tokens[$variableIndex]->isGivenKind(\T_VARIABLE)) {
return false;
}
$instanceOfIndex = $tokens->getNextMeaningfulToken($variableIndex);
if (!$tokens[$instanceOfIndex]->isGivenKind(\T_INSTANCEOF)) {
return false;
}
$classEndIndex = $tokens->getNextMeaningfulToken($instanceOfIndex);
$classPartTokens = [];
do {
$classPartTokens[] = $tokens[$classEndIndex];
$classEndIndex = $tokens->getNextMeaningfulToken($classEndIndex);
} while ($tokens[$classEndIndex]->isGivenKind([\T_STRING, \T_NS_SEPARATOR, \T_VARIABLE]));
if ($tokens[$classEndIndex]->equalsAny([',', ')'])) { // do the fixing
$isInstanceOfVar = $classPartTokens[0]->isGivenKind(\T_VARIABLE);
$insertIndex = $testIndex - 1;
$newTokens = [];
foreach ($classPartTokens as $token) {
$newTokens[++$insertIndex] = clone $token;
}
if (!$isInstanceOfVar) {
$newTokens[++$insertIndex] = new Token([\T_DOUBLE_COLON, '::']);
$newTokens[++$insertIndex] = new Token([CT::T_CLASS_CONSTANT, 'class']);
}
$newTokens[++$insertIndex] = new Token(',');
$newTokens[++$insertIndex] = new Token([\T_WHITESPACE, ' ']);
$newTokens[++$insertIndex] = clone $tokens[$variableIndex];
for ($i = $classEndIndex - 1; $i >= $testIndex; --$i) {
if (!$tokens[$i]->isComment()) {
$tokens->clearTokenAndMergeSurroundingWhitespace($i);
}
}
$name = $isPositiveAssertion && $isPositiveCondition || !$isPositiveAssertion && !$isPositiveCondition
? 'assertInstanceOf'
: 'assertNotInstanceOf';
$tokens->insertSlices($newTokens);
$tokens[$assertCall['index']] = new Token([\T_STRING, $name]);
}
return true;
}
/**
* @param array{
* index: int,
* loweredName: string,
* openBraceIndex: int,
* closeBraceIndex: int,
* } $assertCall
*/
private function fixAssertSameEquals(Tokens $tokens, array $assertCall): void
{
// @ $this->/self::assertEquals/Same([$nextIndex])
$expectedIndex = $tokens->getNextMeaningfulToken($assertCall['openBraceIndex']);
// do not fix
// let $a = [1,2]; $b = "2";
// "$this->assertEquals("2", count($a)); $this->assertEquals($b, count($a)); $this->assertEquals(2.1, count($a));"
if ($tokens[$expectedIndex]->isGivenKind(\T_VARIABLE)) {
if (!$tokens[$tokens->getNextMeaningfulToken($expectedIndex)]->equals(',')) {
return;
}
} elseif (!$tokens[$expectedIndex]->isGivenKind([\T_LNUMBER, \T_VARIABLE])) {
return;
}
// @ $this->/self::assertEquals/Same([$nextIndex,$commaIndex])
$commaIndex = $tokens->getNextMeaningfulToken($expectedIndex);
if (!$tokens[$commaIndex]->equals(',')) {
return;
}
// @ $this->/self::assertEquals/Same([$nextIndex,$commaIndex,$countCallIndex])
$countCallIndex = $tokens->getNextMeaningfulToken($commaIndex);
if ($tokens[$countCallIndex]->isGivenKind(\T_NS_SEPARATOR)) {
$defaultNamespaceTokenIndex = $countCallIndex;
$countCallIndex = $tokens->getNextMeaningfulToken($countCallIndex);
} else {
$defaultNamespaceTokenIndex = null;
}
if (!$tokens[$countCallIndex]->isGivenKind(\T_STRING)) {
return;
}
$lowerContent = strtolower($tokens[$countCallIndex]->getContent());
if (!\in_array($lowerContent, ['count', 'sizeof'], true)) {
return; // not a call to "count" or "sizeOf"
}
// @ $this->/self::assertEquals/Same([$nextIndex,$commaIndex,[$defaultNamespaceTokenIndex,]$countCallIndex,$countCallOpenBraceIndex])
$countCallOpenBraceIndex = $tokens->getNextMeaningfulToken($countCallIndex);
if (!$tokens[$countCallOpenBraceIndex]->equals('(')) {
return;
}
$countCallCloseBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $countCallOpenBraceIndex);
$afterCountCallCloseBraceIndex = $tokens->getNextMeaningfulToken($countCallCloseBraceIndex);
if (!$tokens[$afterCountCallCloseBraceIndex]->equalsAny([')', ','])) {
return;
}
$this->removeFunctionCall(
$tokens,
$defaultNamespaceTokenIndex,
$countCallIndex,
$countCallOpenBraceIndex,
$countCallCloseBraceIndex,
);
$tokens[$assertCall['index']] = new Token([
\T_STRING,
false === strpos($assertCall['loweredName'], 'not', 6) ? 'assertCount' : 'assertNotCount',
]);
}
private function removeFunctionCall(Tokens $tokens, ?int $callNSIndex, int $callIndex, int $openIndex, int $closeIndex): void
{
$tokens->clearTokenAndMergeSurroundingWhitespace($callIndex);
if (null !== $callNSIndex) {
$tokens->clearTokenAndMergeSurroundingWhitespace($callNSIndex);
}
$tokens->clearTokenAndMergeSurroundingWhitespace($openIndex);
$commaIndex = $tokens->getPrevMeaningfulToken($closeIndex);
if ($tokens[$commaIndex]->equals(',')) {
$tokens->removeTrailingWhitespace($commaIndex);
$tokens->clearAt($commaIndex);
}
$tokens->clearTokenAndMergeSurroundingWhitespace($closeIndex);
}
/**
* @param array<int, int> $argumentsIndices
*/
private function swapArguments(Tokens $tokens, array $argumentsIndices): void
{
[$firstArgumentIndex, $secondArgumentIndex] = array_keys($argumentsIndices);
$firstArgumentEndIndex = $argumentsIndices[$firstArgumentIndex];
$secondArgumentEndIndex = $argumentsIndices[$secondArgumentIndex];
$firstClone = $this->cloneAndClearTokens($tokens, $firstArgumentIndex, $firstArgumentEndIndex);
$secondClone = $this->cloneAndClearTokens($tokens, $secondArgumentIndex, $secondArgumentEndIndex);
if (!$firstClone[0]->isWhitespace()) {
array_unshift($firstClone, new Token([\T_WHITESPACE, ' ']));
}
$tokens->insertAt($secondArgumentIndex, $firstClone);
if ($secondClone[0]->isWhitespace()) {
array_shift($secondClone);
}
$tokens->insertAt($firstArgumentIndex, $secondClone);
}
/**
* @return list<Token>
*/
private function cloneAndClearTokens(Tokens $tokens, int $start, int $end): array
{
$clone = [];
for ($i = $start; $i <= $end; ++$i) {
if ('' === $tokens[$i]->getContent()) {
continue;
}
$clone[] = clone $tokens[$i];
$tokens->clearAt($i);
}
return $clone;
}
}
| 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/PhpUnit/PhpUnitConstructFixer.php | src/Fixer/PhpUnit/PhpUnitConstructFixer.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\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
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\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* assertions?: list<'assertEquals'|'assertNotEquals'|'assertNotSame'|'assertSame'>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* assertions: list<'assertEquals'|'assertNotEquals'|'assertNotSame'|'assertSame'>,
* }
*
* @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 PhpUnitConstructFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function isRisky(): bool
{
return true;
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'PHPUnit assertion method calls like `->assertSame(true, $foo)` should be written with dedicated method like `->assertTrue($foo)`.',
[
new CodeSample(
<<<'PHP'
<?php
final class FooTest extends \PHPUnit_Framework_TestCase {
public function testSomething() {
$this->assertEquals(false, $b);
$this->assertSame(true, $a);
$this->assertNotEquals(null, $c);
$this->assertNotSame(null, $d);
}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
final class FooTest extends \PHPUnit_Framework_TestCase {
public function testSomething() {
$this->assertEquals(false, $b);
$this->assertSame(true, $a);
$this->assertNotEquals(null, $c);
$this->assertNotSame(null, $d);
}
}
PHP,
['assertions' => ['assertSame', 'assertNotSame']],
),
],
null,
'Fixer could be risky if one is overriding PHPUnit\'s native methods.',
);
}
/**
* {@inheritdoc}
*
* Must run before PhpUnitDedicateAssertFixer.
*/
public function getPriority(): int
{
return -8;
}
/**
* @uses fixAssertNegative()
* @uses fixAssertPositive()
*/
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
// no assertions to be fixed - fast return
if ([] === $this->configuration['assertions']) {
return;
}
foreach ($this->configuration['assertions'] as $assertionMethod) {
for ($index = $startIndex; $index < $endIndex; ++$index) {
$index = \call_user_func_array(
\in_array($assertionMethod, ['assertSame', 'assertEquals'], true)
? [$this, 'fixAssertPositive']
: [$this, 'fixAssertNegative'],
[$tokens, $index, $assertionMethod],
);
if (null === $index) {
break;
}
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
$assertMethods = [
'assertEquals',
'assertNotEquals',
'assertNotSame',
'assertSame',
];
return new FixerConfigurationResolver([
(new FixerOptionBuilder('assertions', 'List of assertion methods to fix.'))
->setAllowedTypes(['string[]'])
->setAllowedValues([new AllowedValueSubset($assertMethods)])
->setDefault($assertMethods)
->getOption(),
]);
}
private function fixAssertNegative(Tokens $tokens, int $index, string $method): ?int
{
return $this->fixAssert([
'false' => 'assertNotFalse',
'null' => 'assertNotNull',
'true' => 'assertNotTrue',
], $tokens, $index, $method);
}
private function fixAssertPositive(Tokens $tokens, int $index, string $method): ?int
{
return $this->fixAssert([
'false' => 'assertFalse',
'null' => 'assertNull',
'true' => 'assertTrue',
], $tokens, $index, $method);
}
/**
* @param array<string, string> $map
*/
private function fixAssert(array $map, Tokens $tokens, int $index, string $method): ?int
{
$functionsAnalyzer = new FunctionsAnalyzer();
$sequence = $tokens->findSequence(
[
[\T_STRING, $method],
'(',
],
$index,
);
if (null === $sequence) {
return null;
}
$sequenceIndices = array_keys($sequence);
if (!$functionsAnalyzer->isTheSameClassCall($tokens, $sequenceIndices[0])) {
return null;
}
$sequenceIndices[2] = $tokens->getNextMeaningfulToken($sequenceIndices[1]);
$firstParameterToken = $tokens[$sequenceIndices[2]];
if (!$firstParameterToken->isNativeConstant()) {
return $sequenceIndices[2];
}
$sequenceIndices[3] = $tokens->getNextMeaningfulToken($sequenceIndices[2]);
// return if first method argument is an expression, not value
if (!$tokens[$sequenceIndices[3]]->equals(',')) {
return $sequenceIndices[3];
}
$tokens[$sequenceIndices[0]] = new Token([\T_STRING, $map[strtolower($firstParameterToken->getContent())]]);
$tokens->clearRange($sequenceIndices[2], $tokens->getNextNonWhitespace($sequenceIndices[3]) - 1);
return $sequenceIndices[3];
}
}
| 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/PhpUnit/PhpUnitFqcnAnnotationFixer.php | src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.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\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Roland Franssen <franssen.roland@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class PhpUnitFqcnAnnotationFixer extends AbstractPhpUnitFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'PHPUnit annotations should be a FQCNs including a root namespace.',
[
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException InvalidArgumentException
* @covers Project\NameSpace\Something
* @coversDefaultClass Project\Default
* @uses Project\Test\Util
*/
public function testSomeTest()
{
}
}
PHP,
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before NoUnusedImportsFixer, PhpdocOrderByValueFixer.
*/
public function getPriority(): int
{
return -9;
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$prevDocCommentIndex = $tokens->getPrevTokenOfKind($startIndex, [[\T_DOC_COMMENT]]);
if (null !== $prevDocCommentIndex) {
$startIndex = $prevDocCommentIndex;
}
$this->fixPhpUnitClass($tokens, $startIndex, $endIndex);
}
private function fixPhpUnitClass(Tokens $tokens, int $startIndex, int $endIndex): void
{
for ($index = $startIndex; $index < $endIndex; ++$index) {
if ($tokens[$index]->isGivenKind(\T_DOC_COMMENT)) {
$tokens[$index] = new Token([\T_DOC_COMMENT, Preg::replace(
'~^(\s*\*\s*@(?:expectedException|covers|coversDefaultClass|uses)\h+)(?!(?:self|static)::)(\w.*)$~m',
'$1\\\$2',
$tokens[$index]->getContent(),
)]);
}
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/PhpUnit/PhpUnitMockShortWillReturnFixer.php | src/Fixer/PhpUnit/PhpUnitMockShortWillReturnFixer.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\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Michał Adamski <michal.adamski@gmail.com>
* @author Kuba Werłos <werlos@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class PhpUnitMockShortWillReturnFixer extends AbstractPhpUnitFixer
{
private const RETURN_METHODS_MAP = [
'returnargument' => 'willReturnArgument',
'returncallback' => 'willReturnCallback',
'returnself' => 'willReturnSelf',
'returnvalue' => 'willReturn',
'returnvaluemap' => 'willReturnMap',
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Usage of PHPUnit\'s mock e.g. `->will($this->returnValue(..))` must be replaced by its shorter equivalent such as `->willReturn(...)`.',
[
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testSomeTest()
{
$someMock = $this->createMock(Some::class);
$someMock->method("some")->will($this->returnSelf());
$someMock->method("some")->will($this->returnValue("example"));
$someMock->method("some")->will($this->returnArgument(2));
$someMock->method("some")->will($this->returnCallback("str_rot13"));
$someMock->method("some")->will($this->returnValueMap(["a","b","c"]));
}
}
PHP,
),
],
null,
'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.',
);
}
public function isRisky(): bool
{
return true;
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$functionsAnalyzer = new FunctionsAnalyzer();
for ($index = $startIndex; $index < $endIndex; ++$index) {
if (!$tokens[$index]->isObjectOperator()) {
continue;
}
$functionToReplaceIndex = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$functionToReplaceIndex]->equals([\T_STRING, 'will'], false)) {
continue;
}
$functionToReplaceOpeningBraceIndex = $tokens->getNextMeaningfulToken($functionToReplaceIndex);
if (!$tokens[$functionToReplaceOpeningBraceIndex]->equals('(')) {
continue;
}
$classReferenceIndex = $tokens->getNextMeaningfulToken($functionToReplaceOpeningBraceIndex);
$objectOperatorIndex = $tokens->getNextMeaningfulToken($classReferenceIndex);
$functionToRemoveIndex = $tokens->getNextMeaningfulToken($objectOperatorIndex);
if (!$functionsAnalyzer->isTheSameClassCall($tokens, $functionToRemoveIndex)) {
continue;
}
if (!\array_key_exists(strtolower($tokens[$functionToRemoveIndex]->getContent()), self::RETURN_METHODS_MAP)) {
continue;
}
$openingBraceIndex = $tokens->getNextMeaningfulToken($functionToRemoveIndex);
if ($tokens[$tokens->getNextMeaningfulToken($openingBraceIndex)]->isGivenKind(CT::T_FIRST_CLASS_CALLABLE)) {
continue;
}
$closingBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openingBraceIndex);
$tokens[$functionToReplaceIndex] = new Token([\T_STRING, self::RETURN_METHODS_MAP[strtolower($tokens[$functionToRemoveIndex]->getContent())]]);
$tokens->clearTokenAndMergeSurroundingWhitespace($classReferenceIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($objectOperatorIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($functionToRemoveIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($openingBraceIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($closingBraceIndex);
$commaAfterClosingBraceIndex = $tokens->getNextMeaningfulToken($closingBraceIndex);
if ($tokens[$commaAfterClosingBraceIndex]->equals(',')) {
$tokens->clearTokenAndMergeSurroundingWhitespace($commaAfterClosingBraceIndex);
}
}
}
}
| 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/PhpUnit/PhpUnitAssertNewNamesFixer.php | src/Fixer/PhpUnit/PhpUnitAssertNewNamesFixer.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\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Krzysztof Ciszewski <krzysztof@ciszew.ski>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class PhpUnitAssertNewNamesFixer extends AbstractPhpUnitFixer
{
public function isRisky(): bool
{
return true;
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Rename deprecated PHPUnit assertions like `assertFileNotExists` to new methods like `assertFileDoesNotExist`.',
[
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testSomeTest()
{
$this->assertFileNotExists("test.php");
$this->assertNotIsWritable("path.php");
}
}
PHP,
),
],
null,
'Fixer could be risky if one is overriding PHPUnit\'s native methods.',
);
}
/**
* {@inheritdoc}
*
* Must run after PhpUnitDedicateAssertFixer.
*/
public function getPriority(): int
{
return -10;
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
foreach ($this->getPreviousAssertCall($tokens, $startIndex, $endIndex) as $assertCall) {
$this->fixAssertNewNames($tokens, $assertCall);
}
}
/**
* @param array{
* index: int,
* loweredName: string,
* openBraceIndex: int,
* closeBraceIndex: int,
* } $assertCall
*/
private function fixAssertNewNames(Tokens $tokens, array $assertCall): void
{
$replacements = [
'assertnotisreadable' => 'assertIsNotReadable',
'assertnotiswritable' => 'assertIsNotWritable',
'assertdirectorynotexists' => 'assertDirectoryDoesNotExist',
'assertfilenotexists' => 'assertFileDoesNotExist',
'assertdirectorynotisreadable' => 'assertDirectoryIsNotReadable',
'assertdirectorynotiswritable' => 'assertDirectoryIsNotWriteable',
'assertfilenotisreadable' => 'assertFileIsNotReadable',
'assertfilenotiswritable' => 'assertFileIsNotWriteable',
'assertregexp' => 'assertMatchesRegularExpression',
'assertnotregexp' => 'assertDoesNotMatchRegularExpression',
];
$replacement = $replacements[$assertCall['loweredName']] ?? null;
if (null === $replacement) {
return;
}
$tokens[$assertCall['index']] = new Token([
\T_STRING,
$replacement,
]);
}
}
| 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/PhpUnit/PhpUnitAttributesFixer.php | src/Fixer/PhpUnit/PhpUnitAttributesFixer.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\PhpUnit;
use PhpCsFixer\DocBlock\Annotation;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\FullyQualifiedNameAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Processor\ImportProcessor;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* keep_annotations?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* keep_annotations: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Kuba Werłos <werlos@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class PhpUnitAttributesFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/** @var array<string, string> */
private array $fixingMap;
public function __construct()
{
parent::__construct();
$this->prepareFixingMap();
}
public function getDefinition(): FixerDefinitionInterface
{
$codeSample = <<<'PHP'
<?php
/**
* @covers \VendorName\Foo
* @internal
*/
final class FooTest extends TestCase {
/**
* @param int $expected
* @param int $actual
* @dataProvider giveMeSomeData
* @requires PHP 8.0
*/
public function testSomething($expected, $actual) {}
}
PHP;
return new FixerDefinition(
'PHPUnit attributes must be used over their respective PHPDoc-based annotations.',
[
new VersionSpecificCodeSample($codeSample, new VersionSpecification(8_00_00)),
new VersionSpecificCodeSample($codeSample, new VersionSpecification(8_00_00), ['keep_annotations' => true]),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return \PHP_VERSION_ID >= 8_00_00 && parent::isCandidate($tokens);
}
/**
* {@inheritdoc}
*
* Must run before FullyQualifiedStrictTypesFixer, NoEmptyPhpdocFixer, PhpdocSeparationFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer.
* Must run after PhpUnitSizeClassFixer, PhpUnitTestClassRequiresCoversFixer.
*/
public function getPriority(): int
{
return 8;
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('keep_annotations', 'Whether to keep annotations or not. This may be helpful for projects that support PHP before version 8 or PHPUnit before version 10.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$fullyQualifiedNameAnalyzer = new FullyQualifiedNameAnalyzer($tokens);
$classIndex = $tokens->getPrevTokenOfKind($startIndex, [[\T_CLASS]]);
$docBlockIndex = $this->getDocBlockIndex($tokens, $classIndex);
if ($tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT)) {
$startIndex = $docBlockIndex;
}
for ($index = $endIndex; $index >= $startIndex; --$index) {
if (!$tokens[$index]->isGivenKind(\T_DOC_COMMENT)) {
continue;
}
$targetIndex = $tokens->getTokenNotOfKindSibling(
$index,
1,
[[\T_ABSTRACT], [\T_COMMENT], [\T_FINAL], [\T_FUNCTION], [\T_PRIVATE], [\T_PROTECTED], [\T_PUBLIC], [\T_STATIC], [\T_WHITESPACE]],
);
$annotationScope = $tokens[$targetIndex]->isGivenKind(\T_CLASS) ? 'class' : 'method';
$docBlock = new DocBlock($tokens[$index]->getContent());
$presentAttributes = [];
foreach (array_reverse($docBlock->getAnnotations()) as $annotation) {
$annotationName = $annotation->getTag()->getName();
if (!isset($this->fixingMap[$annotationName])) {
continue;
}
if (!self::shouldBeFixed($annotationName, $annotationScope)) {
continue;
}
/** @phpstan-ignore-next-line */
$tokensToInsert = self::{$this->fixingMap[$annotationName]}($tokens, $index, $annotation);
$presentAttributes[$annotationName] ??= self::isAttributeAlreadyPresent($fullyQualifiedNameAnalyzer, $tokens, $index, $tokensToInsert);
if ([] === $tokensToInsert) {
continue;
}
if (!$presentAttributes[$annotationName]) {
$tokens->insertSlices([$index + 1 => $tokensToInsert]);
}
if (!$this->configuration['keep_annotations']) {
$annotation->remove();
}
}
if ('' === $docBlock->getContent()) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
} else {
$tokens[$index] = new Token([\T_DOC_COMMENT, $docBlock->getContent()]);
}
}
}
private function prepareFixingMap(): void
{
// annotations that map to attribute without parameters
foreach ([
'after',
'afterClass',
'before',
'beforeClass',
'coversNothing',
'doesNotPerformAssertions',
'large',
'medium',
'runInSeparateProcess',
'runTestsInSeparateProcesses',
'small',
'test',
'preCondition',
'postCondition',
] as $annotation) {
$this->fixingMap[$annotation] = 'fixWithoutParameters';
}
// annotations that map to attribute with single string value
foreach (['group', 'testDox', 'ticket'] as $annotation) {
$this->fixingMap[$annotation] = 'fixWithSingleStringValue';
}
// annotations that map from 'enabled'/'disabled' value to attribute with boolean value
foreach (['backupGlobals', 'backupStaticAttributes', 'preserveGlobalState'] as $annotation) {
$this->fixingMap[$annotation] = 'fixWithEnabledDisabledValue';
}
// annotations that has custom mapping function
$this->fixingMap['covers'] = 'fixCovers';
$this->fixingMap['dataProvider'] = 'fixDataProvider';
$this->fixingMap['depends'] = 'fixDepends';
$this->fixingMap['requires'] = 'fixRequires';
$this->fixingMap['testWith'] = 'fixTestWith';
$this->fixingMap['uses'] = 'fixUses';
}
private static function shouldBeFixed(string $annotationName, string $annotationScope): bool
{
if (
'method' === $annotationScope
&& \in_array($annotationName, ['covers', 'large', 'medium', 'runTestsInSeparateProcesses', 'small', 'uses'], true)
) {
return false;
}
if (
'class' === $annotationScope
&& \in_array($annotationName, ['after', 'afterClass', 'before', 'beforeClass', 'dataProvider', 'depends', 'postCondition', 'preCondition', 'runInSeparateProcess', 'test', 'testWith'], true)
) {
return false;
}
return true;
}
/**
* @param list<Token> $tokensToInsert
*/
private static function isAttributeAlreadyPresent(
FullyQualifiedNameAnalyzer $fullyQualifiedNameAnalyzer,
Tokens $tokens,
int $index,
array $tokensToInsert
): bool {
$attributeIndex = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$attributeIndex]->isGivenKind(\T_ATTRIBUTE)) {
return false;
}
$insertedClassName = '';
foreach (\array_slice($tokensToInsert, 3) as $token) {
if ($token->equals('(') || $token->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) {
break;
}
$insertedClassName .= $token->getContent();
}
foreach (AttributeAnalyzer::collect($tokens, $attributeIndex) as $attributeAnalysis) {
foreach ($attributeAnalysis->getAttributes() as $attribute) {
$className = ltrim(AttributeAnalyzer::determineAttributeFullyQualifiedName($tokens, $attribute['name'], $attribute['start']), '\\');
if ($insertedClassName === $className) {
return true;
}
}
}
return false;
}
/**
* @return non-empty-list<Token>
*/
private static function fixWithoutParameters(Tokens $tokens, int $index, Annotation $annotation): array
{
return self::createAttributeTokens($tokens, $index, self::getAttributeNameForAnnotation($annotation));
}
/**
* @return list<Token>
*/
private static function fixWithSingleStringValue(Tokens $tokens, int $index, Annotation $annotation): array
{
Preg::match(
\sprintf('/@%s\s+(.*\S)(?:\R|\s*\*+\/$)/', $annotation->getTag()->getName()),
$annotation->getContent(),
$matches,
);
if (!isset($matches[1])) {
return [];
}
return self::createAttributeTokens(
$tokens,
$index,
self::getAttributeNameForAnnotation($annotation),
self::createEscapedStringToken($matches[1]),
);
}
/**
* @return list<Token>
*/
private static function fixWithEnabledDisabledValue(Tokens $tokens, int $index, Annotation $annotation): array
{
$matches = self::getMatches($annotation);
if (!isset($matches[1])) {
return [];
}
return self::createAttributeTokens(
$tokens,
$index,
self::getAttributeNameForAnnotation($annotation),
new Token([\T_STRING, isset($matches[1]) && 'enabled' === $matches[1] ? 'true' : 'false']),
);
}
/**
* @return list<Token>
*/
private static function fixCovers(Tokens $tokens, int $index, Annotation $annotation): array
{
$matches = self::getMatches($annotation);
\assert(isset($matches[1]));
if (str_starts_with($matches[1], '::')) {
return self::createAttributeTokens($tokens, $index, 'CoversFunction', self::createEscapedStringToken(substr($matches[1], 2)));
}
if (!str_contains($matches[1], '::')) {
return self::createAttributeTokens(
$tokens,
$index,
'CoversClass',
...self::toClassConstant($matches[1]),
);
}
return [];
}
/**
* @return list<Token>
*/
private static function fixDataProvider(Tokens $tokens, int $index, Annotation $annotation): array
{
$matches = self::getMatches($annotation);
if (!isset($matches[1])) {
return [];
}
if (str_contains($matches[1], '::')) {
// @phpstan-ignore offsetAccess.notFound
[$class, $method] = explode('::', $matches[1]);
return self::createAttributeTokens(
$tokens,
$index,
'DataProviderExternal',
...[
...self::toClassConstant($class),
new Token(','),
new Token([\T_WHITESPACE, ' ']),
self::fixNameAndCreateEscapedStringToken($method),
],
);
}
return self::createAttributeTokens($tokens, $index, 'DataProvider', self::fixNameAndCreateEscapedStringToken($matches[1]));
}
/**
* @see https://github.com/sebastianbergmann/phpunit/blob/11.5.12/src/Metadata/Parser/AnnotationParser.php#L266
*/
private static function fixNameAndCreateEscapedStringToken(string $methodName): Token
{
return self::createEscapedStringToken(rtrim($methodName, " ()\n\r\t\v\x00"));
}
/**
* @return list<Token>
*/
private static function fixDepends(Tokens $tokens, int $index, Annotation $annotation): array
{
$matches = self::getMatches($annotation);
if (!isset($matches[1])) {
return [];
}
$nameSuffix = '';
$depended = $matches[1];
if (isset($matches[2])) {
if ('clone' === $matches[1]) {
$nameSuffix = 'UsingDeepClone';
$depended = $matches[2];
} elseif ('shallowClone' === $matches[1]) {
$nameSuffix = 'UsingShallowClone';
$depended = $matches[2];
}
}
$class = null;
$method = $depended;
if (str_contains($depended, '::')) {
// @phpstan-ignore offsetAccess.notFound
[$class, $method] = explode('::', $depended);
if ('class' === $method) {
$method = null;
$nameSuffix = '' === $nameSuffix ? 'OnClass' : ('OnClass'.$nameSuffix);
} else {
$nameSuffix = ('External'.$nameSuffix);
}
}
$attributeTokens = [];
if (null !== $class) {
$attributeTokens = self::toClassConstant($class);
}
if (null !== $method) {
if ([] !== $attributeTokens) {
$attributeTokens[] = new Token(',');
$attributeTokens[] = new Token([\T_WHITESPACE, ' ']);
}
$attributeTokens[] = self::createEscapedStringToken($method);
}
return self::createAttributeTokens($tokens, $index, 'Depends'.$nameSuffix, ...$attributeTokens);
}
/**
* @return list<Token>
*/
private static function fixRequires(Tokens $tokens, int $index, Annotation $annotation): array
{
$matches = self::getMatches($annotation);
if (!isset($matches[1])) {
return [];
}
$map = [
'extension' => 'RequiresPhpExtension',
'function' => 'RequiresFunction',
'PHP' => 'RequiresPhp',
'PHPUnit' => 'RequiresPhpunit',
'OS' => 'RequiresOperatingSystem',
'OSFAMILY' => 'RequiresOperatingSystemFamily',
'setting' => 'RequiresSetting',
];
if (!isset($matches[2]) || !isset($map[$matches[1]])) {
return [];
}
$attributeName = $map[$matches[1]];
if ('RequiresFunction' === $attributeName && str_contains($matches[2], '::')) {
// @phpstan-ignore offsetAccess.notFound
[$class, $method] = explode('::', $matches[2]);
$attributeName = 'RequiresMethod';
$attributeTokens = [
...self::toClassConstant($class),
new Token(','),
new Token([\T_WHITESPACE, ' ']),
self::createEscapedStringToken($method),
];
} elseif ('RequiresPhp' === $attributeName && isset($matches[3])) {
$attributeTokens = [self::createEscapedStringToken($matches[2].' '.$matches[3])];
} else {
$attributeTokens = [self::createEscapedStringToken(self::fixVersionConstraint($matches[2]))];
}
if (isset($matches[3]) && 'RequiresPhp' !== $attributeName) {
$attributeTokens[] = new Token(',');
$attributeTokens[] = new Token([\T_WHITESPACE, ' ']);
$attributeTokens[] = self::createEscapedStringToken(self::fixVersionConstraint($matches[3]));
}
return self::createAttributeTokens($tokens, $index, $attributeName, ...$attributeTokens);
}
private static function fixVersionConstraint(string $version): string
{
if (Preg::match('/^[\d\.-]+(dev|(RC|alpha|beta)[\d\.])?$/', $version)) {
$version = '>= '.$version;
}
return $version;
}
/**
* @return list<Token>
*/
private static function fixTestWith(Tokens $tokens, int $index, Annotation $annotation): array
{
$content = $annotation->getContent();
$content = Preg::replace('/@testWith\s+/', '', $content);
$content = Preg::replace('/(^|\R)\s+\**\s*/', "\n", $content);
$content = trim($content);
if ('' === $content) {
return [];
}
$attributeTokens = [];
foreach (explode("\n", $content) as $json) {
$attributeTokens = array_merge(
$attributeTokens,
self::createAttributeTokens($tokens, $index, 'TestWithJson', self::createEscapedStringToken($json)),
);
}
return $attributeTokens;
}
/**
* @return list<Token>
*/
private static function fixUses(Tokens $tokens, int $index, Annotation $annotation): array
{
$matches = self::getMatches($annotation);
if (!isset($matches[1])) {
return [];
}
if (str_starts_with($matches[1], '::')) {
$attributeName = 'UsesFunction';
$attributeTokens = [self::createEscapedStringToken(substr($matches[1], 2))];
} elseif (Preg::match('/^[a-zA-Z\d\\\]+$/', $matches[1])) {
$attributeName = 'UsesClass';
$attributeTokens = self::toClassConstant($matches[1]);
} else {
return [];
}
return self::createAttributeTokens($tokens, $index, $attributeName, ...$attributeTokens);
}
/**
* @return list<string>
*/
private static function getMatches(Annotation $annotation): array
{
Preg::match(
\sprintf('/@%s\s+(\S+)(?:\s+(\S+))?(?:\s+(.+\S))?\s*(?:\R|\*+\/$)/', $annotation->getTag()->getName()),
$annotation->getContent(),
$matches,
);
\assert(array_is_list($matches)); // preg_match matches is not well typed, it depends on used regex, let's assure the type to instruct SCA
return $matches;
}
private static function getAttributeNameForAnnotation(Annotation $annotation): string
{
$annotationName = $annotation->getTag()->getName();
return 'backupStaticAttributes' === $annotationName
? 'BackupStaticProperties'
: ucfirst($annotationName);
}
/**
* @return non-empty-list<Token>
*/
private static function createAttributeTokens(
Tokens $tokens,
int $index,
string $className,
Token ...$attributeTokens
): array {
if ([] !== $attributeTokens) {
$attributeTokens = [
new Token('('),
...$attributeTokens,
new Token(')'),
];
}
return [
clone $tokens[$index + 1],
new Token([\T_ATTRIBUTE, '#[']),
new Token([\T_NS_SEPARATOR, '\\']),
new Token([\T_STRING, 'PHPUnit']),
new Token([\T_NS_SEPARATOR, '\\']),
new Token([\T_STRING, 'Framework']),
new Token([\T_NS_SEPARATOR, '\\']),
new Token([\T_STRING, 'Attributes']),
new Token([\T_NS_SEPARATOR, '\\']),
new Token([\T_STRING, $className]),
...$attributeTokens,
new Token([CT::T_ATTRIBUTE_CLOSE, ']']),
];
}
/**
* @param non-empty-string $name
*
* @return list<Token>
*/
private static function toClassConstant(string $name): array
{
return [
...ImportProcessor::tokenizeName($name),
new Token([\T_DOUBLE_COLON, '::']),
new Token([CT::T_CLASS_CONSTANT, 'class']),
];
}
private static function createEscapedStringToken(string $value): Token
{
return new Token([\T_CONSTANT_ENCAPSED_STRING, "'".str_replace("'", "\\'", $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/PhpUnit/PhpUnitTargetVersion.php | src/Fixer/PhpUnit/PhpUnitTargetVersion.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\PhpUnit;
use Composer\Semver\Comparator;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class PhpUnitTargetVersion
{
public const VERSION_3_0 = '3.0';
public const VERSION_3_2 = '3.2';
public const VERSION_3_5 = '3.5';
public const VERSION_4_3 = '4.3';
public const VERSION_4_8 = '4.8';
public const VERSION_5_0 = '5.0';
public const VERSION_5_2 = '5.2';
public const VERSION_5_4 = '5.4';
public const VERSION_5_5 = '5.5';
public const VERSION_5_6 = '5.6';
public const VERSION_5_7 = '5.7';
public const VERSION_6_0 = '6.0';
public const VERSION_7_5 = '7.5';
public const VERSION_8_4 = '8.4';
public const VERSION_9_1 = '9.1';
public const VERSION_10_0 = '10.0';
public const VERSION_11_0 = '11.0';
public const VERSION_NEWEST = 'newest';
private function __construct() {}
public static function fulfills(string $candidate, string $target): bool
{
if (self::VERSION_NEWEST === $target) {
throw new \LogicException(\sprintf('Parameter `target` shall not be provided as "%s", determine proper target for tested PHPUnit feature instead.', self::VERSION_NEWEST));
}
if (self::VERSION_NEWEST === $candidate) {
return true;
}
return Comparator::greaterThanOrEqualTo($candidate, $target);
}
}
| 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/PhpUnit/PhpUnitSizeClassFixer.php | src/Fixer/PhpUnit/PhpUnitSizeClassFixer.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\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
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\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* group?: 'large'|'medium'|'small',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* group: 'large'|'medium'|'small',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Jefersson Nathan <malukenho.dev@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class PhpUnitSizeClassFixer extends AbstractPhpUnitFixer implements WhitespacesAwareFixerInterface, ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private const SIZES = ['small', 'medium', 'large'];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'All PHPUnit test cases should have `@small`, `@medium` or `@large` annotation to enable run time limits.',
[
new CodeSample("<?php\nclass MyTest extends TestCase {}\n"),
new CodeSample("<?php\nclass MyTest extends TestCase {}\n", ['group' => 'medium']),
],
'The special groups [small, medium, large] provides a way to identify tests that are taking long to be executed.',
);
}
/**
* {@inheritdoc}
*
* Must run before PhpUnitAttributesFixer, PhpdocSeparationFixer.
*/
public function getPriority(): int
{
return 9;
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('group', 'Define a specific group to be used in case no group is already in use.'))
->setAllowedValues(self::SIZES)
->setDefault('small')
->getOption(),
]);
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$classIndex = $tokens->getPrevTokenOfKind($startIndex, [[\T_CLASS]]);
if ($this->isAbstractClass($tokens, $classIndex)) {
return;
}
$this->ensureIsDocBlockWithAnnotation(
$tokens,
$classIndex,
$this->configuration['group'],
self::SIZES,
[
'phpunit\framework\attributes\small',
'phpunit\framework\attributes\medium',
'phpunit\framework\attributes\large',
],
);
}
private function isAbstractClass(Tokens $tokens, int $i): bool
{
$typeIndex = $tokens->getPrevMeaningfulToken($i);
return $tokens[$typeIndex]->isGivenKind(\T_ABSTRACT);
}
}
| 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/PhpUnit/PhpUnitNoExpectationAnnotationFixer.php | src/Fixer/PhpUnit/PhpUnitNoExpectationAnnotationFixer.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\PhpUnit;
use PhpCsFixer\DocBlock\Annotation;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* target?: '3.2'|'4.3'|'newest',
* use_class_const?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* target: '3.2'|'4.3'|'newest',
* use_class_const: 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 PhpUnitNoExpectationAnnotationFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private bool $fixMessageRegExp;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Usages of `@expectedException*` annotations MUST be replaced by `->setExpectedException*` methods.',
[
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException FooException
* @expectedExceptionMessageRegExp /foo.*$/
* @expectedExceptionCode 123
*/
function testAaa()
{
aaa();
}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException FooException
* @expectedExceptionCode 123
*/
function testBbb()
{
bbb();
}
/**
* @expectedException FooException
* @expectedExceptionMessageRegExp /foo.*$/
*/
function testCcc()
{
ccc();
}
}
PHP,
['target' => PhpUnitTargetVersion::VERSION_3_2],
),
],
null,
'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.',
);
}
/**
* {@inheritdoc}
*
* Must run before NoEmptyPhpdocFixer, PhpUnitExpectationFixer.
*/
public function getPriority(): int
{
return 10;
}
public function isRisky(): bool
{
return true;
}
protected function configurePostNormalisation(): void
{
$this->fixMessageRegExp = PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_4_3);
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('target', 'Target version of PHPUnit.'))
->setAllowedTypes(['string'])
->setAllowedValues([PhpUnitTargetVersion::VERSION_3_2, PhpUnitTargetVersion::VERSION_4_3, PhpUnitTargetVersion::VERSION_NEWEST])
->setDefault(PhpUnitTargetVersion::VERSION_NEWEST)
->getOption(),
(new FixerOptionBuilder('use_class_const', 'Use ::class notation.'))
->setAllowedTypes(['bool'])
->setDefault(true)
->getOption(),
]);
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
for ($i = $endIndex - 1; $i > $startIndex; --$i) {
if (!$tokens[$i]->isGivenKind(\T_FUNCTION) || $tokensAnalyzer->isLambda($i)) {
continue;
}
$functionIndex = $i;
$docBlockIndex = $i;
// ignore abstract functions
$braceIndex = $tokens->getNextTokenOfKind($functionIndex, [';', '{']);
if (!$tokens[$braceIndex]->equals('{')) {
continue;
}
do {
$docBlockIndex = $tokens->getPrevNonWhitespace($docBlockIndex);
} while ($tokens[$docBlockIndex]->isGivenKind([\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_FINAL, \T_ABSTRACT, \T_COMMENT]));
if (!$tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT)) {
continue;
}
$doc = new DocBlock($tokens[$docBlockIndex]->getContent());
$annotations = [];
foreach ($doc->getAnnotationsOfType([
'expectedException',
'expectedExceptionCode',
'expectedExceptionMessage',
'expectedExceptionMessageRegExp',
]) as $annotation) {
$tag = $annotation->getTag()->getName();
$content = $this->extractContentFromAnnotation($annotation);
$annotations[$tag] = $content;
$annotation->remove();
}
if (!isset($annotations['expectedException'])) {
continue;
}
if (!$this->fixMessageRegExp && isset($annotations['expectedExceptionMessageRegExp'])) {
continue;
}
$originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $docBlockIndex);
$paramList = $this->annotationsToParamList($annotations);
$newMethodsCode = '<?php $this->'
.(isset($annotations['expectedExceptionMessageRegExp']) ? 'setExpectedExceptionRegExp' : 'setExpectedException')
.'('
.implode(', ', $paramList)
.');';
$newMethods = Tokens::fromCode($newMethodsCode);
$newMethods[0] = new Token([
\T_WHITESPACE,
$this->whitespacesConfig->getLineEnding().$originalIndent.$this->whitespacesConfig->getIndent(),
]);
// apply changes
$docContent = $doc->getContent();
if ('' === $docContent) {
$docContent = '/** */';
}
$tokens[$docBlockIndex] = new Token([\T_DOC_COMMENT, $docContent]);
$tokens->insertAt($braceIndex + 1, $newMethods);
$whitespaceIndex = $braceIndex + $newMethods->getSize() + 1;
$tokens[$whitespaceIndex] = new Token([
\T_WHITESPACE,
$this->whitespacesConfig->getLineEnding().$tokens[$whitespaceIndex]->getContent(),
]);
$i = $docBlockIndex;
}
}
private function extractContentFromAnnotation(Annotation $annotation): string
{
$tag = $annotation->getTag()->getName();
if (!Preg::match('/@'.$tag.'\s+(.+)$/s', $annotation->getContent(), $matches)) {
return '';
}
$content = Preg::replace('/\*+\/$/', '', $matches[1]);
if (Preg::match('/\R/u', $content)) {
$content = Preg::replace('/\s*\R+\s*\*\s*/u', ' ', $content);
}
return rtrim($content);
}
/**
* @param array<string, string> $annotations
*
* @return non-empty-list<string>
*/
private function annotationsToParamList(array $annotations): array
{
$params = [];
$exceptionClass = ltrim($annotations['expectedException'], '\\');
if (str_contains($exceptionClass, '*')) {
$exceptionClass = substr($exceptionClass, 0, strpos($exceptionClass, '*'));
}
$exceptionClass = trim($exceptionClass);
if (true === $this->configuration['use_class_const']) {
$params[] = "\\{$exceptionClass}::class";
} else {
$params[] = "'{$exceptionClass}'";
}
if (isset($annotations['expectedExceptionMessage'])) {
$params[] = var_export($annotations['expectedExceptionMessage'], true);
} elseif (isset($annotations['expectedExceptionMessageRegExp'])) {
$params[] = var_export($annotations['expectedExceptionMessageRegExp'], true);
} elseif (isset($annotations['expectedExceptionCode'])) {
$params[] = 'null';
}
if (isset($annotations['expectedExceptionCode'])) {
$params[] = $annotations['expectedExceptionCode'];
}
return $params;
}
}
| 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/PhpUnit/PhpUnitMockFixer.php | src/Fixer/PhpUnit/PhpUnitMockFixer.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\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
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\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* target?: '5.4'|'5.5'|'newest',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* target: '5.4'|'5.5'|'newest',
* }
*
* @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 PhpUnitMockFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private bool $fixCreatePartialMock;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Usages of `->getMock` and `->getMockWithoutInvokingTheOriginalConstructor` methods MUST be replaced by `->createMock` or `->createPartialMock` methods.',
[
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testFoo()
{
$mock = $this->getMockWithoutInvokingTheOriginalConstructor("Foo");
$mock1 = $this->getMock("Foo");
$mock1 = $this->getMock("Bar", ["aaa"]);
$mock1 = $this->getMock("Baz", ["aaa"], ["argument"]); // version with more than 2 params is not supported
}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
public function testFoo()
{
$mock1 = $this->getMock("Foo");
$mock1 = $this->getMock("Bar", ["aaa"]); // version with multiple params is not supported
}
}
PHP,
['target' => PhpUnitTargetVersion::VERSION_5_4],
),
],
null,
'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.',
);
}
public function isRisky(): bool
{
return true;
}
protected function configurePostNormalisation(): void
{
$this->fixCreatePartialMock = PhpUnitTargetVersion::fulfills($this->configuration['target'], PhpUnitTargetVersion::VERSION_5_5);
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$argumentsAnalyzer = new ArgumentsAnalyzer();
for ($index = $startIndex; $index < $endIndex; ++$index) {
if (!$tokens[$index]->isObjectOperator()) {
continue;
}
$index = $tokens->getNextMeaningfulToken($index);
if ($tokens[$index]->equals([\T_STRING, 'getMockWithoutInvokingTheOriginalConstructor'], false)) {
$tokens[$index] = new Token([\T_STRING, 'createMock']);
} elseif ($tokens[$index]->equals([\T_STRING, 'getMock'], false)) {
$openingParenthesis = $tokens->getNextMeaningfulToken($index);
$closingParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openingParenthesis);
$argumentsCount = $argumentsAnalyzer->countArguments($tokens, $openingParenthesis, $closingParenthesis);
if (1 === $argumentsCount) {
$tokens[$index] = new Token([\T_STRING, 'createMock']);
} elseif (2 === $argumentsCount && true === $this->fixCreatePartialMock) {
$tokens[$index] = new Token([\T_STRING, 'createPartialMock']);
}
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('target', 'Target version of PHPUnit.'))
->setAllowedTypes(['string'])
->setAllowedValues([PhpUnitTargetVersion::VERSION_5_4, PhpUnitTargetVersion::VERSION_5_5, PhpUnitTargetVersion::VERSION_NEWEST])
->setDefault(PhpUnitTargetVersion::VERSION_NEWEST)
->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/PhpUnit/PhpUnitDataProviderStaticFixer.php | src/Fixer/PhpUnit/PhpUnitDataProviderStaticFixer.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\PhpUnit;
use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
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\DataProviderAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* force?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* force: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Kuba Werłos <werlos@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class PhpUnitDataProviderStaticFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Data providers must be static.',
[
new CodeSample(
<<<'PHP'
<?php
class FooTest extends TestCase {
/**
* @dataProvider provideSomethingCases
*/
public function testSomething($expected, $actual) {}
public function provideSomethingCases() {}
}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
class FooTest extends TestCase {
/**
* @dataProvider provideSomethingCases1
* @dataProvider provideSomethingCases2
*/
public function testSomething($expected, $actual) {}
public function provideSomethingCases1() { $this->getData1(); }
public function provideSomethingCases2() { self::getData2(); }
}
PHP,
['force' => true],
),
new CodeSample(
<<<'PHP'
<?php
class FooTest extends TestCase {
/**
* @dataProvider provideSomething1Cases
* @dataProvider provideSomething2Cases
*/
public function testSomething($expected, $actual) {}
public function provideSomething1Cases() { $this->getData1(); }
public function provideSomething2Cases() { self::getData2(); }
}
PHP,
['force' => false],
),
],
null,
'Fixer could be risky if one is calling data provider function dynamically.',
);
}
public function isRisky(): bool
{
return true;
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder(
'force',
'Whether to make the data providers static even if they have a dynamic class call'
.' (may introduce fatal error "using $this when not in object context",'
.' and you may have to adjust the code manually by converting dynamic calls to static ones).',
))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
{
$dataProviderAnalyzer = new DataProviderAnalyzer();
$tokensAnalyzer = new TokensAnalyzer($tokens);
$inserts = [];
foreach ($dataProviderAnalyzer->getDataProviders($tokens, $startIndex, $endIndex) as $dataProviderDefinitionIndex) {
$methodStartIndex = $tokens->getNextTokenOfKind($dataProviderDefinitionIndex->getNameIndex(), ['{']);
if (null !== $methodStartIndex) {
$methodEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $methodStartIndex);
if (false === $this->configuration['force'] && null !== $tokens->findSequence([[\T_VARIABLE, '$this']], $methodStartIndex, $methodEndIndex)) {
continue;
}
}
/** @var int $functionIndex */
$functionIndex = $tokens->getPrevTokenOfKind($dataProviderDefinitionIndex->getNameIndex(), [[\T_FUNCTION]]);
$methodAttributes = $tokensAnalyzer->getMethodAttributes($functionIndex);
if (false !== $methodAttributes['static']) {
continue;
}
$inserts[$functionIndex] = [new Token([\T_STATIC, 'static']), new Token([\T_WHITESPACE, ' '])];
}
$tokens->insertSlices($inserts);
}
}
| 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/ConstantNotation/NativeConstantInvocationFixer.php | src/Fixer/ConstantNotation/NativeConstantInvocationFixer.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\ConstantNotation;
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\NamespaceUsesAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* exclude?: list<string>,
* fix_built_in?: bool,
* include?: list<string>,
* scope?: 'all'|'namespaced',
* strict?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* exclude: list<string>,
* fix_built_in: bool,
* include: list<string>,
* scope: 'all'|'namespaced',
* strict: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Filippo Tessarotto <zoeslam@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NativeConstantInvocationFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @var array<string, true>
*/
private array $constantsToEscape = [];
/**
* @var array<string, true>
*/
private array $caseInsensitiveConstantsToEscape = [];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Add leading `\` before constant invocation of internal constant to speed up resolving. Constant name match is case-sensitive, except for `null`, `false` and `true`.',
[
new CodeSample("<?php var_dump(PHP_VERSION, M_PI, MY_CUSTOM_PI);\n"),
new CodeSample(
<<<'PHP'
<?php
namespace space1 {
echo PHP_VERSION;
}
namespace {
echo M_PI;
}
PHP,
['scope' => 'namespaced'],
),
new CodeSample(
"<?php var_dump(PHP_VERSION, M_PI, MY_CUSTOM_PI);\n",
[
'include' => [
'MY_CUSTOM_PI',
],
],
),
new CodeSample(
"<?php var_dump(PHP_VERSION, M_PI, MY_CUSTOM_PI);\n",
[
'fix_built_in' => false,
'include' => [
'MY_CUSTOM_PI',
],
],
),
new CodeSample(
"<?php var_dump(PHP_VERSION, M_PI, MY_CUSTOM_PI);\n",
[
'exclude' => [
'M_PI',
],
],
),
],
null,
'Risky when any of the constants are namespaced or overridden.',
);
}
/**
* {@inheritdoc}
*
* Must run before GlobalNamespaceImportFixer.
* Must run after FunctionToConstantFixer.
*/
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
{
$uniqueConfiguredExclude = array_unique($this->configuration['exclude']);
// Case-sensitive constants handling
$constantsToEscape = array_values($this->configuration['include']);
if (true === $this->configuration['fix_built_in']) {
$getDefinedConstants = get_defined_constants(true);
unset($getDefinedConstants['user']);
foreach ($getDefinedConstants as $constants) {
$constantsToEscape = [...$constantsToEscape, ...array_keys($constants)];
}
}
$constantsToEscape = array_diff(
array_unique($constantsToEscape),
$uniqueConfiguredExclude,
);
// Case-insensitive constants handling
$caseInsensitiveConstantsToEscape = [];
foreach ($constantsToEscape as $constantIndex => $constant) {
$loweredConstant = strtolower($constant);
if (\in_array($loweredConstant, ['null', 'false', 'true'], true)) {
$caseInsensitiveConstantsToEscape[] = $loweredConstant;
unset($constantsToEscape[$constantIndex]);
}
}
$caseInsensitiveConstantsToEscape = array_diff(
array_unique($caseInsensitiveConstantsToEscape),
array_map(
static fn (string $function): string => strtolower($function),
$uniqueConfiguredExclude,
),
);
// Store the cache
$this->constantsToEscape = array_fill_keys($constantsToEscape, true);
ksort($this->constantsToEscape);
$this->caseInsensitiveConstantsToEscape = array_fill_keys($caseInsensitiveConstantsToEscape, true);
ksort($this->caseInsensitiveConstantsToEscape);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
if ('all' === $this->configuration['scope']) {
$this->fixConstantInvocations($tokens, 0, \count($tokens) - 1);
return;
}
$namespaces = $tokens->getNamespaceDeclarations();
// 'scope' is 'namespaced' here
foreach (array_reverse($namespaces) as $namespace) {
if ($namespace->isGlobalNamespace()) {
continue;
}
$this->fixConstantInvocations($tokens, $namespace->getScopeStartIndex(), $namespace->getScopeEndIndex());
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
$constantChecker = static function (array $value): bool {
foreach ($value as $constantName) {
if (trim($constantName) !== $constantName) {
throw new InvalidOptionsException(\sprintf(
'Each element must be a non-empty, trimmed string, got "%s" instead.',
get_debug_type($constantName),
));
}
}
return true;
};
return new FixerConfigurationResolver([
(new FixerOptionBuilder('fix_built_in', 'Whether to fix constants returned by `get_defined_constants`. User constants are not accounted in this list and must be specified in the include one.'))
->setAllowedTypes(['bool'])
->setDefault(true)
->getOption(),
(new FixerOptionBuilder('include', 'List of additional constants to fix.'))
->setAllowedTypes(['string[]'])
->setAllowedValues([$constantChecker])
->setDefault([])
->getOption(),
(new FixerOptionBuilder('exclude', 'List of constants to ignore.'))
->setAllowedTypes(['string[]'])
->setAllowedValues([$constantChecker])
->setDefault(['null', 'false', 'true'])
->getOption(),
(new FixerOptionBuilder('scope', 'Only fix constant invocations that are made within a namespace or fix all.'))
->setAllowedValues(['all', 'namespaced'])
->setDefault('all')
->getOption(),
(new FixerOptionBuilder('strict', 'Whether leading `\` of constant invocation not meant to have it should be removed.'))
->setAllowedTypes(['bool'])
->setDefault(true)
->getOption(),
]);
}
private function fixConstantInvocations(Tokens $tokens, int $startIndex, int $endIndex): void
{
$useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens);
$useConstantDeclarations = [];
foreach ($useDeclarations as $use) {
if ($use->isConstant()) {
$useConstantDeclarations[$use->getShortName()] = true;
}
}
$tokenAnalyzer = new TokensAnalyzer($tokens);
for ($index = $endIndex; $index > $startIndex; --$index) {
$token = $tokens[$index];
// test if we are at a constant call
if (!$token->isGivenKind(\T_STRING)) {
continue;
}
if (!$tokenAnalyzer->isConstantInvocation($index)) {
continue;
}
$tokenContent = $token->getContent();
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if (!isset($this->constantsToEscape[$tokenContent]) && !isset($this->caseInsensitiveConstantsToEscape[strtolower($tokenContent)])) {
if (false === $this->configuration['strict']) {
continue;
}
if (!$tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) {
continue;
}
$prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex);
if ($tokens[$prevPrevIndex]->isGivenKind(\T_STRING)) {
continue;
}
$tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex);
continue;
}
if (isset($useConstantDeclarations[$tokenContent])) {
continue;
}
if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) {
continue;
}
$tokens->insertAt($index, new Token([\T_NS_SEPARATOR, '\\']));
}
}
}
| 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/ArrayNotation/TrimArraySpacesFixer.php | src/Fixer/ArrayNotation/TrimArraySpacesFixer.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\ArrayNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Jared Henderson <jared@netrivet.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class TrimArraySpacesFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Arrays should be formatted like function/method arguments, without leading or trailing single line space.',
[new CodeSample("<?php\n\$sample = array( );\n\$sample = array( 'a', 'b' );\n")],
);
}
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 applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = 0, $c = $tokens->count(); $index < $c; ++$index) {
if ($tokens[$index]->isGivenKind([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN])) {
self::fixArray($tokens, $index);
}
}
}
/**
* Method to trim leading/trailing whitespace within single line arrays.
*/
private static function fixArray(Tokens $tokens, int $index): void
{
$startIndex = $index;
if ($tokens[$startIndex]->isGivenKind(\T_ARRAY)) {
$startIndex = $tokens->getNextMeaningfulToken($startIndex);
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex);
} elseif ($tokens[$startIndex]->isGivenKind(CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN)) {
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_DESTRUCTURING_SQUARE_BRACE, $startIndex);
} else {
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $startIndex);
}
$nextIndex = $startIndex + 1;
$nextToken = $tokens[$nextIndex];
$nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($startIndex);
$nextNonWhitespaceToken = $tokens[$nextNonWhitespaceIndex];
$tokenAfterNextNonWhitespaceToken = $tokens[$nextNonWhitespaceIndex + 1];
$prevIndex = $endIndex - 1;
$prevToken = $tokens[$prevIndex];
$prevNonWhitespaceIndex = $tokens->getPrevNonWhitespace($endIndex);
$prevNonWhitespaceToken = $tokens[$prevNonWhitespaceIndex];
if (
$nextToken->isWhitespace(" \t")
&& (
!$nextNonWhitespaceToken->isComment()
|| $nextNonWhitespaceIndex === $prevNonWhitespaceIndex
|| $tokenAfterNextNonWhitespaceToken->isWhitespace(" \t")
|| str_starts_with($nextNonWhitespaceToken->getContent(), '/*')
)
) {
$tokens->clearAt($nextIndex);
}
if (
$prevToken->isWhitespace(" \t")
&& !$prevNonWhitespaceToken->equals(',')
) {
$tokens->clearAt($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/ArrayNotation/NoWhitespaceBeforeCommaInArrayFixer.php | src/Fixer/ArrayNotation/NoWhitespaceBeforeCommaInArrayFixer.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\ArrayNotation;
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;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* after_heredoc?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* after_heredoc: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Adam Marczuk <adam@marczuk.info>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoWhitespaceBeforeCommaInArrayFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'In array declaration, there MUST NOT be a whitespace before each comma.',
[
new CodeSample("<?php \$x = array(1 , \"2\");\n"),
new CodeSample(
<<<'PHP'
<?php
$x = [<<<EOD
foo
EOD
, 'bar'
];
PHP,
['after_heredoc' => true],
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; $index > 0; --$index) {
if ($tokens[$index]->isGivenKind([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) {
$this->fixSpacing($index, $tokens);
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('after_heredoc', 'Whether the whitespace between heredoc end and comma should be removed.'))
->setAllowedTypes(['bool'])
->setDefault(Future::getV4OrV3(true, false))
->getOption(),
]);
}
/**
* Method to fix spacing in array declaration.
*/
private function fixSpacing(int $index, Tokens $tokens): void
{
if ($tokens[$index]->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) {
$startIndex = $index;
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $startIndex);
} else {
$startIndex = $tokens->getNextTokenOfKind($index, ['(']);
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex);
}
for ($i = $endIndex - 1; $i > $startIndex; --$i) {
$i = $this->skipNonArrayElements($i, $tokens);
$currentToken = $tokens[$i];
$prevIndex = $tokens->getPrevNonWhitespace($i - 1);
if (
$currentToken->equals(',') && !$tokens[$prevIndex]->isComment()
&& (true === $this->configuration['after_heredoc'] || !$tokens[$prevIndex]->isGivenKind(\T_END_HEREDOC))
) {
$tokens->removeLeadingWhitespace($i);
}
}
}
/**
* Method to move index over the non-array elements like function calls or function declarations.
*/
private function skipNonArrayElements(int $index, Tokens $tokens): int
{
if ($tokens[$index]->equals('}')) {
return $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
}
if ($tokens[$index]->equals(')')) {
$startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
$startIndex = $tokens->getPrevMeaningfulToken($startIndex);
if (!$tokens[$startIndex]->isGivenKind([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) {
return $startIndex;
}
}
if ($tokens[$index]->equals(',') && $this->commaIsPartOfImplementsList($index, $tokens)) {
--$index;
}
return $index;
}
private function commaIsPartOfImplementsList(int $index, Tokens $tokens): bool
{
do {
$index = $tokens->getPrevMeaningfulToken($index);
$current = $tokens[$index];
} while ($current->isGivenKind(\T_STRING) || $current->equals(','));
return $current->isGivenKind(\T_IMPLEMENTS);
}
}
| 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/ArrayNotation/ReturnToYieldFromFixer.php | src/Fixer/ArrayNotation/ReturnToYieldFromFixer.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\ArrayNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Kuba Werłos <werlos@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ReturnToYieldFromFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'If the function explicitly returns an array, and has the return type `iterable`, then `yield from` must be used instead of `return`.',
[
new CodeSample(
<<<'PHP'
<?php function giveMeData(): iterable {
return [1, 2, 3];
}
PHP,
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAllTokenKindsFound([\T_FUNCTION, \T_RETURN]) && $tokens->isAnyTokenKindsFound([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]);
}
/**
* {@inheritdoc}
*
* Must run before YieldFromArrayToYieldsFixer.
* Must run after PhpUnitDataProviderReturnTypeFixer, PhpdocToReturnTypeFixer.
*/
public function getPriority(): int
{
return 1;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens->findGivenKind(\T_RETURN) as $index => $token) {
if (!$this->shouldBeFixed($tokens, $index)) {
continue;
}
$tokens[$index] = new Token([\T_YIELD_FROM, 'yield from']);
}
}
private function shouldBeFixed(Tokens $tokens, int $returnIndex): bool
{
$arrayStartIndex = $tokens->getNextMeaningfulToken($returnIndex);
if (!$tokens[$arrayStartIndex]->isGivenKind([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) {
return false;
}
if ($tokens[$arrayStartIndex]->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) {
$arrayEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $arrayStartIndex);
} else {
$arrayOpenParenthesisIndex = $tokens->getNextTokenOfKind($arrayStartIndex, ['(']);
$arrayEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $arrayOpenParenthesisIndex);
}
$functionEndIndex = $arrayEndIndex;
do {
$functionEndIndex = $tokens->getNextMeaningfulToken($functionEndIndex);
} while (null !== $functionEndIndex && $tokens[$functionEndIndex]->equals(';'));
if (null === $functionEndIndex || !$tokens[$functionEndIndex]->equals('}')) {
return false;
}
$functionStartIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $functionEndIndex);
$returnTypeIndex = $tokens->getPrevMeaningfulToken($functionStartIndex);
if (!$tokens[$returnTypeIndex]->isGivenKind(\T_STRING)) {
return false;
}
if ('iterable' !== strtolower($tokens[$returnTypeIndex]->getContent())) {
return false;
}
$beforeReturnTypeIndex = $tokens->getPrevMeaningfulToken($returnTypeIndex);
return $tokens[$beforeReturnTypeIndex]->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/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.php | src/Fixer/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.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\ArrayNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Carlos Cirello <carlos.cirello.nl@gmail.com>
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
* @author Graham Campbell <hello@gjcampbell.co.uk>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoMultilineWhitespaceAroundDoubleArrowFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Operator `=>` should not be surrounded by multi-line whitespaces.',
[new CodeSample("<?php\n\$a = array(1\n\n=> 2);\n")],
);
}
/**
* {@inheritdoc}
*
* Must run before BinaryOperatorSpacesFixer, MethodArgumentSpaceFixer.
*/
public function getPriority(): int
{
return 31;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_DOUBLE_ARROW);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(\T_DOUBLE_ARROW)) {
continue;
}
if (!$tokens[$index - 2]->isComment() || str_starts_with($tokens[$index - 2]->getContent(), '/*')) {
$this->fixWhitespace($tokens, $index - 1);
}
// do not move anything about if there is a comment following the whitespace
if (!$tokens[$index + 2]->isComment()) {
$this->fixWhitespace($tokens, $index + 1);
}
}
}
private function fixWhitespace(Tokens $tokens, int $index): void
{
$token = $tokens[$index];
if ($token->isWhitespace() && !$token->isWhitespace(" \t")) {
$tokens[$index] = new Token([\T_WHITESPACE, rtrim($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/ArrayNotation/YieldFromArrayToYieldsFixer.php | src/Fixer/ArrayNotation/YieldFromArrayToYieldsFixer.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\ArrayNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Kuba Werłos <werlos@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class YieldFromArrayToYieldsFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Yield from array must be unpacked to series of yields.',
[
new CodeSample(
<<<'PHP'
<?php function generate() {
yield from [
1,
2,
3,
];
}
PHP,
),
],
'The conversion will make the array in `yield from` changed in arrays of 1 less dimension.',
'The rule is risky in case of `yield from` being used multiple times within single function scope, while using list-alike data sources (e.g. `function foo() { yield from ["a"]; yield from ["b"]; }`). It only matters when consuming such iterator with key-value context, because set of yielded keys may be changed after applying this rule.',
);
}
public function isRisky(): bool
{
return true;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_YIELD_FROM);
}
/**
* {@inheritdoc}
*
* Must run before BlankLineBeforeStatementFixer, NoExtraBlankLinesFixer, NoMultipleStatementsPerLineFixer, NoWhitespaceInBlankLineFixer, StatementIndentationFixer.
* Must run after ReturnToYieldFromFixer.
*/
public function getPriority(): int
{
return 0;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
/**
* @var array<int, Token> $inserts
*/
$inserts = [];
foreach ($this->getYieldsFromToUnpack($tokens) as $index => [$startIndex, $endIndex]) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
if ($tokens[$startIndex]->equals('(')) {
$prevStartIndex = $tokens->getPrevMeaningfulToken($startIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($prevStartIndex); // clear `array` from `array(`
}
$tokens->clearTokenAndMergeSurroundingWhitespace($startIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($endIndex);
$arrayHasTrailingComma = false;
$startIndex = $tokens->getNextMeaningfulToken($startIndex);
$inserts[$startIndex] = [new Token([\T_YIELD, 'yield']), new Token([\T_WHITESPACE, ' '])];
foreach ($this->findArrayItemCommaIndex(
$tokens,
$startIndex,
$tokens->getPrevMeaningfulToken($endIndex),
) as $commaIndex) {
$nextItemIndex = $tokens->getNextMeaningfulToken($commaIndex);
if ($nextItemIndex < $endIndex) {
$inserts[$nextItemIndex] = [new Token([\T_YIELD, 'yield']), new Token([\T_WHITESPACE, ' '])];
$tokens[$commaIndex] = new Token(';');
} else {
$arrayHasTrailingComma = true;
// array has trailing comma - we replace it with `;` (as it's best fit to put it)
$tokens[$commaIndex] = new Token(';');
}
}
// there was a trailing comma, so we do not need original `;` after initial array structure
if (true === $arrayHasTrailingComma) {
$tokens->clearTokenAndMergeSurroundingWhitespace($tokens->getNextMeaningfulToken($endIndex));
}
}
$tokens->insertSlices($inserts);
}
/**
* @return iterable<int, array{int, int}>
*/
private function getYieldsFromToUnpack(Tokens $tokens): iterable
{
$tokensCount = $tokens->count();
$index = 0;
while (++$index < $tokensCount) {
if (!$tokens[$index]->isGivenKind(\T_YIELD_FROM)) {
continue;
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if (!$tokens[$prevIndex]->equalsAny([';', '{', '}', [\T_OPEN_TAG]])) {
continue;
}
$arrayStartIndex = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$arrayStartIndex]->isGivenKind([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) {
continue;
}
if ($tokens[$arrayStartIndex]->isGivenKind(\T_ARRAY)) {
$startIndex = $tokens->getNextTokenOfKind($arrayStartIndex, ['(']);
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex);
} else {
$startIndex = $arrayStartIndex;
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $startIndex);
}
// is there empty "yield from []" ?
if ($endIndex === $tokens->getNextMeaningfulToken($startIndex)) {
continue;
}
// is there any nested "yield from"?
if ([] !== $tokens->findGivenKind(\T_YIELD_FROM, $startIndex, $endIndex)) {
continue;
}
yield $index => [$startIndex, $endIndex];
}
}
/**
* @return iterable<int>
*/
private function findArrayItemCommaIndex(Tokens $tokens, int $startIndex, int $endIndex): iterable
{
for ($index = $startIndex; $index <= $endIndex; ++$index) {
$token = $tokens[$index];
// skip nested (), [], {} constructs
$blockDefinitionProbe = Tokens::detectBlockType($token);
if (null !== $blockDefinitionProbe && true === $blockDefinitionProbe['isStart']) {
$index = $tokens->findBlockEnd($blockDefinitionProbe['type'], $index);
continue;
}
if (!$tokens[$index]->equals(',')) {
continue;
}
yield $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/ArrayNotation/ArraySyntaxFixer.php | src/Fixer/ArrayNotation/ArraySyntaxFixer.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\ArrayNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* syntax?: 'long'|'short',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* syntax: 'long'|'short',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Gregor Harlan <gharlan@web.de>
* @author Sebastiaan Stok <s.stok@rollerscapes.net>
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ArraySyntaxFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @var CT::T_ARRAY_SQUARE_BRACE_OPEN|T_ARRAY
*/
private $candidateTokenKind;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'PHP arrays should be declared using the configured syntax.',
[
new CodeSample(
"<?php\narray(1,2);\n",
),
new CodeSample(
"<?php\n[1,2];\n",
['syntax' => 'long'],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before BinaryOperatorSpacesFixer, SingleSpaceAfterConstructFixer, SingleSpaceAroundConstructFixer, TernaryOperatorSpacesFixer.
*/
public function getPriority(): int
{
return 37;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound($this->candidateTokenKind);
}
protected function configurePostNormalisation(): void
{
$this->resolveCandidateTokenKind();
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
if ($tokens[$index]->isGivenKind($this->candidateTokenKind)) {
if ('short' === $this->configuration['syntax']) {
$this->fixToShortArraySyntax($tokens, $index);
} else {
$this->fixToLongArraySyntax($tokens, $index);
}
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('syntax', 'Whether to use the `long` or `short` array syntax.'))
->setAllowedValues(['long', 'short'])
->setDefault('short')
->getOption(),
]);
}
private function fixToLongArraySyntax(Tokens $tokens, int $index): void
{
$closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index);
$tokens[$index] = new Token('(');
$tokens[$closeIndex] = new Token(')');
$tokens->insertAt($index, new Token([\T_ARRAY, 'array']));
}
private function fixToShortArraySyntax(Tokens $tokens, int $index): void
{
$openIndex = $tokens->getNextTokenOfKind($index, ['(']);
$closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex);
$tokens[$openIndex] = new Token([CT::T_ARRAY_SQUARE_BRACE_OPEN, '[']);
$tokens[$closeIndex] = new Token([CT::T_ARRAY_SQUARE_BRACE_CLOSE, ']']);
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
private function resolveCandidateTokenKind(): void
{
$this->candidateTokenKind = 'long' === $this->configuration['syntax'] ? CT::T_ARRAY_SQUARE_BRACE_OPEN : \T_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/ArrayNotation/NoTrailingCommaInSinglelineArrayFixer.php | src/Fixer/ArrayNotation/NoTrailingCommaInSinglelineArrayFixer.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\ArrayNotation;
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>
* @author Sebastiaan Stok <s.stok@rollerscapes.net>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoTrailingCommaInSinglelineArrayFixer extends AbstractProxyFixer implements DeprecatedFixerInterface
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'PHP single-line arrays should not have trailing comma.',
[new CodeSample("<?php\n\$a = array('sample', );\n")],
);
}
public function getSuccessorsNames(): array
{
return array_keys($this->proxyFixers);
}
protected function createProxyFixers(): array
{
$fixer = new NoTrailingCommaInSinglelineFixer();
$fixer->configure(['elements' => ['array']]);
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/ArrayNotation/NormalizeIndexBraceFixer.php | src/Fixer/ArrayNotation/NormalizeIndexBraceFixer.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\ArrayNotation;
use PhpCsFixer\AbstractFixer;
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;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NormalizeIndexBraceFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Array index should always be written by using square braces.',
[new VersionSpecificCodeSample(
"<?php\necho \$sample{\$index};\n",
new VersionSpecification(null, 8_04_00 - 1),
)],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if ($token->isGivenKind(CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN)) {
$tokens[$index] = new Token('[');
} elseif ($token->isGivenKind(CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE)) {
$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/ArrayNotation/WhitespaceAfterCommaInArrayFixer.php | src/Fixer/ArrayNotation/WhitespaceAfterCommaInArrayFixer.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\ArrayNotation;
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\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* ensure_single_space?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* ensure_single_space: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Adam Marczuk <adam@marczuk.info>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class WhitespaceAfterCommaInArrayFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'In array declaration, there MUST be a whitespace after each comma.',
[
new CodeSample("<?php\n\$sample = array(1,'a',\$b,);\n"),
new CodeSample("<?php\n\$sample = [1,2, 3, 4, 5];\n", ['ensure_single_space' => true]),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]);
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('ensure_single_space', 'If there are only horizontal whitespaces after the comma then ensure it is a single space.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$tokensToInsert = [];
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
if (!$tokens[$index]->isGivenKind([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) {
continue;
}
if ($tokens[$index]->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) {
$startIndex = $index;
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $startIndex);
} else {
$startIndex = $tokens->getNextTokenOfKind($index, ['(']);
$endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex);
}
for ($i = $endIndex - 1; $i > $startIndex; --$i) {
$i = $this->skipNonArrayElements($i, $tokens);
if (!$tokens[$i]->equals(',')) {
continue;
}
if (!$tokens[$i + 1]->isWhitespace()) {
$tokensToInsert[$i + 1] = new Token([\T_WHITESPACE, ' ']);
} elseif (
true === $this->configuration['ensure_single_space']
&& ' ' !== $tokens[$i + 1]->getContent()
&& Preg::match('/^\h+$/', $tokens[$i + 1]->getContent())
&& (!$tokens[$i + 2]->isComment() || Preg::match('/^\h+$/', $tokens[$i + 3]->getContent()))
) {
$tokens[$i + 1] = new Token([\T_WHITESPACE, ' ']);
}
}
}
if ([] !== $tokensToInsert) {
$tokens->insertSlices($tokensToInsert);
}
}
/**
* Method to move index over the non-array elements like function calls or function declarations.
*
* @return int New index
*/
private function skipNonArrayElements(int $index, Tokens $tokens): int
{
if ($tokens[$index]->equals('}')) {
return $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
}
if ($tokens[$index]->equals(')')) {
$startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
$startIndex = $tokens->getPrevMeaningfulToken($startIndex);
if (!$tokens[$startIndex]->isGivenKind([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) {
return $startIndex;
}
}
if ($tokens[$index]->equals(',') && $this->commaIsPartOfImplementsList($index, $tokens)) {
--$index;
}
return $index;
}
private function commaIsPartOfImplementsList(int $index, Tokens $tokens): bool
{
do {
$index = $tokens->getPrevMeaningfulToken($index);
$current = $tokens[$index];
} while ($current->isGivenKind(\T_STRING) || $current->equals(','));
return $current->isGivenKind(\T_IMPLEMENTS);
}
}
| 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/LanguageConstruct/DeclareParenthesesFixer.php | src/Fixer/LanguageConstruct/DeclareParenthesesFixer.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\LanguageConstruct;
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 DeclareParenthesesFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There must not be spaces around `declare` statement parentheses.',
[new CodeSample("<?php declare ( strict_types=1 );\n")],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_DECLARE);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(\T_DECLARE)) {
continue;
}
$tokens->removeTrailingWhitespace($index);
$startParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(']);
$tokens->removeTrailingWhitespace($startParenthesisIndex);
$endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex);
$tokens->removeLeadingWhitespace($endParenthesisIndex);
}
}
}
| 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/LanguageConstruct/ClassKeywordFixer.php | src/Fixer/LanguageConstruct/ClassKeywordFixer.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\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ExperimentalFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
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 ClassKeywordFixer extends AbstractFixer implements ExperimentalFixerInterface
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Converts FQCN strings to `*::class` keywords.',
[
new CodeSample(
<<<'PHP'
<?php
$foo = 'PhpCsFixer\Tokenizer\Tokens';
$bar = "\PhpCsFixer\Tokenizer\Tokens";
PHP,
),
],
'This rule does not have an understanding of whether a class exists in the scope of the codebase or not, relying on run-time and autoloaded classes to determine it, which makes the rule useless when running on a single file out of codebase context.',
'Do not use it, unless you know what you are doing.',
);
}
/**
* {@inheritdoc}
*
* Must run before FullyQualifiedStrictTypesFixer.
*/
public function getPriority(): int
{
return 8;
}
public function isCandidate(Tokens $tokens): bool
{
return true;
}
public function isRisky(): bool
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if ($token->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) {
$name = substr($token->getContent(), 1, -1);
$name = ltrim($name, '\\');
$name = str_replace('\\\\', '\\', $name);
if ($this->exists($name)) {
$substitution = Tokens::fromCode("<?php echo \\{$name}::class;");
$substitution->clearRange(0, 2);
$substitution->clearAt($substitution->getSize() - 1);
$substitution->clearEmptyTokens();
$tokens->clearAt($index);
$tokens->insertAt($index, $substitution);
}
}
}
}
private function exists(string $name): bool
{
if (class_exists($name) || interface_exists($name) || trait_exists($name)) {
$rc = new \ReflectionClass($name);
return $rc->getName() === $name;
}
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/LanguageConstruct/CombineConsecutiveIssetsFixer.php | src/Fixer/LanguageConstruct/CombineConsecutiveIssetsFixer.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\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class CombineConsecutiveIssetsFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Using `isset($var) &&` multiple times should be done in one call.',
[new CodeSample("<?php\n\$a = isset(\$a) && isset(\$b);\n")],
);
}
/**
* {@inheritdoc}
*
* Must run before MultilineWhitespaceBeforeSemicolonsFixer, NoSinglelineWhitespaceBeforeSemicolonsFixer, NoSpacesInsideParenthesisFixer, NoTrailingWhitespaceFixer, NoWhitespaceInBlankLineFixer, SpacesInsideParenthesesFixer.
*/
public function getPriority(): int
{
return 4;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAllTokenKindsFound([\T_ISSET, \T_BOOLEAN_AND]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$tokenCount = $tokens->count();
for ($index = 1; $index < $tokenCount; ++$index) {
if (!$tokens[$index]->isGivenKind(\T_ISSET)
|| !$tokens[$tokens->getPrevMeaningfulToken($index)]->equalsAny(['(', '{', ';', '=', [\T_OPEN_TAG], [\T_BOOLEAN_AND], [\T_BOOLEAN_OR]])) {
continue;
}
$issetInfo = $this->getIssetInfo($tokens, $index);
$issetCloseBraceIndex = end($issetInfo); // ')' token
$insertLocation = (int) prev($issetInfo) + 1; // one index after the previous meaningful of ')'
$booleanAndTokenIndex = $tokens->getNextMeaningfulToken($issetCloseBraceIndex);
while ($tokens[$booleanAndTokenIndex]->isGivenKind(\T_BOOLEAN_AND)) {
$issetIndex = $tokens->getNextMeaningfulToken($booleanAndTokenIndex);
if (!$tokens[$issetIndex]->isGivenKind(\T_ISSET)) {
$index = $issetIndex;
break;
}
// fetch info about the 'isset' statement that we're merging
$nextIssetInfo = $this->getIssetInfo($tokens, $issetIndex);
$nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken(end($nextIssetInfo));
$nextMeaningfulToken = $tokens[$nextMeaningfulTokenIndex];
if (!$nextMeaningfulToken->equalsAny([')', '}', ';', [\T_CLOSE_TAG], [\T_BOOLEAN_AND], [\T_BOOLEAN_OR]])) {
$index = $nextMeaningfulTokenIndex;
break;
}
// clone what we want to move, do not clone '(' and ')' of the 'isset' statement we're merging
$clones = $this->getTokenClones($tokens, \array_slice($nextIssetInfo, 1, -1));
// clean up now the tokens of the 'isset' statement we're merging
$this->clearTokens($tokens, array_merge($nextIssetInfo, [$issetIndex, $booleanAndTokenIndex]));
// insert the tokens to create the new statement
array_unshift($clones, new Token(','), new Token([\T_WHITESPACE, ' ']));
$tokens->insertAt($insertLocation, $clones);
// correct some counts and offset based on # of tokens inserted
$numberOfTokensInserted = \count($clones);
$tokenCount += $numberOfTokensInserted;
$issetCloseBraceIndex += $numberOfTokensInserted;
$insertLocation += $numberOfTokensInserted;
$booleanAndTokenIndex = $tokens->getNextMeaningfulToken($issetCloseBraceIndex);
}
}
}
/**
* @param list<int> $indices
*/
private function clearTokens(Tokens $tokens, array $indices): void
{
foreach ($indices as $index) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
}
/**
* @param int $index of T_ISSET
*
* @return non-empty-list<int> indices of meaningful tokens belonging to the isset statement
*/
private function getIssetInfo(Tokens $tokens, int $index): array
{
$openIndex = $tokens->getNextMeaningfulToken($index);
$braceOpenCount = 1;
$meaningfulTokenIndices = [$openIndex];
for ($i = $openIndex + 1;; ++$i) {
if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) {
continue;
}
$meaningfulTokenIndices[] = $i;
if ($tokens[$i]->equals(')')) {
--$braceOpenCount;
if (0 === $braceOpenCount) {
break;
}
} elseif ($tokens[$i]->equals('(')) {
++$braceOpenCount;
}
}
return $meaningfulTokenIndices;
}
/**
* @param list<int> $indices
*
* @return list<Token>
*/
private function getTokenClones(Tokens $tokens, array $indices): array
{
$clones = [];
foreach ($indices as $i) {
$clones[] = clone $tokens[$i];
}
return $clones;
}
}
| 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/LanguageConstruct/FunctionToConstantFixer.php | src/Fixer/LanguageConstruct/FunctionToConstantFixer.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\LanguageConstruct;
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\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* functions?: list<'get_called_class'|'get_class'|'get_class_this'|'php_sapi_name'|'phpversion'|'pi'>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* functions: list<'get_called_class'|'get_class'|'get_class_this'|'php_sapi_name'|'phpversion'|'pi'>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class FunctionToConstantFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @var null|array<string, non-empty-list<Token>>
*/
private static ?array $availableFunctions = null;
/**
* @var array<string, non-empty-list<Token>>
*/
private array $functionsFixMap;
public function __construct()
{
if (null === self::$availableFunctions) {
self::$availableFunctions = [
'get_called_class' => [
new Token([\T_STATIC, 'static']),
new Token([\T_DOUBLE_COLON, '::']),
new Token([CT::T_CLASS_CONSTANT, 'class']),
],
'get_class' => [
new Token([\T_STRING, 'self']),
new Token([\T_DOUBLE_COLON, '::']),
new Token([CT::T_CLASS_CONSTANT, 'class']),
],
'get_class_this' => [
new Token([\T_STATIC, 'static']),
new Token([\T_DOUBLE_COLON, '::']),
new Token([CT::T_CLASS_CONSTANT, 'class']),
],
'php_sapi_name' => [new Token([\T_STRING, 'PHP_SAPI'])],
'phpversion' => [new Token([\T_STRING, 'PHP_VERSION'])],
'pi' => [new Token([\T_STRING, 'M_PI'])],
];
}
parent::__construct();
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Replace core functions calls returning constants with the constants.',
[
new CodeSample(
"<?php\necho phpversion();\necho pi();\necho php_sapi_name();\nclass Foo\n{\n public function Bar()\n {\n echo get_class();\n echo get_called_class();\n }\n}\n",
),
new CodeSample(
"<?php\necho phpversion();\necho pi();\nclass Foo\n{\n public function Bar()\n {\n echo get_class();\n get_class(\$this);\n echo get_called_class();\n }\n}\n",
['functions' => ['get_called_class', 'get_class_this', 'phpversion']],
),
],
null,
'Risky when any of the configured functions to replace are overridden.',
);
}
/**
* {@inheritdoc}
*
* Must run before NativeConstantInvocationFixer, NativeFunctionCasingFixer, NoExtraBlankLinesFixer, NoSinglelineWhitespaceBeforeSemicolonsFixer, NoTrailingWhitespaceFixer, NoWhitespaceInBlankLineFixer, SelfStaticAccessorFixer.
* Must run after NoSpacesAfterFunctionNameFixer, NoSpacesInsideParenthesisFixer, SpacesInsideParenthesesFixer.
*/
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 configurePostNormalisation(): void
{
$this->functionsFixMap = [];
foreach ($this->configuration['functions'] as $key) {
$this->functionsFixMap[$key] = self::$availableFunctions[$key];
}
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$functionAnalyzer = new FunctionsAnalyzer();
for ($index = $tokens->count() - 4; $index > 0; --$index) {
$candidate = $this->getReplaceCandidate($tokens, $functionAnalyzer, $index);
if (null === $candidate) {
continue;
}
$this->fixFunctionCallToConstant(
$tokens,
$index,
$candidate[0], // brace open
$candidate[1], // brace close
$candidate[2], // replacement
);
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
$functionNames = array_keys(self::$availableFunctions);
return new FixerConfigurationResolver([
(new FixerOptionBuilder('functions', 'List of function names to fix.'))
->setAllowedTypes(['string[]'])
->setAllowedValues([new AllowedValueSubset($functionNames)])
->setDefault([
'get_called_class',
'get_class',
'get_class_this',
'php_sapi_name',
'phpversion',
'pi',
])
->getOption(),
]);
}
/**
* @param non-empty-list<Token> $replacements
*/
private function fixFunctionCallToConstant(Tokens $tokens, int $index, int $braceOpenIndex, int $braceCloseIndex, array $replacements): void
{
for ($i = $braceCloseIndex; $i >= $braceOpenIndex; --$i) {
if ($tokens[$i]->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) {
continue;
}
$tokens->clearTokenAndMergeSurroundingWhitespace($i);
}
if (
$replacements[0]->isGivenKind([\T_CLASS_C, \T_STATIC])
|| ($replacements[0]->isGivenKind(\T_STRING) && 'self' === $replacements[0]->getContent())
) {
$prevIndex = $tokens->getPrevMeaningfulToken($index);
$prevToken = $tokens[$prevIndex];
if ($prevToken->isGivenKind(\T_NS_SEPARATOR)) {
$tokens->clearAt($prevIndex);
}
}
$tokens->clearAt($index);
$tokens->insertAt($index, $replacements);
}
/**
* @return ?array{int, int, non-empty-list<Token>}
*/
private function getReplaceCandidate(
Tokens $tokens,
FunctionsAnalyzer $functionAnalyzer,
int $index
): ?array {
if (!$tokens[$index]->isGivenKind(\T_STRING)) {
return null;
}
$lowerContent = strtolower($tokens[$index]->getContent());
if ('get_class' === $lowerContent) {
return $this->fixGetClassCall($tokens, $functionAnalyzer, $index);
}
if (!isset($this->functionsFixMap[$lowerContent])) {
return null;
}
if (!$functionAnalyzer->isGlobalFunctionCall($tokens, $index)) {
return null;
}
// test if function call without parameters
$braceOpenIndex = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$braceOpenIndex]->equals('(')) {
return null;
}
$braceCloseIndex = $tokens->getNextMeaningfulToken($braceOpenIndex);
if (!$tokens[$braceCloseIndex]->equals(')')) {
return null;
}
return $this->getReplacementTokenClones($lowerContent, $braceOpenIndex, $braceCloseIndex);
}
/**
* @return ?array{int, int, non-empty-list<Token>}
*/
private function fixGetClassCall(
Tokens $tokens,
FunctionsAnalyzer $functionAnalyzer,
int $index
): ?array {
if (!isset($this->functionsFixMap['get_class']) && !isset($this->functionsFixMap['get_class_this'])) {
return null;
}
if (!$functionAnalyzer->isGlobalFunctionCall($tokens, $index)) {
return null;
}
$braceOpenIndex = $tokens->getNextMeaningfulToken($index);
$braceCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $braceOpenIndex);
if ($braceCloseIndex === $tokens->getNextMeaningfulToken($braceOpenIndex)) { // no arguments passed
if (isset($this->functionsFixMap['get_class'])) {
return $this->getReplacementTokenClones('get_class', $braceOpenIndex, $braceCloseIndex);
}
} elseif (isset($this->functionsFixMap['get_class_this'])) {
$isThis = false;
for ($i = $braceOpenIndex + 1; $i < $braceCloseIndex; ++$i) {
if ($tokens[$i]->equalsAny([[\T_WHITESPACE], [\T_COMMENT], [\T_DOC_COMMENT], ')'])) {
continue;
}
if ($tokens[$i]->isGivenKind(\T_VARIABLE) && '$this' === strtolower($tokens[$i]->getContent())) {
$isThis = true;
continue;
}
if (false === $isThis && $tokens[$i]->equals('(')) {
continue;
}
$isThis = false;
break;
}
if ($isThis) {
return $this->getReplacementTokenClones('get_class_this', $braceOpenIndex, $braceCloseIndex);
}
}
return null;
}
/**
* @return array{int, int, non-empty-list<Token>}
*/
private function getReplacementTokenClones(string $lowerContent, int $braceOpenIndex, int $braceCloseIndex): array
{
$clones = array_map(
static fn (Token $token): Token => clone $token,
$this->functionsFixMap[$lowerContent],
);
return [
$braceOpenIndex,
$braceCloseIndex,
$clones,
];
}
}
| 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/LanguageConstruct/IsNullFixer.php | src/Fixer/LanguageConstruct/IsNullFixer.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\LanguageConstruct;
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 Vladimir Reznichenko <kalessil@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class IsNullFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Replaces `is_null($var)` expression with `null === $var`.',
[
new CodeSample("<?php\n\$a = is_null(\$b);\n"),
],
null,
'Risky when the function `is_null` is overridden.',
);
}
/**
* {@inheritdoc}
*
* Must run before YodaStyleFixer.
*/
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 applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$functionsAnalyzer = new FunctionsAnalyzer();
$currIndex = 0;
while (true) {
// recalculate "end" because we might have added tokens in previous iteration
$matches = $tokens->findSequence([[\T_STRING, 'is_null'], '('], $currIndex, $tokens->count() - 1, false);
// stop looping if didn't find any new matches
if (null === $matches) {
break;
}
// 0 and 1 accordingly are "is_null", "(" tokens
$matches = array_keys($matches);
// move the cursor just after the sequence
[$isNullIndex, $currIndex] = $matches;
if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $matches[0])) {
continue;
}
$next = $tokens->getNextMeaningfulToken($currIndex);
if ($tokens[$next]->equals(')')) {
continue;
}
$prevTokenIndex = $tokens->getPrevMeaningfulToken($matches[0]);
// handle function references with namespaces
if ($tokens[$prevTokenIndex]->isGivenKind(\T_NS_SEPARATOR)) {
$tokens->removeTrailingWhitespace($prevTokenIndex);
$tokens->clearAt($prevTokenIndex);
$prevTokenIndex = $tokens->getPrevMeaningfulToken($prevTokenIndex);
}
// check if inversion being used, text comparison is due to not existing constant
$isInvertedNullCheck = false;
if ($tokens[$prevTokenIndex]->equals('!')) {
$isInvertedNullCheck = true;
// get rid of inverting for proper transformations
$tokens->removeTrailingWhitespace($prevTokenIndex);
$tokens->clearAt($prevTokenIndex);
}
// before getting rind of `()` around a parameter, ensure it's not assignment/ternary invariant
$referenceEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $matches[1]);
$isContainingDangerousConstructs = false;
for ($paramTokenIndex = $matches[1]; $paramTokenIndex <= $referenceEnd; ++$paramTokenIndex) {
if (\in_array($tokens[$paramTokenIndex]->getContent(), ['?', '?:', '=', '??'], true)) {
$isContainingDangerousConstructs = true;
break;
}
}
// edge cases: is_null() followed/preceded by ==, ===, !=, !==, <>, (int-or-other-casting)
$parentLeftToken = $tokens[$tokens->getPrevMeaningfulToken($isNullIndex)];
$parentRightToken = $tokens[$tokens->getNextMeaningfulToken($referenceEnd)];
$parentOperations = [\T_IS_EQUAL, \T_IS_NOT_EQUAL, \T_IS_IDENTICAL, \T_IS_NOT_IDENTICAL];
$wrapIntoParentheses = $parentLeftToken->isCast() || $parentLeftToken->isGivenKind($parentOperations) || $parentRightToken->isGivenKind($parentOperations);
// possible trailing comma removed
$prevIndex = $tokens->getPrevMeaningfulToken($referenceEnd);
if ($tokens[$prevIndex]->equals(',')) {
$tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex);
}
if (!$isContainingDangerousConstructs) {
// closing parenthesis removed with leading spaces
$tokens->removeLeadingWhitespace($referenceEnd);
$tokens->clearAt($referenceEnd);
// opening parenthesis removed with trailing spaces
$tokens->removeLeadingWhitespace($matches[1]);
$tokens->removeTrailingWhitespace($matches[1]);
$tokens->clearAt($matches[1]);
}
// sequence which we'll use as a replacement
$replacement = [
new Token([\T_STRING, 'null']),
new Token([\T_WHITESPACE, ' ']),
new Token($isInvertedNullCheck ? [\T_IS_NOT_IDENTICAL, '!=='] : [\T_IS_IDENTICAL, '===']),
new Token([\T_WHITESPACE, ' ']),
];
if ($wrapIntoParentheses) {
array_unshift($replacement, new Token('('));
$tokens->insertAt($referenceEnd + 1, new Token(')'));
}
$tokens->overrideRange($isNullIndex, $isNullIndex, $replacement);
// nested is_null calls support
$currIndex = $isNullIndex;
}
}
}
| 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/LanguageConstruct/NoUnsetOnPropertyFixer.php | src/Fixer/LanguageConstruct/NoUnsetOnPropertyFixer.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\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _UnsetInfo array{
* startIndex: int,
* endIndex: int,
* isToTransform: bool,
* isFirst: bool,
* }
*
* @author Gert de Pagter <BackEndTea@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoUnsetOnPropertyFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Properties should be set to `null` instead of using `unset`.',
[new CodeSample("<?php\nunset(\$this->a);\n")],
null,
'Risky when relying on attributes to be removed using `unset` rather than be set to `null`.'
.' Changing variables to `null` instead of unsetting means these still show up when looping over class variables'
.' and reference properties remain unbroken.'
.' Since PHP 7.4, this rule might introduce `null` assignments to properties whose type declaration does not allow it.',
);
}
public function isRisky(): bool
{
return true;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_UNSET)
&& $tokens->isAnyTokenKindsFound([\T_OBJECT_OPERATOR, \T_PAAMAYIM_NEKUDOTAYIM]);
}
/**
* {@inheritdoc}
*
* Must run before CombineConsecutiveUnsetsFixer.
*/
public function getPriority(): int
{
return 25;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
if (!$tokens[$index]->isGivenKind(\T_UNSET)) {
continue;
}
$unsetsInfo = $this->getUnsetsInfo($tokens, $index);
if (!$this->isAnyUnsetToTransform($unsetsInfo)) {
continue;
}
$isLastUnset = true; // "last" as we reverse the array below
foreach (array_reverse($unsetsInfo) as $unsetInfo) {
$this->updateTokens($tokens, $unsetInfo, $isLastUnset);
$isLastUnset = false;
}
}
}
/**
* @return list<_UnsetInfo>
*/
private function getUnsetsInfo(Tokens $tokens, int $index): array
{
$argumentsAnalyzer = new ArgumentsAnalyzer();
$unsetStart = $tokens->getNextTokenOfKind($index, ['(']);
$unsetEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $unsetStart);
$isFirst = true;
$unsets = [];
foreach ($argumentsAnalyzer->getArguments($tokens, $unsetStart, $unsetEnd) as $startIndex => $endIndex) {
$startIndex = $tokens->getNextMeaningfulToken($startIndex - 1);
$endIndex = $tokens->getPrevMeaningfulToken($endIndex + 1);
$unsets[] = [
'startIndex' => $startIndex,
'endIndex' => $endIndex,
'isToTransform' => $this->isProperty($tokens, $startIndex, $endIndex),
'isFirst' => $isFirst,
];
$isFirst = false;
}
return $unsets;
}
private function isProperty(Tokens $tokens, int $index, int $endIndex): bool
{
if ($tokens[$index]->isGivenKind(\T_VARIABLE)) {
$nextIndex = $tokens->getNextMeaningfulToken($index);
if (null === $nextIndex || !$tokens[$nextIndex]->isGivenKind(\T_OBJECT_OPERATOR)) {
return false;
}
$nextIndex = $tokens->getNextMeaningfulToken($nextIndex);
$nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex);
if (null !== $nextNextIndex && $nextNextIndex < $endIndex) {
return false;
}
return null !== $nextIndex && $tokens[$nextIndex]->isGivenKind(\T_STRING);
}
if ($tokens[$index]->isGivenKind([\T_NS_SEPARATOR, \T_STRING])) {
$nextIndex = $tokens->getTokenNotOfKindsSibling($index, 1, [\T_DOUBLE_COLON, \T_NS_SEPARATOR, \T_STRING]);
$nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex);
if (null !== $nextNextIndex && $nextNextIndex < $endIndex) {
return false;
}
return null !== $nextIndex && $tokens[$nextIndex]->isGivenKind(\T_VARIABLE);
}
return false;
}
/**
* @param list<_UnsetInfo> $unsetsInfo
*/
private function isAnyUnsetToTransform(array $unsetsInfo): bool
{
foreach ($unsetsInfo as $unsetInfo) {
if ($unsetInfo['isToTransform']) {
return true;
}
}
return false;
}
/**
* @param _UnsetInfo $unsetInfo
*/
private function updateTokens(Tokens $tokens, array $unsetInfo, bool $isLastUnset): void
{
// if entry is first and to be transformed we remove leading "unset("
if ($unsetInfo['isFirst'] && $unsetInfo['isToTransform']) {
$braceIndex = $tokens->getPrevTokenOfKind($unsetInfo['startIndex'], ['(']);
$unsetIndex = $tokens->getPrevTokenOfKind($braceIndex, [[\T_UNSET]]);
$tokens->clearTokenAndMergeSurroundingWhitespace($braceIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($unsetIndex);
}
// if entry is last and to be transformed we remove trailing ")"
if ($isLastUnset && $unsetInfo['isToTransform']) {
$braceIndex = $tokens->getNextTokenOfKind($unsetInfo['endIndex'], [')']);
$previousIndex = $tokens->getPrevMeaningfulToken($braceIndex);
if ($tokens[$previousIndex]->equals(',')) {
$tokens->clearTokenAndMergeSurroundingWhitespace($previousIndex); // trailing ',' in function call (PHP 7.3)
}
$tokens->clearTokenAndMergeSurroundingWhitespace($braceIndex);
}
// if entry is not last we replace comma with semicolon (last entry already has semicolon - from original unset)
if (!$isLastUnset) {
$commaIndex = $tokens->getNextTokenOfKind($unsetInfo['endIndex'], [',']);
$tokens[$commaIndex] = new Token(';');
}
// if entry is to be unset and is not last we add trailing ")"
if (!$unsetInfo['isToTransform'] && !$isLastUnset) {
$tokens->insertAt($unsetInfo['endIndex'] + 1, new Token(')'));
}
// if entry is to be unset and is not first we add leading "unset("
if (!$unsetInfo['isToTransform'] && !$unsetInfo['isFirst']) {
$tokens->insertAt(
$unsetInfo['startIndex'],
[
new Token([\T_UNSET, 'unset']),
new Token('('),
],
);
}
// and finally
// if entry is to be transformed we add trailing " = null"
if ($unsetInfo['isToTransform']) {
$tokens->insertAt(
$unsetInfo['endIndex'] + 1,
[
new Token([\T_WHITESPACE, ' ']),
new Token('='),
new Token([\T_WHITESPACE, ' ']),
new Token([\T_STRING, 'null']),
],
);
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/LanguageConstruct/GetClassToClassKeywordFixer.php | src/Fixer/LanguageConstruct/GetClassToClassKeywordFixer.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\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
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 GetClassToClassKeywordFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Replace `get_class` calls on object variables with class keyword syntax.',
[
new VersionSpecificCodeSample(
"<?php\nget_class(\$a);\n",
new VersionSpecification(8_00_00),
),
new VersionSpecificCodeSample(
"<?php\n\n\$date = new \\DateTimeImmutable();\n\$class = get_class(\$date);\n",
new VersionSpecification(8_00_00),
),
],
null,
'Risky if the `get_class` function is overridden.',
);
}
/**
* {@inheritdoc}
*
* Must run before MultilineWhitespaceBeforeSemicolonsFixer.
* Must run after NoSpacesAfterFunctionNameFixer, NoSpacesInsideParenthesisFixer, SpacesInsideParenthesesFixer.
*/
public function getPriority(): int
{
return 1;
}
public function isCandidate(Tokens $tokens): bool
{
return \PHP_VERSION_ID >= 8_00_00 && $tokens->isAllTokenKindsFound([\T_STRING, \T_VARIABLE]);
}
public function isRisky(): bool
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$functionsAnalyzer = new FunctionsAnalyzer();
$indicesToClear = [];
$tokenSlices = [];
for ($index = $tokens->count() - 1; $index > 0; --$index) {
if (!$tokens[$index]->equals([\T_STRING, 'get_class'], false)) {
continue;
}
if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) {
continue;
}
$braceOpenIndex = $tokens->getNextMeaningfulToken($index);
$braceCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $braceOpenIndex);
if ($braceCloseIndex === $tokens->getNextMeaningfulToken($braceOpenIndex)) {
continue; // get_class with no arguments
}
$meaningfulTokensCount = 0;
$variableTokensIndices = [];
for ($i = $braceOpenIndex + 1; $i < $braceCloseIndex; ++$i) {
if (!$tokens[$i]->equalsAny([[\T_WHITESPACE], [\T_COMMENT], [\T_DOC_COMMENT], '(', ')'])) {
++$meaningfulTokensCount;
}
if (!$tokens[$i]->isGivenKind(\T_VARIABLE)) {
continue;
}
if ('$this' === strtolower($tokens[$i]->getContent())) {
continue 2; // get_class($this)
}
$variableTokensIndices[] = $i;
}
if ($meaningfulTokensCount > 1 || 1 !== \count($variableTokensIndices)) {
continue; // argument contains more logic, or more arguments, or no variable argument
}
$indicesToClear[$index] = [$braceOpenIndex, current($variableTokensIndices), $braceCloseIndex];
}
foreach ($indicesToClear as $index => $items) {
$tokenSlices[$index] = $this->getReplacementTokenSlices($tokens, $items[1]);
$this->clearGetClassCall($tokens, $index, $items[0], $items[2]);
}
$tokens->insertSlices($tokenSlices);
}
/**
* @return non-empty-list<Token>
*/
private function getReplacementTokenSlices(Tokens $tokens, int $variableIndex): array
{
return [
new Token([\T_VARIABLE, $tokens[$variableIndex]->getContent()]),
new Token([\T_DOUBLE_COLON, '::']),
new Token([CT::T_CLASS_CONSTANT, 'class']),
];
}
private function clearGetClassCall(Tokens $tokens, int $index, int $braceOpenIndex, int $braceCloseIndex): void
{
for ($i = $braceOpenIndex; $i <= $braceCloseIndex; ++$i) {
if ($tokens[$i]->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) {
continue;
}
$tokens->clearTokenAndMergeSurroundingWhitespace($i);
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) {
$tokens->clearAt($prevIndex);
}
$tokens->clearAt($index);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/LanguageConstruct/NullableTypeDeclarationFixer.php | src/Fixer/LanguageConstruct/NullableTypeDeclarationFixer.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\LanguageConstruct;
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\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* syntax?: 'question_mark'|'union',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* syntax: 'question_mark'|'union',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author John Paul E. Balandan, CPA <paulbalandan@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NullableTypeDeclarationFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private const OPTION_SYNTAX_UNION = 'union';
private const OPTION_SYNTAX_QUESTION_MARK = 'question_mark';
private const PROPERTY_MODIFIERS = [\T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC, \T_ABSTRACT, \T_FINAL, \T_VAR, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET];
private int $candidateTokenKind;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Nullable single type declaration should be standardised using configured syntax.',
[
new VersionSpecificCodeSample(
<<<'PHP'
<?php
function bar(null|int $value, null|\Closure $callable): int|null {}
PHP,
new VersionSpecification(8_00_00),
),
new VersionSpecificCodeSample(
<<<'PHP'
<?php
function baz(?int $value, ?\stdClass $obj, ?array $config): ?int {}
PHP,
new VersionSpecification(8_00_00),
['syntax' => self::OPTION_SYNTAX_UNION],
),
new VersionSpecificCodeSample(
<<<'PHP'
<?php
class ValueObject
{
public null|string $name;
public ?int $count;
public null|bool $internal;
public null|\Closure $callback;
}
PHP,
new VersionSpecification(8_00_00),
['syntax' => self::OPTION_SYNTAX_QUESTION_MARK],
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return \PHP_VERSION_ID >= 8_00_00 && $tokens->isTokenKindFound($this->candidateTokenKind);
}
/**
* {@inheritdoc}
*
* Must run before OrderedTypesFixer, TypesSpacesFixer.
* Must run after NullableTypeDeclarationForDefaultNullValueFixer.
*/
public function getPriority(): int
{
return 2;
}
protected function configurePostNormalisation(): void
{
$this->candidateTokenKind = self::OPTION_SYNTAX_QUESTION_MARK === $this->configuration['syntax']
? CT::T_TYPE_ALTERNATION // `|` -> `?`
: CT::T_NULLABLE_TYPE; // `?` -> `|`
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('syntax', 'Whether to use question mark (`?`) or explicit `null` union for nullable type.'))
->setAllowedValues([self::OPTION_SYNTAX_UNION, self::OPTION_SYNTAX_QUESTION_MARK])
->setDefault(self::OPTION_SYNTAX_QUESTION_MARK)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$functionsAnalyzer = new FunctionsAnalyzer();
foreach (array_reverse($this->getElements($tokens), true) as $index => $type) {
if ('property' === $type) {
$this->normalizePropertyType($tokens, $index);
continue;
}
$this->normalizeMethodReturnType($functionsAnalyzer, $tokens, $index);
$this->normalizeMethodArgumentType($functionsAnalyzer, $tokens, $index);
}
}
/**
* @return array<int, string>
*
* @phpstan-return array<int, 'function'|'property'>
*/
private function getElements(Tokens $tokens): array
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
$elements = array_map(
static fn (array $element): string => 'method' === $element['type'] ? 'function' : $element['type'],
array_filter(
$tokensAnalyzer->getClassyElements(),
static fn (array $element): bool => \in_array($element['type'], ['method', 'property'], true),
),
);
foreach ($tokens as $index => $token) {
if (
$token->isGivenKind(\T_FN)
|| ($token->isGivenKind(\T_FUNCTION) && !isset($elements[$index]))
) {
$elements[$index] = 'function';
}
}
return $elements;
}
private function collectTypeAnalysis(Tokens $tokens, int $startIndex, int $endIndex): ?TypeAnalysis
{
$type = '';
$typeStartIndex = $tokens->getNextMeaningfulToken($startIndex);
$typeEndIndex = $typeStartIndex;
for ($i = $typeStartIndex; $i < $endIndex; ++$i) {
if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) {
continue;
}
$type .= $tokens[$i]->getContent();
$typeEndIndex = $i;
}
return '' !== $type ? new TypeAnalysis($type, $typeStartIndex, $typeEndIndex) : null;
}
private function isTypeNormalizable(TypeAnalysis $typeAnalysis): bool
{
$type = $typeAnalysis->getName();
if ('null' === strtolower($type) || !$typeAnalysis->isNullable()) {
return false;
}
if (str_contains($type, '&')) {
return false; // skip DNF types
}
if (!str_contains($type, '|')) {
return true;
}
return 1 === substr_count($type, '|') && Preg::match('/(?:\|null$|^null\|)/i', $type);
}
private function normalizePropertyType(Tokens $tokens, int $index): void
{
$propertyEndIndex = $index;
do {
$index = $tokens->getPrevMeaningfulToken($index);
} while (!$tokens[$index]->isGivenKind(self::PROPERTY_MODIFIERS));
$propertyType = $this->collectTypeAnalysis($tokens, $index, $propertyEndIndex);
if (null === $propertyType || !$this->isTypeNormalizable($propertyType)) {
return;
}
$this->normalizeNullableType($tokens, $propertyType);
}
private function normalizeMethodArgumentType(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index): void
{
foreach (array_reverse($functionsAnalyzer->getFunctionArguments($tokens, $index), true) as $argumentInfo) {
$argumentType = $argumentInfo->getTypeAnalysis();
if (null === $argumentType || !$this->isTypeNormalizable($argumentType)) {
continue;
}
$this->normalizeNullableType($tokens, $argumentType);
}
}
private function normalizeMethodReturnType(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index): void
{
$returnType = $functionsAnalyzer->getFunctionReturnType($tokens, $index);
if (null === $returnType || !$this->isTypeNormalizable($returnType)) {
return;
}
$this->normalizeNullableType($tokens, $returnType);
}
private function normalizeNullableType(Tokens $tokens, TypeAnalysis $typeAnalysis): void
{
$type = $typeAnalysis->getName();
if (!str_contains($type, '|') && !str_contains($type, '&')) {
$type = ($typeAnalysis->isNullable() ? '?' : '').$type;
}
$isQuestionMarkSyntax = self::OPTION_SYNTAX_QUESTION_MARK === $this->configuration['syntax'];
if ($isQuestionMarkSyntax) {
$normalizedType = $this->convertToNullableType($type);
$normalizedTypeAsString = implode('', $normalizedType);
} else {
$normalizedType = $this->convertToExplicitUnionType($type);
$normalizedTypeAsString = implode('|', $normalizedType);
}
if ($normalizedTypeAsString === $type) {
return; // nothing to fix
}
$tokens->overrideRange(
$typeAnalysis->getStartIndex(),
$typeAnalysis->getEndIndex(),
$this->createTypeDeclarationTokens($normalizedType, $isQuestionMarkSyntax),
);
$prevStartIndex = $typeAnalysis->getStartIndex() - 1;
if (!$tokens[$prevStartIndex]->isWhitespace() && !$tokens[$prevStartIndex]->equals('(')) {
$tokens->ensureWhitespaceAtIndex($prevStartIndex, 1, ' ');
}
}
/**
* @return array{0: string, 1?: string}
*/
private function convertToNullableType(string $type): array
{
if (str_starts_with($type, '?')) {
return [$type]; // no need to convert; already fixed
}
return ['?', Preg::replace('/(?:\|null$|^null\|)/i', '', $type)];
}
/**
* @return array{0: string, 1?: string}
*/
private function convertToExplicitUnionType(string $type): array
{
if (str_contains($type, '|')) {
return [$type]; // no need to convert; already fixed
}
return ['null', substr($type, 1)];
}
/**
* @param list<string> $types
*
* @return list<Token>
*/
private function createTypeDeclarationTokens(array $types, bool $isQuestionMarkSyntax): array
{
$count = \count($types);
$newTokens = [];
foreach ($types as $index => $type) {
$specialType = [
'?' => CT::T_NULLABLE_TYPE,
'array' => CT::T_ARRAY_TYPEHINT,
'callable' => \T_CALLABLE,
'static' => \T_STATIC,
][strtolower($type)] ?? null;
if (null !== $specialType) {
$newTokens[] = new Token([$specialType, $type]);
} else {
foreach (explode('\\', $type) as $nsIndex => $value) {
if (0 === $nsIndex && '' === $value) {
continue;
}
if ($nsIndex > 0) {
$newTokens[] = new Token([\T_NS_SEPARATOR, '\\']);
}
$newTokens[] = new Token([\T_STRING, $value]);
}
}
if ($index <= $count - 2 && !$isQuestionMarkSyntax) {
$newTokens[] = new Token([CT::T_TYPE_ALTERNATION, '|']);
}
}
return $newTokens;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/LanguageConstruct/SingleSpaceAfterConstructFixer.php | src/Fixer/LanguageConstruct/SingleSpaceAfterConstructFixer.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\LanguageConstruct;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
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;
/**
* @deprecated
*
* @phpstan-type _AutogeneratedInputConfiguration array{
* constructs?: list<'abstract'|'as'|'attribute'|'break'|'case'|'catch'|'class'|'clone'|'comment'|'const'|'const_import'|'continue'|'do'|'echo'|'else'|'elseif'|'enum'|'extends'|'final'|'finally'|'for'|'foreach'|'function'|'function_import'|'global'|'goto'|'if'|'implements'|'include'|'include_once'|'instanceof'|'insteadof'|'interface'|'match'|'named_argument'|'namespace'|'new'|'open_tag_with_echo'|'php_doc'|'php_open'|'print'|'private'|'protected'|'public'|'readonly'|'require'|'require_once'|'return'|'static'|'switch'|'throw'|'trait'|'try'|'type_colon'|'use'|'use_lambda'|'use_trait'|'var'|'while'|'yield'|'yield_from'>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* constructs: list<'abstract'|'as'|'attribute'|'break'|'case'|'catch'|'class'|'clone'|'comment'|'const'|'const_import'|'continue'|'do'|'echo'|'else'|'elseif'|'enum'|'extends'|'final'|'finally'|'for'|'foreach'|'function'|'function_import'|'global'|'goto'|'if'|'implements'|'include'|'include_once'|'instanceof'|'insteadof'|'interface'|'match'|'named_argument'|'namespace'|'new'|'open_tag_with_echo'|'php_doc'|'php_open'|'print'|'private'|'protected'|'public'|'readonly'|'require'|'require_once'|'return'|'static'|'switch'|'throw'|'trait'|'try'|'type_colon'|'use'|'use_lambda'|'use_trait'|'var'|'while'|'yield'|'yield_from'>,
* }
*
* @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 SingleSpaceAfterConstructFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, DeprecatedFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @var array<string, null|int>
*/
private const TOKEN_MAP = [
'abstract' => \T_ABSTRACT,
'as' => \T_AS,
'attribute' => CT::T_ATTRIBUTE_CLOSE,
'break' => \T_BREAK,
'case' => \T_CASE,
'catch' => \T_CATCH,
'class' => \T_CLASS,
'clone' => \T_CLONE,
'comment' => \T_COMMENT,
'const' => \T_CONST,
'const_import' => CT::T_CONST_IMPORT,
'continue' => \T_CONTINUE,
'do' => \T_DO,
'echo' => \T_ECHO,
'else' => \T_ELSE,
'elseif' => \T_ELSEIF,
'enum' => null,
'extends' => \T_EXTENDS,
'final' => \T_FINAL,
'finally' => \T_FINALLY,
'for' => \T_FOR,
'foreach' => \T_FOREACH,
'function' => \T_FUNCTION,
'function_import' => CT::T_FUNCTION_IMPORT,
'global' => \T_GLOBAL,
'goto' => \T_GOTO,
'if' => \T_IF,
'implements' => \T_IMPLEMENTS,
'include' => \T_INCLUDE,
'include_once' => \T_INCLUDE_ONCE,
'instanceof' => \T_INSTANCEOF,
'insteadof' => \T_INSTEADOF,
'interface' => \T_INTERFACE,
'match' => null,
'named_argument' => CT::T_NAMED_ARGUMENT_COLON,
'namespace' => \T_NAMESPACE,
'new' => \T_NEW,
'open_tag_with_echo' => \T_OPEN_TAG_WITH_ECHO,
'php_doc' => \T_DOC_COMMENT,
'php_open' => \T_OPEN_TAG,
'print' => \T_PRINT,
'private' => \T_PRIVATE,
'protected' => \T_PROTECTED,
'public' => \T_PUBLIC,
'readonly' => null,
'require' => \T_REQUIRE,
'require_once' => \T_REQUIRE_ONCE,
'return' => \T_RETURN,
'static' => \T_STATIC,
'switch' => \T_SWITCH,
'throw' => \T_THROW,
'trait' => \T_TRAIT,
'try' => \T_TRY,
'type_colon' => CT::T_TYPE_COLON,
'use' => \T_USE,
'use_lambda' => CT::T_USE_LAMBDA,
'use_trait' => CT::T_USE_TRAIT,
'var' => \T_VAR,
'while' => \T_WHILE,
'yield' => \T_YIELD,
'yield_from' => \T_YIELD_FROM,
];
private SingleSpaceAroundConstructFixer $singleSpaceAroundConstructFixer;
public function __construct()
{
$this->singleSpaceAroundConstructFixer = new SingleSpaceAroundConstructFixer();
parent::__construct();
}
public function getSuccessorsNames(): array
{
return array_keys($this->proxyFixers);
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Ensures a single space after language constructs.',
[
new CodeSample(
<<<'PHP'
<?php
throw new \Exception();
PHP,
),
new CodeSample(
<<<'PHP'
<?php
echo "Hello!";
PHP,
[
'constructs' => [
'echo',
],
],
),
new CodeSample(
<<<'PHP'
<?php
yield from baz();
PHP,
[
'constructs' => [
'yield_from',
],
],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before BracesFixer, FunctionDeclarationFixer.
* Must run after ArraySyntaxFixer, ModernizeStrposFixer.
*/
public function getPriority(): int
{
return parent::getPriority();
}
protected function configurePostNormalisation(): void
{
$this->singleSpaceAroundConstructFixer->configure([
'constructs_contain_a_single_space' => [
'yield_from',
],
'constructs_preceded_by_a_single_space' => [],
'constructs_followed_by_a_single_space' => $this->configuration['constructs'],
]);
}
protected function createProxyFixers(): array
{
return [$this->singleSpaceAroundConstructFixer];
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
$defaults = self::TOKEN_MAP;
$tokens = array_keys($defaults);
unset($defaults['type_colon']);
return new FixerConfigurationResolver([
(new FixerOptionBuilder('constructs', 'List of constructs which must be followed by a single space.'))
->setAllowedTypes(['string[]'])
->setAllowedValues([new AllowedValueSubset($tokens)])
->setDefault(array_keys($defaults))
->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/LanguageConstruct/DirConstantFixer.php | src/Fixer/LanguageConstruct/DirConstantFixer.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\LanguageConstruct;
use PhpCsFixer\AbstractFunctionReferenceFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Vladimir Reznichenko <kalessil@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class DirConstantFixer extends AbstractFunctionReferenceFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Replaces `dirname(__FILE__)` expression with equivalent `__DIR__` constant.',
[new CodeSample("<?php\n\$a = dirname(__FILE__);\n")],
null,
'Risky when the function `dirname` is overridden.',
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAllTokenKindsFound([\T_STRING, \T_FILE]);
}
/**
* {@inheritdoc}
*
* Must run before CombineNestedDirnameFixer.
*/
public function getPriority(): int
{
return 40;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$currIndex = 0;
do {
$boundaries = $this->find('dirname', $tokens, $currIndex, $tokens->count() - 1);
if (null === $boundaries) {
return;
}
[$functionNameIndex, $openParenthesis, $closeParenthesis] = $boundaries;
// analysing cursor shift, so nested expressions kept processed
$currIndex = $openParenthesis;
// ensure __FILE__ is in between (...)
$fileCandidateRightIndex = $tokens->getPrevMeaningfulToken($closeParenthesis);
$trailingCommaIndex = null;
if ($tokens[$fileCandidateRightIndex]->equals(',')) {
$trailingCommaIndex = $fileCandidateRightIndex;
$fileCandidateRightIndex = $tokens->getPrevMeaningfulToken($fileCandidateRightIndex);
}
$fileCandidateRight = $tokens[$fileCandidateRightIndex];
if (!$fileCandidateRight->isGivenKind(\T_FILE)) {
continue;
}
$fileCandidateLeftIndex = $tokens->getNextMeaningfulToken($openParenthesis);
$fileCandidateLeft = $tokens[$fileCandidateLeftIndex];
if (!$fileCandidateLeft->isGivenKind(\T_FILE)) {
continue;
}
// get rid of root namespace when it used
$namespaceCandidateIndex = $tokens->getPrevMeaningfulToken($functionNameIndex);
$namespaceCandidate = $tokens[$namespaceCandidateIndex];
if ($namespaceCandidate->isGivenKind(\T_NS_SEPARATOR)) {
$tokens->removeTrailingWhitespace($namespaceCandidateIndex);
$tokens->clearAt($namespaceCandidateIndex);
}
if (null !== $trailingCommaIndex) {
if (!$tokens[$tokens->getNextNonWhitespace($trailingCommaIndex)]->isComment()) {
$tokens->removeTrailingWhitespace($trailingCommaIndex);
}
$tokens->clearTokenAndMergeSurroundingWhitespace($trailingCommaIndex);
}
// closing parenthesis removed with leading spaces
if (!$tokens[$tokens->getNextNonWhitespace($closeParenthesis)]->isComment()) {
$tokens->removeLeadingWhitespace($closeParenthesis);
}
$tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesis);
// opening parenthesis removed with trailing and leading spaces
if (!$tokens[$tokens->getNextNonWhitespace($openParenthesis)]->isComment()) {
$tokens->removeLeadingWhitespace($openParenthesis);
}
$tokens->removeTrailingWhitespace($openParenthesis);
$tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesis);
// replace constant and remove function name
$tokens[$fileCandidateLeftIndex] = new Token([\T_DIR, '__DIR__']);
$tokens->clearTokenAndMergeSurroundingWhitespace($functionNameIndex);
} while (null !== $currIndex);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/LanguageConstruct/SingleSpaceAroundConstructFixer.php | src/Fixer/LanguageConstruct/SingleSpaceAroundConstructFixer.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\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* constructs_contain_a_single_space?: list<'yield_from'>,
* constructs_followed_by_a_single_space?: list<'abstract'|'as'|'attribute'|'break'|'case'|'catch'|'class'|'clone'|'comment'|'const'|'const_import'|'continue'|'do'|'echo'|'else'|'elseif'|'enum'|'extends'|'final'|'finally'|'for'|'foreach'|'function'|'function_import'|'global'|'goto'|'if'|'implements'|'include'|'include_once'|'instanceof'|'insteadof'|'interface'|'match'|'named_argument'|'namespace'|'new'|'open_tag_with_echo'|'php_doc'|'php_open'|'print'|'private'|'private_set'|'protected'|'protected_set'|'public'|'public_set'|'readonly'|'require'|'require_once'|'return'|'static'|'switch'|'throw'|'trait'|'try'|'type_colon'|'use'|'use_lambda'|'use_trait'|'var'|'while'|'yield'|'yield_from'>,
* constructs_preceded_by_a_single_space?: list<'as'|'else'|'elseif'|'use_lambda'>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* constructs_contain_a_single_space: list<'yield_from'>,
* constructs_followed_by_a_single_space: list<'abstract'|'as'|'attribute'|'break'|'case'|'catch'|'class'|'clone'|'comment'|'const'|'const_import'|'continue'|'do'|'echo'|'else'|'elseif'|'enum'|'extends'|'final'|'finally'|'for'|'foreach'|'function'|'function_import'|'global'|'goto'|'if'|'implements'|'include'|'include_once'|'instanceof'|'insteadof'|'interface'|'match'|'named_argument'|'namespace'|'new'|'open_tag_with_echo'|'php_doc'|'php_open'|'print'|'private'|'private_set'|'protected'|'protected_set'|'public'|'public_set'|'readonly'|'require'|'require_once'|'return'|'static'|'switch'|'throw'|'trait'|'try'|'type_colon'|'use'|'use_lambda'|'use_trait'|'var'|'while'|'yield'|'yield_from'>,
* constructs_preceded_by_a_single_space: list<'as'|'else'|'elseif'|'use_lambda'>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Andreas Möller <am@localheinz.com>
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class SingleSpaceAroundConstructFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @var array<string, int>
*/
private const TOKEN_MAP_CONTAIN_A_SINGLE_SPACE = [
// for now, only one case - but we are ready to extend it, when we learn about new cases to cover
'yield_from' => \T_YIELD_FROM,
];
/**
* @var array<string, int>
*/
private const TOKEN_MAP_PRECEDED_BY_A_SINGLE_SPACE = [
'as' => \T_AS,
'else' => \T_ELSE,
'elseif' => \T_ELSEIF,
'use_lambda' => CT::T_USE_LAMBDA,
];
/**
* @var array<string, int>
*/
private const TOKEN_MAP_FOLLOWED_BY_A_SINGLE_SPACE = [
'abstract' => \T_ABSTRACT,
'as' => \T_AS,
'attribute' => CT::T_ATTRIBUTE_CLOSE,
'break' => \T_BREAK,
'case' => \T_CASE,
'catch' => \T_CATCH,
'class' => \T_CLASS,
'clone' => \T_CLONE,
'comment' => \T_COMMENT,
'const' => \T_CONST,
'const_import' => CT::T_CONST_IMPORT,
'continue' => \T_CONTINUE,
'do' => \T_DO,
'echo' => \T_ECHO,
'else' => \T_ELSE,
'elseif' => \T_ELSEIF,
'enum' => FCT::T_ENUM,
'extends' => \T_EXTENDS,
'final' => \T_FINAL,
'finally' => \T_FINALLY,
'for' => \T_FOR,
'foreach' => \T_FOREACH,
'function' => \T_FUNCTION,
'function_import' => CT::T_FUNCTION_IMPORT,
'global' => \T_GLOBAL,
'goto' => \T_GOTO,
'if' => \T_IF,
'implements' => \T_IMPLEMENTS,
'include' => \T_INCLUDE,
'include_once' => \T_INCLUDE_ONCE,
'instanceof' => \T_INSTANCEOF,
'insteadof' => \T_INSTEADOF,
'interface' => \T_INTERFACE,
'match' => FCT::T_MATCH,
'named_argument' => CT::T_NAMED_ARGUMENT_COLON,
'namespace' => \T_NAMESPACE,
'new' => \T_NEW,
'open_tag_with_echo' => \T_OPEN_TAG_WITH_ECHO,
'php_doc' => \T_DOC_COMMENT,
'php_open' => \T_OPEN_TAG,
'print' => \T_PRINT,
'private' => \T_PRIVATE,
'private_set' => FCT::T_PRIVATE_SET,
'protected' => \T_PROTECTED,
'protected_set' => FCT::T_PROTECTED_SET,
'public' => \T_PUBLIC,
'public_set' => FCT::T_PUBLIC_SET,
'readonly' => FCT::T_READONLY,
'require' => \T_REQUIRE,
'require_once' => \T_REQUIRE_ONCE,
'return' => \T_RETURN,
'static' => \T_STATIC,
'switch' => \T_SWITCH,
'throw' => \T_THROW,
'trait' => \T_TRAIT,
'try' => \T_TRY,
'type_colon' => CT::T_TYPE_COLON,
'use' => \T_USE,
'use_lambda' => CT::T_USE_LAMBDA,
'use_trait' => CT::T_USE_TRAIT,
'var' => \T_VAR,
'while' => \T_WHILE,
'yield' => \T_YIELD,
'yield_from' => \T_YIELD_FROM,
];
/**
* @var array<string, int>
*/
private array $fixTokenMapFollowedByASingleSpace = [];
/**
* @var array<string, int>
*/
private array $fixTokenMapContainASingleSpace = [];
/**
* @var array<string, int>
*/
private array $fixTokenMapPrecededByASingleSpace = [];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Ensures a single space after language constructs.',
[
new CodeSample(
<<<'PHP'
<?php
throw new \Exception();
PHP,
),
new CodeSample(
<<<'PHP'
<?php
function foo() { yield from baz(); }
PHP,
[
'constructs_contain_a_single_space' => [
'yield_from',
],
'constructs_followed_by_a_single_space' => [
'yield_from',
],
],
),
new CodeSample(
<<<'PHP'
<?php
$foo = function& ()use($bar) {
};
PHP,
[
'constructs_preceded_by_a_single_space' => [
'use_lambda',
],
'constructs_followed_by_a_single_space' => [
'use_lambda',
],
],
),
new CodeSample(
<<<'PHP'
<?php
echo "Hello!";
PHP,
[
'constructs_followed_by_a_single_space' => [
'echo',
],
],
),
new CodeSample(
<<<'PHP'
<?php
yield from baz();
PHP,
[
'constructs_followed_by_a_single_space' => [
'yield_from',
],
],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before BracesFixer, FunctionDeclarationFixer.
* Must run after ArraySyntaxFixer, ModernizeStrposFixer.
*/
public function getPriority(): int
{
return 36;
}
public function isCandidate(Tokens $tokens): bool
{
$tokenKinds = [
...array_values($this->fixTokenMapContainASingleSpace),
...array_values($this->fixTokenMapPrecededByASingleSpace),
...array_values($this->fixTokenMapFollowedByASingleSpace),
];
return $tokens->isAnyTokenKindsFound($tokenKinds);
}
protected function configurePostNormalisation(): void
{
$this->fixTokenMapContainASingleSpace = [];
foreach ($this->configuration['constructs_contain_a_single_space'] as $key) {
$this->fixTokenMapContainASingleSpace[$key] = self::TOKEN_MAP_CONTAIN_A_SINGLE_SPACE[$key];
}
$this->fixTokenMapPrecededByASingleSpace = [];
foreach ($this->configuration['constructs_preceded_by_a_single_space'] as $key) {
$this->fixTokenMapPrecededByASingleSpace[$key] = self::TOKEN_MAP_PRECEDED_BY_A_SINGLE_SPACE[$key];
}
$this->fixTokenMapFollowedByASingleSpace = [];
foreach ($this->configuration['constructs_followed_by_a_single_space'] as $key) {
$this->fixTokenMapFollowedByASingleSpace[$key] = self::TOKEN_MAP_FOLLOWED_BY_A_SINGLE_SPACE[$key];
}
if (isset($this->fixTokenMapFollowedByASingleSpace['public'])) {
$this->fixTokenMapFollowedByASingleSpace['constructor_public'] = CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC;
}
if (isset($this->fixTokenMapFollowedByASingleSpace['protected'])) {
$this->fixTokenMapFollowedByASingleSpace['constructor_protected'] = CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED;
}
if (isset($this->fixTokenMapFollowedByASingleSpace['private'])) {
$this->fixTokenMapFollowedByASingleSpace['constructor_private'] = CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE;
}
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$tokenKindsContainASingleSpace = array_values($this->fixTokenMapContainASingleSpace);
for ($index = $tokens->count() - 1; $index > 0; --$index) {
if ($tokens[$index]->isGivenKind($tokenKindsContainASingleSpace)) {
$token = $tokens[$index];
if (
$token->isGivenKind(\T_YIELD_FROM)
&& 'yield from' !== strtolower($token->getContent())
) {
$tokens[$index] = new Token([\T_YIELD_FROM, Preg::replace(
'/\s+/',
' ',
$token->getContent(),
)]);
}
}
}
$tokenKindsPrecededByASingleSpace = array_values($this->fixTokenMapPrecededByASingleSpace);
for ($index = $tokens->count() - 1; $index > 0; --$index) {
if ($tokens[$index]->isGivenKind($tokenKindsPrecededByASingleSpace)) {
if (!$this->isFullLineCommentBefore($tokens, $index)) {
$tokens->ensureWhitespaceAtIndex($index - 1, 1, ' ');
}
}
}
$tokenKindsFollowedByASingleSpace = array_values($this->fixTokenMapFollowedByASingleSpace);
for ($index = $tokens->count() - 2; $index >= 0; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind($tokenKindsFollowedByASingleSpace)) {
continue;
}
$whitespaceTokenIndex = $index + 1;
if ($tokens[$whitespaceTokenIndex]->equalsAny([',', ':', ';', ')', [CT::T_ARRAY_SQUARE_BRACE_CLOSE], [CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE]])) {
continue;
}
if (
$token->isGivenKind(\T_STATIC)
&& !$tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind([\T_FN, \T_FUNCTION, \T_NS_SEPARATOR, \T_STRING, \T_VARIABLE, CT::T_ARRAY_TYPEHINT, CT::T_NULLABLE_TYPE])
) {
continue;
}
if ($token->isGivenKind(\T_OPEN_TAG)) {
if ($tokens[$whitespaceTokenIndex]->isGivenKind(\T_WHITESPACE) && !str_contains($tokens[$whitespaceTokenIndex]->getContent(), "\n") && !str_contains($token->getContent(), "\n")) {
$tokens->clearAt($whitespaceTokenIndex);
}
continue;
}
if ($token->isGivenKind(\T_CLASS) && $tokens[$tokens->getNextMeaningfulToken($index)]->equals('(')) {
continue;
}
if ($token->isGivenKind([\T_EXTENDS, \T_IMPLEMENTS]) && $this->isMultilineExtendsOrImplementsWithMoreThanOneAncestor($tokens, $index)) {
continue;
}
if ($token->isGivenKind(\T_RETURN) && $this->isMultiLineReturn($tokens, $index)) {
continue;
}
if ($token->isGivenKind(\T_CONST) && $this->isMultilineCommaSeparatedConstant($tokens, $index)) {
continue;
}
if ($token->isComment() || $token->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) {
if ($tokens[$whitespaceTokenIndex]->isGivenKind(\T_WHITESPACE) && str_contains($tokens[$whitespaceTokenIndex]->getContent(), "\n")) {
continue;
}
}
if ($tokens[$whitespaceTokenIndex]->isWhitespace() && str_contains($tokens[$whitespaceTokenIndex]->getContent(), "\n")) {
$nextNextToken = $tokens[$whitespaceTokenIndex + 1];
if (
$nextNextToken->isGivenKind(FCT::T_ATTRIBUTE)
|| $nextNextToken->isComment() && str_starts_with($nextNextToken->getContent(), '#[')
) {
continue;
}
if ($nextNextToken->isGivenKind(\T_DOC_COMMENT)) {
continue;
}
}
$tokens->ensureWhitespaceAtIndex($whitespaceTokenIndex, 0, ' ');
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
$tokenMapContainASingleSpaceKeys = array_keys(self::TOKEN_MAP_CONTAIN_A_SINGLE_SPACE);
$tokenMapPrecededByASingleSpaceKeys = array_keys(self::TOKEN_MAP_PRECEDED_BY_A_SINGLE_SPACE);
$tokenMapFollowedByASingleSpaceKeys = array_keys(self::TOKEN_MAP_FOLLOWED_BY_A_SINGLE_SPACE);
return new FixerConfigurationResolver([
(new FixerOptionBuilder('constructs_contain_a_single_space', 'List of constructs which must contain a single space.'))
->setAllowedTypes(['string[]'])
->setAllowedValues([new AllowedValueSubset($tokenMapContainASingleSpaceKeys)])
->setDefault($tokenMapContainASingleSpaceKeys)
->getOption(),
(new FixerOptionBuilder('constructs_preceded_by_a_single_space', 'List of constructs which must be preceded by a single space.'))
->setAllowedTypes(['string[]'])
->setAllowedValues([new AllowedValueSubset($tokenMapPrecededByASingleSpaceKeys)])
->setDefault(['as', 'use_lambda'])
->getOption(),
(new FixerOptionBuilder('constructs_followed_by_a_single_space', 'List of constructs which must be followed by a single space.'))
->setAllowedTypes(['string[]'])
->setAllowedValues([new AllowedValueSubset($tokenMapFollowedByASingleSpaceKeys)])
->setDefault($tokenMapFollowedByASingleSpaceKeys)
->getOption(),
]);
}
private function isMultiLineReturn(Tokens $tokens, int $index): bool
{
++$index;
$tokenFollowingReturn = $tokens[$index];
if (
!$tokenFollowingReturn->isGivenKind(\T_WHITESPACE)
|| !str_contains($tokenFollowingReturn->getContent(), "\n")
) {
return false;
}
$nestedCount = 0;
for ($indexEnd = \count($tokens) - 1, ++$index; $index < $indexEnd; ++$index) {
if (str_contains($tokens[$index]->getContent(), "\n")) {
return true;
}
if ($tokens[$index]->equals('{')) {
++$nestedCount;
} elseif ($tokens[$index]->equals('}')) {
--$nestedCount;
} elseif (0 === $nestedCount && $tokens[$index]->equalsAny([';', [\T_CLOSE_TAG]])) {
break;
}
}
return false;
}
private function isMultilineExtendsOrImplementsWithMoreThanOneAncestor(Tokens $tokens, int $index): bool
{
$hasMoreThanOneAncestor = false;
while (true) {
++$index;
$token = $tokens[$index];
if ($token->equals(',')) {
$hasMoreThanOneAncestor = true;
continue;
}
if ($token->equals('{')) {
return false;
}
if ($hasMoreThanOneAncestor && str_contains($token->getContent(), "\n")) {
return true;
}
}
return LogicException('Not reachable code was reached.'); // @phpstan-ignore deadCode.unreachable
}
private function isMultilineCommaSeparatedConstant(Tokens $tokens, int $constantIndex): bool
{
$isMultilineConstant = false;
$hasMoreThanOneConstant = false;
$index = $constantIndex;
while (!$tokens[$index]->equalsAny([';', [\T_CLOSE_TAG]])) {
++$index;
$isMultilineConstant = $isMultilineConstant || str_contains($tokens[$index]->getContent(), "\n");
if ($tokens[$index]->equals(',')) {
$hasMoreThanOneConstant = true;
}
$blockType = Tokens::detectBlockType($tokens[$index]);
if (null !== $blockType && true === $blockType['isStart']) {
$index = $tokens->findBlockEnd($blockType['type'], $index);
}
}
return $hasMoreThanOneConstant && $isMultilineConstant;
}
private function isFullLineCommentBefore(Tokens $tokens, int $index): bool
{
$beforeIndex = $tokens->getPrevNonWhitespace($index);
if (!$tokens[$beforeIndex]->isGivenKind(\T_COMMENT)) {
return false;
}
$content = $tokens[$beforeIndex]->getContent();
return str_starts_with($content, '#') || str_starts_with($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/LanguageConstruct/DeclareEqualNormalizeFixer.php | src/Fixer/LanguageConstruct/DeclareEqualNormalizeFixer.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\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* space?: 'none'|'single',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* space: 'none'|'single',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class DeclareEqualNormalizeFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Equal sign in declare statement should be surrounded by spaces or not following configuration.',
[
new CodeSample("<?php\ndeclare(ticks = 1);\n"),
new CodeSample("<?php\ndeclare(ticks=1);\n", ['space' => 'single']),
],
);
}
/**
* {@inheritdoc}
*
* Must run after DeclareStrictTypesFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_DECLARE);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = 0, $count = $tokens->count(); $index < $count - 6; ++$index) {
if (!$tokens[$index]->isGivenKind(\T_DECLARE)) {
continue;
}
$openParenthesisIndex = $tokens->getNextMeaningfulToken($index);
$closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesisIndex);
for ($i = $closeParenthesisIndex; $i > $openParenthesisIndex; --$i) {
if ($tokens[$i]->equals('=')) {
if ('none' === $this->configuration['space']) {
$this->removeWhitespaceAroundToken($tokens, $i);
} else {
$this->ensureWhitespaceAroundToken($tokens, $i);
}
}
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('space', 'Spacing to apply around the equal sign.'))
->setAllowedValues(['single', 'none'])
->setDefault('none')
->getOption(),
]);
}
/**
* @param int $index of `=` token
*/
private function ensureWhitespaceAroundToken(Tokens $tokens, int $index): void
{
if ($tokens[$index + 1]->isWhitespace()) {
if (' ' !== $tokens[$index + 1]->getContent()) {
$tokens[$index + 1] = new Token([\T_WHITESPACE, ' ']);
}
} else {
$tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' ']));
}
if ($tokens[$index - 1]->isWhitespace()) {
if (' ' !== $tokens[$index - 1]->getContent() && !$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) {
$tokens[$index - 1] = new Token([\T_WHITESPACE, ' ']);
}
} else {
$tokens->insertAt($index, new Token([\T_WHITESPACE, ' ']));
}
}
/**
* @param int $index of `=` token
*/
private function removeWhitespaceAroundToken(Tokens $tokens, int $index): void
{
if (!$tokens[$tokens->getPrevNonWhitespace($index)]->isComment()) {
$tokens->removeLeadingWhitespace($index);
}
$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/LanguageConstruct/ErrorSuppressionFixer.php | src/Fixer/LanguageConstruct/ErrorSuppressionFixer.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\LanguageConstruct;
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;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* mute_deprecation_error?: bool,
* noise_remaining_usages?: bool,
* noise_remaining_usages_exclude?: list<string>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* mute_deprecation_error: bool,
* noise_remaining_usages: bool,
* noise_remaining_usages_exclude: list<string>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Jules Pietri <jules@heahprod.com>
* @author Kuba Werłos <werlos@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ErrorSuppressionFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @internal
*/
public const OPTION_MUTE_DEPRECATION_ERROR = 'mute_deprecation_error';
/**
* @internal
*/
public const OPTION_NOISE_REMAINING_USAGES = 'noise_remaining_usages';
/**
* @internal
*/
public const OPTION_NOISE_REMAINING_USAGES_EXCLUDE = 'noise_remaining_usages_exclude';
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Error control operator should be added to deprecation notices and/or removed from other cases.',
[
new CodeSample("<?php\ntrigger_error('Warning.', E_USER_DEPRECATED);\n"),
new CodeSample(
"<?php\n@mkdir(\$dir);\n@unlink(\$path);\n",
[self::OPTION_NOISE_REMAINING_USAGES => true],
),
new CodeSample(
"<?php\n@mkdir(\$dir);\n@unlink(\$path);\n",
[
self::OPTION_NOISE_REMAINING_USAGES => true,
self::OPTION_NOISE_REMAINING_USAGES_EXCLUDE => ['unlink'],
],
),
],
null,
'Risky because adding/removing `@` might cause changes to code behaviour or if `trigger_error` function is overridden.',
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_STRING);
}
public function isRisky(): bool
{
return true;
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder(self::OPTION_MUTE_DEPRECATION_ERROR, 'Whether to add `@` in deprecation notices.'))
->setAllowedTypes(['bool'])
->setDefault(true)
->getOption(),
(new FixerOptionBuilder(self::OPTION_NOISE_REMAINING_USAGES, 'Whether to remove `@` in remaining usages.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
(new FixerOptionBuilder(self::OPTION_NOISE_REMAINING_USAGES_EXCLUDE, 'List of global functions to exclude from removing `@`.'))
->setAllowedTypes(['string[]'])
->setDefault([])
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$functionsAnalyzer = new FunctionsAnalyzer();
$excludedFunctions = array_map(static fn (string $function): string => strtolower($function), $this->configuration[self::OPTION_NOISE_REMAINING_USAGES_EXCLUDE]);
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if (true === $this->configuration[self::OPTION_NOISE_REMAINING_USAGES] && $token->equals('@')) {
$tokens->clearAt($index);
continue;
}
if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) {
continue;
}
$functionIndex = $index;
$startIndex = $index;
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) {
$startIndex = $prevIndex;
$prevIndex = $tokens->getPrevMeaningfulToken($startIndex);
}
$index = $prevIndex;
if ($this->isDeprecationErrorCall($tokens, $functionIndex)) {
if (false === $this->configuration[self::OPTION_MUTE_DEPRECATION_ERROR]) {
continue;
}
if ($tokens[$prevIndex]->equals('@')) {
continue;
}
$tokens->insertAt($startIndex, new Token('@'));
continue;
}
if (!$tokens[$prevIndex]->equals('@')) {
continue;
}
if (true === $this->configuration[self::OPTION_NOISE_REMAINING_USAGES] && !\in_array($tokens[$functionIndex]->getContent(), $excludedFunctions, true)) {
$tokens->clearAt($index);
}
}
}
private function isDeprecationErrorCall(Tokens $tokens, int $index): bool
{
if ('trigger_error' !== strtolower($tokens[$index]->getContent())) {
return false;
}
$endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextTokenOfKind($index, [[\T_STRING], '(']));
$prevIndex = $tokens->getPrevMeaningfulToken($endBraceIndex);
if ($tokens[$prevIndex]->equals(',')) {
$prevIndex = $tokens->getPrevMeaningfulToken($prevIndex);
}
return $tokens[$prevIndex]->equals([\T_STRING, 'E_USER_DEPRECATED']);
}
}
| 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/LanguageConstruct/ExplicitIndirectVariableFixer.php | src/Fixer/LanguageConstruct/ExplicitIndirectVariableFixer.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\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Filippo Tessarotto <zoeslam@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ExplicitIndirectVariableFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Add curly braces to indirect variables to make them clear to understand.',
[
new CodeSample(
<<<'EOT'
<?php
echo $$foo;
echo $$foo['bar'];
echo $foo->$bar['baz'];
echo $foo->$callback($baz);
EOT,
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_VARIABLE);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; $index > 1; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(\T_VARIABLE)) {
continue;
}
$prevIndex = $tokens->getPrevMeaningfulToken($index);
$prevToken = $tokens[$prevIndex];
if (!$prevToken->equals('$') && !$prevToken->isObjectOperator()) {
continue;
}
$openingBrace = CT::T_DYNAMIC_VAR_BRACE_OPEN;
$closingBrace = CT::T_DYNAMIC_VAR_BRACE_CLOSE;
if ($prevToken->isObjectOperator()) {
$openingBrace = CT::T_DYNAMIC_PROP_BRACE_OPEN;
$closingBrace = CT::T_DYNAMIC_PROP_BRACE_CLOSE;
}
$tokens->overrideRange($index, $index, [
new Token([$openingBrace, '{']),
new Token([\T_VARIABLE, $token->getContent()]),
new Token([$closingBrace, '}']),
]);
}
}
}
| 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/LanguageConstruct/ClassKeywordRemoveFixer.php | src/Fixer/LanguageConstruct/ClassKeywordRemoveFixer.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\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
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;
/**
* @deprecated
*
* @author Sullivan Senechal <soullivaneuh@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ClassKeywordRemoveFixer extends AbstractFixer implements DeprecatedFixerInterface
{
/**
* @var array<array-key, string>
*/
private array $imports = [];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Converts `::class` keywords to FQCN strings.',
[
new CodeSample(
<<<'PHP'
<?php
use Foo\Bar\Baz;
$className = Baz::class;
PHP,
),
],
);
}
public function getSuccessorsNames(): array
{
return [];
}
/**
* {@inheritdoc}
*
* Must run before NoUnusedImportsFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(CT::T_CLASS_CONSTANT);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$previousNamespaceScopeEndIndex = 0;
foreach ($tokens->getNamespaceDeclarations() as $declaration) {
$this->replaceClassKeywordsSection($tokens, '', $previousNamespaceScopeEndIndex, $declaration->getStartIndex());
$this->replaceClassKeywordsSection($tokens, $declaration->getFullName(), $declaration->getStartIndex(), $declaration->getScopeEndIndex());
$previousNamespaceScopeEndIndex = $declaration->getScopeEndIndex();
}
$this->replaceClassKeywordsSection($tokens, '', $previousNamespaceScopeEndIndex, $tokens->count() - 1);
}
private function storeImports(Tokens $tokens, int $startIndex, int $endIndex): void
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
$this->imports = [];
foreach ($tokensAnalyzer->getImportUseIndexes() as $index) {
if ($index < $startIndex || $index > $endIndex) {
continue;
}
$import = '';
while (($index = $tokens->getNextMeaningfulToken($index)) !== null) {
if ($tokens[$index]->equalsAny([';', [CT::T_GROUP_IMPORT_BRACE_OPEN]]) || $tokens[$index]->isGivenKind(\T_AS)) {
break;
}
$import .= $tokens[$index]->getContent();
}
// Imports group (PHP 7 spec)
if ($tokens[$index]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) {
$groupEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_GROUP_IMPORT_BRACE, $index);
$groupImports = array_map(
static fn (string $import): string => trim($import),
explode(',', $tokens->generatePartialCode($index + 1, $groupEndIndex - 1)),
);
foreach ($groupImports as $groupImport) {
$groupImportParts = array_map(static fn (string $import): string => trim($import), explode(' as ', $groupImport));
if (2 === \count($groupImportParts)) {
$this->imports[$groupImportParts[1]] = $import.$groupImportParts[0];
} else {
$this->imports[] = $import.$groupImport;
}
}
} elseif ($tokens[$index]->isGivenKind(\T_AS)) {
$aliasIndex = $tokens->getNextMeaningfulToken($index);
$alias = $tokens[$aliasIndex]->getContent();
$this->imports[$alias] = $import;
} else {
$this->imports[] = $import;
}
}
}
private function replaceClassKeywordsSection(Tokens $tokens, string $namespace, int $startIndex, int $endIndex): void
{
if ($endIndex - $startIndex < 3) {
return;
}
$this->storeImports($tokens, $startIndex, $endIndex);
$ctClassTokens = $tokens->findGivenKind(CT::T_CLASS_CONSTANT, $startIndex, $endIndex);
foreach (array_reverse(array_keys($ctClassTokens)) as $classIndex) {
$this->replaceClassKeyword($tokens, $namespace, $classIndex);
}
}
private function replaceClassKeyword(Tokens $tokens, string $namespacePrefix, int $classIndex): void
{
$classEndIndex = $tokens->getPrevMeaningfulToken($classIndex);
$classEndIndex = $tokens->getPrevMeaningfulToken($classEndIndex);
if (!$tokens[$classEndIndex]->isGivenKind(\T_STRING)) {
return;
}
if ($tokens[$classEndIndex]->equalsAny([[\T_STRING, 'self'], [\T_STATIC, 'static'], [\T_STRING, 'parent']], false)) {
return;
}
$classBeginIndex = $classEndIndex;
while (true) {
$prev = $tokens->getPrevMeaningfulToken($classBeginIndex);
if (!$tokens[$prev]->isGivenKind([\T_NS_SEPARATOR, \T_STRING])) {
break;
}
$classBeginIndex = $prev;
}
$classString = $tokens->generatePartialCode(
$tokens[$classBeginIndex]->isGivenKind(\T_NS_SEPARATOR)
? $tokens->getNextMeaningfulToken($classBeginIndex)
: $classBeginIndex,
$classEndIndex,
);
$classImport = false;
if ($tokens[$classBeginIndex]->isGivenKind(\T_NS_SEPARATOR)) {
$namespacePrefix = '';
} else {
foreach ($this->imports as $alias => $import) {
if ($classString === $alias) {
$classImport = $import;
break;
}
$classStringArray = explode('\\', $classString);
$namespaceToTest = $classStringArray[0];
if (0 === ($namespaceToTest <=> substr($import, -\strlen($namespaceToTest)))) {
$classImport = $import;
break;
}
}
}
for ($i = $classBeginIndex; $i <= $classIndex; ++$i) {
if (!$tokens[$i]->isComment() && !($tokens[$i]->isWhitespace() && str_contains($tokens[$i]->getContent(), "\n"))) {
$tokens->clearAt($i);
}
}
$tokens->insertAt($classBeginIndex, new Token([
\T_CONSTANT_ENCAPSED_STRING,
"'".$this->makeClassFQN($namespacePrefix, $classImport, $classString)."'",
]));
}
/**
* @param false|string $classImport
*/
private function makeClassFQN(string $namespacePrefix, $classImport, string $classString): string
{
if (false === $classImport) {
return ('' !== $namespacePrefix ? ($namespacePrefix.'\\') : '').$classString;
}
$classStringArray = explode('\\', $classString);
$classStringLength = \count($classStringArray);
$classImportArray = explode('\\', $classImport);
$classImportLength = \count($classImportArray);
if (1 === $classStringLength) {
return $classImport;
}
return implode('\\', array_merge(
\array_slice($classImportArray, 0, $classImportLength - $classStringLength + 1),
$classStringArray,
));
}
}
| 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/LanguageConstruct/CombineConsecutiveUnsetsFixer.php | src/Fixer/LanguageConstruct/CombineConsecutiveUnsetsFixer.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\LanguageConstruct;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class CombineConsecutiveUnsetsFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Calling `unset` on multiple items should be done in one call.',
[new CodeSample("<?php\nunset(\$a); unset(\$b);\n")],
);
}
/**
* {@inheritdoc}
*
* Must run before NoExtraBlankLinesFixer, NoTrailingWhitespaceFixer, NoWhitespaceInBlankLineFixer, SpaceAfterSemicolonFixer.
* Must run after NoEmptyStatementFixer, NoUnsetOnPropertyFixer, NoUselessElseFixer.
*/
public function getPriority(): int
{
return 24;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_UNSET);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
if (!$tokens[$index]->isGivenKind(\T_UNSET)) {
continue;
}
$previousUnsetCall = $this->getPreviousUnsetCall($tokens, $index);
if (\is_int($previousUnsetCall)) {
$index = $previousUnsetCall;
continue;
}
[$previousUnset, , $previousUnsetBraceEnd] = $previousUnsetCall;
// Merge the tokens inside the 'unset' call into the previous one 'unset' call.
$tokensAddCount = $this->moveTokens(
$tokens,
$nextUnsetContentStart = $tokens->getNextTokenOfKind($index, ['(']),
$nextUnsetContentEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextUnsetContentStart),
$previousUnsetBraceEnd - 1,
);
if (!$tokens[$previousUnsetBraceEnd]->isWhitespace()) {
$tokens->insertAt($previousUnsetBraceEnd, new Token([\T_WHITESPACE, ' ']));
++$tokensAddCount;
}
$tokens->insertAt($previousUnsetBraceEnd, new Token(','));
++$tokensAddCount;
// Remove 'unset', '(', ')' and (possibly) ';' from the merged 'unset' call.
$this->clearOffsetTokens($tokens, $tokensAddCount, [$index, $nextUnsetContentStart, $nextUnsetContentEnd]);
$nextUnsetSemicolon = $tokens->getNextMeaningfulToken($nextUnsetContentEnd);
if (null !== $nextUnsetSemicolon && $tokens[$nextUnsetSemicolon]->equals(';')) {
$tokens->clearTokenAndMergeSurroundingWhitespace($nextUnsetSemicolon);
}
$index = $previousUnset + 1;
}
}
/**
* @param list<int> $indices
*/
private function clearOffsetTokens(Tokens $tokens, int $offset, array $indices): void
{
foreach ($indices as $index) {
$tokens->clearTokenAndMergeSurroundingWhitespace($index + $offset);
}
}
/**
* Find a previous call to unset directly before the index.
*
* Returns an array with
* * unset index
* * opening brace index
* * closing brace index
* * end semicolon index
*
* Or the index to where the method looked for a call.
*
* @return array{int, int, int, int}|int
*/
private function getPreviousUnsetCall(Tokens $tokens, int $index)
{
$previousUnsetSemicolon = $tokens->getPrevMeaningfulToken($index);
if (null === $previousUnsetSemicolon) {
return $index;
}
if (!$tokens[$previousUnsetSemicolon]->equals(';')) {
return $previousUnsetSemicolon;
}
$previousUnsetBraceEnd = $tokens->getPrevMeaningfulToken($previousUnsetSemicolon);
if (null === $previousUnsetBraceEnd) {
return $index;
}
if (!$tokens[$previousUnsetBraceEnd]->equals(')')) {
return $previousUnsetBraceEnd;
}
$previousUnsetBraceStart = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $previousUnsetBraceEnd);
$previousUnset = $tokens->getPrevMeaningfulToken($previousUnsetBraceStart);
if (null === $previousUnset) {
return $index;
}
if (!$tokens[$previousUnset]->isGivenKind(\T_UNSET)) {
return $previousUnset;
}
return [
$previousUnset,
$previousUnsetBraceStart,
$previousUnsetBraceEnd,
$previousUnsetSemicolon,
];
}
/**
* @param int $start Index previous of the first token to move
* @param int $end Index of the last token to move
* @param int $to Upper boundary index
*
* @return int Number of tokens inserted
*/
private function moveTokens(Tokens $tokens, int $start, int $end, int $to): int
{
$added = 0;
for ($i = $start + 1; $i < $end; $i += 2) {
if ($tokens[$i]->isWhitespace() && $tokens[$to + 1]->isWhitespace()) {
$tokens[$to + 1] = new Token([\T_WHITESPACE, $tokens[$to + 1]->getContent().$tokens[$i]->getContent()]);
} else {
$tokens->insertAt(++$to, clone $tokens[$i]);
++$end;
++$added;
}
$tokens->clearAt($i + 1);
}
return $added;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Alias/BacktickToShellExecFixer.php | src/Fixer/Alias/BacktickToShellExecFixer.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\Alias;
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 Filippo Tessarotto <zoeslam@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class BacktickToShellExecFixer extends AbstractFixer
{
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound('`');
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Converts backtick operators to `shell_exec` calls.',
[
new CodeSample(
<<<'EOT'
<?php
$plain = `ls -lah`;
$withVar = `ls -lah $var1 ${var2} {$var3} {$var4[0]} {$var5->call()}`;
EOT,
),
],
'Conversion is done only when it is non risky, so when special chars like single-quotes, double-quotes and backticks are not used inside the command.',
);
}
/**
* {@inheritdoc}
*
* Must run before ExplicitStringVariableFixer, NativeFunctionInvocationFixer, SingleQuoteFixer.
*/
public function getPriority(): int
{
return 17;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$backtickStarted = false;
$backtickTokens = [];
for ($index = $tokens->count() - 1; $index > 0; --$index) {
$token = $tokens[$index];
if (!$token->equals('`')) {
if ($backtickStarted) {
$backtickTokens[$index] = $token;
}
continue;
}
$backtickTokens[$index] = $token;
if ($backtickStarted) {
$this->fixBackticks($tokens, $backtickTokens);
$backtickTokens = [];
}
$backtickStarted = !$backtickStarted;
}
}
/**
* Override backtick code with corresponding double-quoted string.
*
* @param array<int, Token> $backtickTokens
*/
private function fixBackticks(Tokens $tokens, array $backtickTokens): void
{
// Track indices for final override
ksort($backtickTokens);
$openingBacktickIndex = array_key_first($backtickTokens);
$closingBacktickIndex = array_key_last($backtickTokens);
// Strip enclosing backticks
array_shift($backtickTokens);
array_pop($backtickTokens);
// Double-quoted strings are parsed differently if they contain
// variables or not, so we need to build the new token array accordingly
$count = \count($backtickTokens);
$newTokens = [
new Token([\T_STRING, 'shell_exec']),
new Token('('),
];
if (1 !== $count) {
$newTokens[] = new Token('"');
}
foreach ($backtickTokens as $token) {
if (!$token->isGivenKind(\T_ENCAPSED_AND_WHITESPACE)) {
$newTokens[] = $token;
continue;
}
$content = $token->getContent();
// Escaping special chars depends on the context: too tricky
if (Preg::match('/[`"\']/u', $content)) {
return;
}
$kind = \T_ENCAPSED_AND_WHITESPACE;
if (1 === $count) {
$content = '"'.$content.'"';
$kind = \T_CONSTANT_ENCAPSED_STRING;
}
$newTokens[] = new Token([$kind, $content]);
}
if (1 !== $count) {
$newTokens[] = new Token('"');
}
$newTokens[] = new Token(')');
$tokens->overrideRange($openingBacktickIndex, $closingBacktickIndex, $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/Alias/NoMixedEchoPrintFixer.php | src/Fixer/Alias/NoMixedEchoPrintFixer.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\Alias;
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{
* use?: 'echo'|'print',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* use: 'echo'|'print',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Sullivan Senechal <soullivaneuh@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoMixedEchoPrintFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @var T_ECHO|T_PRINT
*/
private int $candidateTokenType;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Either language construct `print` or `echo` should be used.',
[
new CodeSample("<?php print 'example';\n"),
new CodeSample("<?php echo('example');\n", ['use' => 'print']),
],
);
}
/**
* {@inheritdoc}
*
* Must run after EchoTagSyntaxFixer, NoUselessPrintfFixer.
*/
public function getPriority(): int
{
return -10;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound($this->candidateTokenType);
}
protected function configurePostNormalisation(): void
{
$this->candidateTokenType = 'echo' === $this->configuration['use'] ? \T_PRINT : \T_ECHO;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if ($token->isGivenKind($this->candidateTokenType)) {
if (\T_PRINT === $this->candidateTokenType) {
$this->fixPrintToEcho($tokens, $index);
} else {
$this->fixEchoToPrint($tokens, $index);
}
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('use', 'The desired language construct.'))
->setAllowedValues(['print', 'echo'])
->setDefault('echo')
->getOption(),
]);
}
private function fixEchoToPrint(Tokens $tokens, int $index): void
{
$nextTokenIndex = $tokens->getNextMeaningfulToken($index);
$endTokenIndex = $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]);
$canBeConverted = true;
for ($i = $nextTokenIndex; $i < $endTokenIndex; ++$i) {
if ($tokens[$i]->equalsAny(['(', [CT::T_ARRAY_SQUARE_BRACE_OPEN]])) {
$blockType = Tokens::detectBlockType($tokens[$i]);
$i = $tokens->findBlockEnd($blockType['type'], $i);
}
if ($tokens[$i]->equals(',')) {
$canBeConverted = false;
break;
}
}
if (false === $canBeConverted) {
return;
}
$tokens[$index] = new Token([\T_PRINT, 'print']);
}
private function fixPrintToEcho(Tokens $tokens, int $index): void
{
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)];
if (!$prevToken->equalsAny([';', '{', '}', ')', [\T_OPEN_TAG], [\T_ELSE]])) {
return;
}
$tokens[$index] = new Token([\T_ECHO, 'echo']);
}
}
| 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/Alias/MbStrFunctionsFixer.php | src/Fixer/Alias/MbStrFunctionsFixer.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\Alias;
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 Filippo Tessarotto <zoeslam@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class MbStrFunctionsFixer extends AbstractFixer
{
/**
* list of the string-related function names and their mb_ equivalent.
*
* @var array<
* string,
* array{
* alternativeName: string,
* argumentCount: list<int>,
* },
* >
*/
private static array $functionsMap = [
'str_split' => ['alternativeName' => 'mb_str_split', 'argumentCount' => [1, 2, 3]],
'stripos' => ['alternativeName' => 'mb_stripos', 'argumentCount' => [2, 3]],
'stristr' => ['alternativeName' => 'mb_stristr', 'argumentCount' => [2, 3]],
'strlen' => ['alternativeName' => 'mb_strlen', 'argumentCount' => [1]],
'strpos' => ['alternativeName' => 'mb_strpos', 'argumentCount' => [2, 3]],
'strrchr' => ['alternativeName' => 'mb_strrchr', 'argumentCount' => [2]],
'strripos' => ['alternativeName' => 'mb_strripos', 'argumentCount' => [2, 3]],
'strrpos' => ['alternativeName' => 'mb_strrpos', 'argumentCount' => [2, 3]],
'strstr' => ['alternativeName' => 'mb_strstr', 'argumentCount' => [2, 3]],
'strtolower' => ['alternativeName' => 'mb_strtolower', 'argumentCount' => [1]],
'strtoupper' => ['alternativeName' => 'mb_strtoupper', 'argumentCount' => [1]],
'substr' => ['alternativeName' => 'mb_substr', 'argumentCount' => [2, 3]],
'substr_count' => ['alternativeName' => 'mb_substr_count', 'argumentCount' => [2, 3, 4]],
];
/**
* @var array<
* string,
* array{
* alternativeName: string,
* argumentCount: list<int>,
* },
* >
*/
private array $functions;
public function __construct()
{
parent::__construct();
if (\PHP_VERSION_ID >= 8_03_00) {
self::$functionsMap['str_pad'] = ['alternativeName' => 'mb_str_pad', 'argumentCount' => [1, 2, 3, 4]];
}
if (\PHP_VERSION_ID >= 8_04_00) {
self::$functionsMap['trim'] = ['alternativeName' => 'mb_trim', 'argumentCount' => [1, 2]];
self::$functionsMap['ltrim'] = ['alternativeName' => 'mb_ltrim', 'argumentCount' => [1, 2]];
self::$functionsMap['rtrim'] = ['alternativeName' => 'mb_rtrim', 'argumentCount' => [1, 2]];
}
$this->functions = array_filter(
self::$functionsMap,
static fn (array $mapping): bool => (new \ReflectionFunction($mapping['alternativeName']))->isInternal(),
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_STRING);
}
public function isRisky(): bool
{
return true;
}
/**
* {@inheritdoc}
*
* Must run before NativeFunctionInvocationFixer.
*/
public function getPriority(): int
{
return 2;
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Replace non multibyte-safe functions with corresponding mb function.',
[
new CodeSample(
<<<'PHP'
<?php
$a = strlen($a);
$a = strpos($a, $b);
$a = strrpos($a, $b);
$a = substr($a, $b);
$a = strtolower($a);
$a = strtoupper($a);
$a = stripos($a, $b);
$a = strripos($a, $b);
$a = strstr($a, $b);
$a = stristr($a, $b);
$a = strrchr($a, $b);
$a = substr_count($a, $b);
PHP,
),
],
null,
'Risky when any of the functions are overridden, or when relying on the string byte size rather than its length in characters.',
);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$argumentsAnalyzer = new ArgumentsAnalyzer();
$functionsAnalyzer = new FunctionsAnalyzer();
for ($index = $tokens->count() - 1; $index > 0; --$index) {
if (!$tokens[$index]->isGivenKind(\T_STRING)) {
continue;
}
$lowercasedContent = strtolower($tokens[$index]->getContent());
if (!isset($this->functions[$lowercasedContent])) {
continue;
}
// is it a global function call?
if ($functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) {
$openParenthesis = $tokens->getNextMeaningfulToken($index);
$closeParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis);
$numberOfArguments = $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $closeParenthesis);
if (!\in_array($numberOfArguments, $this->functions[$lowercasedContent]['argumentCount'], true)) {
continue;
}
$tokens[$index] = new Token([\T_STRING, $this->functions[$lowercasedContent]['alternativeName']]);
continue;
}
// is it a global function import?
$functionIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$functionIndex]->isGivenKind(\T_NS_SEPARATOR)) {
$functionIndex = $tokens->getPrevMeaningfulToken($functionIndex);
}
if (!$tokens[$functionIndex]->isGivenKind(CT::T_FUNCTION_IMPORT)) {
continue;
}
$useIndex = $tokens->getPrevMeaningfulToken($functionIndex);
if (!$tokens[$useIndex]->isGivenKind(\T_USE)) {
continue;
}
$tokens[$index] = new Token([\T_STRING, $this->functions[$lowercasedContent]['alternativeName']]);
}
}
}
| 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/Alias/ArrayPushFixer.php | src/Fixer/Alias/ArrayPushFixer.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\Alias;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ArrayPushFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Converts simple usages of `array_push($x, $y);` to `$x[] = $y;`.',
[new CodeSample("<?php\narray_push(\$x, \$y);\n")],
null,
'Risky when the function `array_push` is overridden.',
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_STRING) && $tokens->count() > 7;
}
public function isRisky(): bool
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$functionsAnalyzer = new FunctionsAnalyzer();
for ($index = $tokens->count() - 7; $index > 0; --$index) {
if (!$tokens[$index]->equals([\T_STRING, 'array_push'], false)) {
continue;
}
if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) {
continue; // redeclare/override
}
// meaningful before must be `<?php`, `{`, `}` or `;`
$callIndex = $index;
$index = $tokens->getPrevMeaningfulToken($index);
$namespaceSeparatorIndex = null;
if ($tokens[$index]->isGivenKind(\T_NS_SEPARATOR)) {
$namespaceSeparatorIndex = $index;
$index = $tokens->getPrevMeaningfulToken($index);
}
if (!$tokens[$index]->equalsAny([';', '{', '}', ')', [\T_OPEN_TAG]])) {
continue;
}
// figure out where the arguments list opens
$openBraceIndex = $tokens->getNextMeaningfulToken($callIndex);
$blockType = Tokens::detectBlockType($tokens[$openBraceIndex]);
if (null === $blockType || Tokens::BLOCK_TYPE_PARENTHESIS_BRACE !== $blockType['type']) {
continue;
}
// figure out where the arguments list closes
$closeBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openBraceIndex);
// meaningful after `)` must be `;`, `? >` or nothing
$afterCloseBraceIndex = $tokens->getNextMeaningfulToken($closeBraceIndex);
if (null !== $afterCloseBraceIndex && !$tokens[$afterCloseBraceIndex]->equalsAny([';', [\T_CLOSE_TAG]])) {
continue;
}
// must have 2 arguments
// first argument must be a variable (with possibly array indexing etc.),
// after that nothing meaningful should be there till the next `,` or `)`
// if `)` than we cannot fix it (it is a single argument call)
$firstArgumentStop = $this->getFirstArgumentEnd($tokens, $openBraceIndex);
$firstArgumentStop = $tokens->getNextMeaningfulToken($firstArgumentStop);
if (!$tokens[$firstArgumentStop]->equals(',')) {
return;
}
// second argument can be about anything but ellipsis, we must make sure there is not
// a third argument (or more) passed to `array_push`
$secondArgumentStart = $tokens->getNextMeaningfulToken($firstArgumentStop);
$secondArgumentStop = $this->getSecondArgumentEnd($tokens, $secondArgumentStart, $closeBraceIndex);
if (null === $secondArgumentStop) {
continue;
}
// candidate is valid, replace tokens
$tokens->clearTokenAndMergeSurroundingWhitespace($closeBraceIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($firstArgumentStop);
$tokens->insertAt(
$firstArgumentStop,
[
new Token('['),
new Token(']'),
new Token([\T_WHITESPACE, ' ']),
new Token('='),
],
);
$tokens->clearTokenAndMergeSurroundingWhitespace($openBraceIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($callIndex);
if (null !== $namespaceSeparatorIndex) {
$tokens->clearTokenAndMergeSurroundingWhitespace($namespaceSeparatorIndex);
}
}
}
private function getFirstArgumentEnd(Tokens $tokens, int $index): int
{
$nextIndex = $tokens->getNextMeaningfulToken($index);
$nextToken = $tokens[$nextIndex];
while ($nextToken->equalsAny([
'$',
'[',
'(',
[CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN],
[CT::T_DYNAMIC_PROP_BRACE_OPEN],
[CT::T_DYNAMIC_VAR_BRACE_OPEN],
[CT::T_NAMESPACE_OPERATOR],
[\T_NS_SEPARATOR],
[\T_STATIC],
[\T_STRING],
[\T_VARIABLE],
])) {
$blockType = Tokens::detectBlockType($nextToken);
if (null !== $blockType) {
$nextIndex = $tokens->findBlockEnd($blockType['type'], $nextIndex);
}
$index = $nextIndex;
$nextIndex = $tokens->getNextMeaningfulToken($nextIndex);
$nextToken = $tokens[$nextIndex];
}
if ($nextToken->isGivenKind(\T_OBJECT_OPERATOR)) {
return $this->getFirstArgumentEnd($tokens, $nextIndex);
}
if ($nextToken->isGivenKind(\T_PAAMAYIM_NEKUDOTAYIM)) {
return $this->getFirstArgumentEnd($tokens, $tokens->getNextMeaningfulToken($nextIndex));
}
return $index;
}
/**
* @param int $endIndex boundary, i.e. tokens index of `)`
*/
private function getSecondArgumentEnd(Tokens $tokens, int $index, int $endIndex): ?int
{
if ($tokens[$index]->isGivenKind(\T_ELLIPSIS)) {
return null;
}
for (; $index <= $endIndex; ++$index) {
$blockType = Tokens::detectBlockType($tokens[$index]);
while (null !== $blockType && $blockType['isStart']) {
$index = $tokens->findBlockEnd($blockType['type'], $index);
$index = $tokens->getNextMeaningfulToken($index);
$blockType = Tokens::detectBlockType($tokens[$index]);
}
if ($tokens[$index]->equals(',') || $tokens[$index]->isGivenKind([\T_YIELD, \T_YIELD_FROM, \T_LOGICAL_AND, \T_LOGICAL_OR, \T_LOGICAL_XOR])) {
return null;
}
}
return $endIndex;
}
}
| 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/Alias/NoAliasLanguageConstructCallFixer.php | src/Fixer/Alias/NoAliasLanguageConstructCallFixer.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\Alias;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoAliasLanguageConstructCallFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Master language constructs shall be used instead of aliases.',
[
new CodeSample(
<<<'PHP'
<?php
die;
PHP,
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_EXIT);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(\T_EXIT)) {
continue;
}
if ('exit' === strtolower($token->getContent())) {
continue;
}
$tokens[$index] = new Token([\T_EXIT, 'exit']);
}
}
}
| 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/Alias/NoAliasFunctionsFixer.php | src/Fixer/Alias/NoAliasFunctionsFixer.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\Alias;
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\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* sets?: list<'@all'|'@exif'|'@ftp'|'@IMAP'|'@internal'|'@ldap'|'@mbreg'|'@mysqli'|'@oci'|'@odbc'|'@openssl'|'@pcntl'|'@pg'|'@posix'|'@snmp'|'@sodium'|'@time'>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* sets: list<'@all'|'@exif'|'@ftp'|'@IMAP'|'@internal'|'@ldap'|'@mbreg'|'@mysqli'|'@oci'|'@odbc'|'@openssl'|'@pcntl'|'@pg'|'@posix'|'@snmp'|'@sodium'|'@time'>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Vladimir Reznichenko <kalessil@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 NoAliasFunctionsFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private const SETS = [
'@internal' => [
'diskfreespace' => 'disk_free_space',
'dns_check_record' => 'checkdnsrr',
'dns_get_mx' => 'getmxrr',
'session_commit' => 'session_write_close',
'stream_register_wrapper' => 'stream_wrapper_register',
'set_file_buffer' => 'stream_set_write_buffer',
'socket_set_blocking' => 'stream_set_blocking',
'socket_get_status' => 'stream_get_meta_data',
'socket_set_timeout' => 'stream_set_timeout',
'socket_getopt' => 'socket_get_option',
'socket_setopt' => 'socket_set_option',
'chop' => 'rtrim',
'close' => 'closedir',
'doubleval' => 'floatval',
'fputs' => 'fwrite',
'get_required_files' => 'get_included_files',
'ini_alter' => 'ini_set',
'is_double' => 'is_float',
'is_integer' => 'is_int',
'is_long' => 'is_int',
'is_real' => 'is_float',
'is_writeable' => 'is_writable',
'join' => 'implode',
'key_exists' => 'array_key_exists',
'magic_quotes_runtime' => 'set_magic_quotes_runtime',
'pos' => 'current',
'show_source' => 'highlight_file',
'sizeof' => 'count',
'strchr' => 'strstr',
'user_error' => 'trigger_error',
],
'@IMAP' => [
'imap_create' => 'imap_createmailbox',
'imap_fetchtext' => 'imap_body',
'imap_header' => 'imap_headerinfo',
'imap_listmailbox' => 'imap_list',
'imap_listsubscribed' => 'imap_lsub',
'imap_rename' => 'imap_renamemailbox',
'imap_scan' => 'imap_listscan',
'imap_scanmailbox' => 'imap_listscan',
],
'@ldap' => [
'ldap_close' => 'ldap_unbind',
'ldap_modify' => 'ldap_mod_replace',
],
'@mysqli' => [
'mysqli_execute' => 'mysqli_stmt_execute',
'mysqli_set_opt' => 'mysqli_options',
'mysqli_escape_string' => 'mysqli_real_escape_string',
],
'@pg' => [
'pg_exec' => 'pg_query',
],
'@oci' => [
'oci_free_cursor' => 'oci_free_statement',
],
'@odbc' => [
'odbc_do' => 'odbc_exec',
'odbc_field_precision' => 'odbc_field_len',
],
'@mbreg' => [
'mbereg' => 'mb_ereg',
'mbereg_match' => 'mb_ereg_match',
'mbereg_replace' => 'mb_ereg_replace',
'mbereg_search' => 'mb_ereg_search',
'mbereg_search_getpos' => 'mb_ereg_search_getpos',
'mbereg_search_getregs' => 'mb_ereg_search_getregs',
'mbereg_search_init' => 'mb_ereg_search_init',
'mbereg_search_pos' => 'mb_ereg_search_pos',
'mbereg_search_regs' => 'mb_ereg_search_regs',
'mbereg_search_setpos' => 'mb_ereg_search_setpos',
'mberegi' => 'mb_eregi',
'mberegi_replace' => 'mb_eregi_replace',
'mbregex_encoding' => 'mb_regex_encoding',
'mbsplit' => 'mb_split',
],
'@openssl' => [
'openssl_get_publickey' => 'openssl_pkey_get_public',
'openssl_get_privatekey' => 'openssl_pkey_get_private',
],
'@sodium' => [
'sodium_crypto_scalarmult_base' => 'sodium_crypto_box_publickey_from_secretkey',
],
'@exif' => [
'read_exif_data' => 'exif_read_data',
],
'@ftp' => [
'ftp_quit' => 'ftp_close',
],
'@posix' => [
'posix_errno' => 'posix_get_last_error',
],
'@pcntl' => [
'pcntl_errno' => 'pcntl_get_last_error',
],
'@time' => [
'mktime' => ['time', 0],
'gmmktime' => ['time', 0],
],
];
/**
* @var array<string, array{string, int}|string> stores alias (key) - master (value) functions mapping
*/
private array $aliases = [];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Master functions shall be used instead of aliases.',
[
new CodeSample(
<<<'PHP'
<?php
$a = chop($b);
close($b);
$a = doubleval($b);
$a = fputs($b, $c);
$a = get_required_files();
ini_alter($b, $c);
$a = is_double($b);
$a = is_integer($b);
$a = is_long($b);
$a = is_real($b);
$a = is_writeable($b);
$a = join($glue, $pieces);
$a = key_exists($key, $array);
magic_quotes_runtime($new_setting);
$a = pos($array);
$a = show_source($filename, true);
$a = sizeof($b);
$a = strchr($haystack, $needle);
$a = imap_header($imap_stream, 1);
user_error($message);
mbereg_search_getregs();
PHP,
),
new CodeSample(
<<<'PHP'
<?php
$a = is_double($b);
mbereg_search_getregs();
PHP,
['sets' => ['@mbreg']],
),
],
null,
'Risky when any of the alias functions are overridden.',
);
}
/**
* {@inheritdoc}
*
* Must run before ImplodeCallFixer, PhpUnitDedicateAssertFixer.
*/
public function getPriority(): int
{
return 40;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_STRING);
}
public function isRisky(): bool
{
return true;
}
protected function configurePostNormalisation(): void
{
$this->aliases = [];
foreach ($this->configuration['sets'] as $set) {
if ('@all' === $set) {
$this->aliases = array_merge(...array_values(self::SETS));
break;
}
if (!isset(self::SETS[$set])) {
throw new \LogicException(\sprintf('Set %s passed option validation, but not part of ::SETS.', $set));
}
$this->aliases = array_merge($this->aliases, self::SETS[$set]);
}
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$functionsAnalyzer = new FunctionsAnalyzer();
$argumentsAnalyzer = new ArgumentsAnalyzer();
foreach ($tokens->findGivenKind(\T_STRING) as $index => $token) {
// check mapping hit
$tokenContent = strtolower($token->getContent());
if (!isset($this->aliases[$tokenContent])) {
continue;
}
// skip expressions without parameters list
$openParenthesis = $tokens->getNextMeaningfulToken($index);
if (!$tokens[$openParenthesis]->equals('(')) {
continue;
}
if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) {
continue;
}
if (\is_array($this->aliases[$tokenContent])) {
[$alias, $numberOfArguments] = $this->aliases[$tokenContent];
$count = $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis));
if ($numberOfArguments !== $count) {
continue;
}
} else {
$alias = $this->aliases[$tokenContent];
}
$tokens[$index] = new Token([\T_STRING, $alias]);
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
$sets = [
'@all' => 'all listed sets',
'@internal' => 'native functions',
'@exif' => 'EXIF functions',
'@ftp' => 'FTP functions',
'@IMAP' => 'IMAP functions',
'@ldap' => 'LDAP functions',
'@mbreg' => 'from `ext-mbstring`',
'@mysqli' => 'mysqli functions',
'@oci' => 'oci functions',
'@odbc' => 'odbc functions',
'@openssl' => 'openssl functions',
'@pcntl' => 'PCNTL functions',
'@pg' => 'pg functions',
'@posix' => 'POSIX functions',
'@snmp' => 'SNMP functions', // @TODO Remove on next major 4.0 as this set is now empty
'@sodium' => 'libsodium functions',
'@time' => 'time functions',
];
$list = "List of sets to fix. Defined sets are:\n\n";
foreach ($sets as $set => $description) {
$list .= \sprintf("* `%s` (%s);\n", $set, $description);
}
$list = rtrim($list, ";\n").'.';
return new FixerConfigurationResolver([
(new FixerOptionBuilder('sets', $list))
->setAllowedTypes(['string[]'])
->setAllowedValues([new AllowedValueSubset(array_keys($sets))])
->setDefault(['@internal', '@IMAP', '@pg'])
->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/Alias/RandomApiMigrationFixer.php | src/Fixer/Alias/RandomApiMigrationFixer.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\Alias;
use PhpCsFixer\AbstractFunctionReferenceFixer;
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\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* replacements?: array<string, string>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* replacements: array<string, string>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Vladimir Reznichenko <kalessil@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class RandomApiMigrationFixer extends AbstractFunctionReferenceFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @var array<string, array<int, int>>
*/
private const ARGUMENT_COUNTS = [
'getrandmax' => [0],
'mt_rand' => [1, 2],
'rand' => [0, 2],
'srand' => [0, 1],
'random_int' => [0, 2],
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Replaces `rand`, `srand`, `getrandmax` functions calls with their `mt_*` analogs or `random_int`.',
[
new CodeSample("<?php\n\$a = getrandmax();\n\$a = rand(\$b, \$c);\n\$a = srand();\n"),
new CodeSample(
"<?php\n\$a = getrandmax();\n\$a = rand(\$b, \$c);\n\$a = srand();\n",
['replacements' => ['getrandmax' => 'mt_getrandmax']],
),
new CodeSample(
"<?php \$a = rand(\$b, \$c);\n",
['replacements' => ['rand' => 'random_int']],
),
],
null,
'Risky when the configured functions are overridden. Or when relying on the seed based generating of the numbers.',
);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$argumentsAnalyzer = new ArgumentsAnalyzer();
foreach ($this->configuration['replacements'] as $functionIdentity => $functionReplacement) {
if ($functionIdentity === $functionReplacement) {
continue;
}
$currIndex = 0;
do {
// try getting function reference and translate boundaries for humans
$boundaries = $this->find($functionIdentity, $tokens, $currIndex, $tokens->count() - 1);
if (null === $boundaries) {
// next function search, as current one not found
continue 2;
}
[$functionName, $openParenthesis, $closeParenthesis] = $boundaries;
$count = $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $closeParenthesis);
\assert(isset(self::ARGUMENT_COUNTS[$functionIdentity])); // for PHPStan
if (!\in_array($count, self::ARGUMENT_COUNTS[$functionIdentity], true)) {
continue 2;
}
// analysing cursor shift, so nested calls could be processed
$currIndex = $openParenthesis;
$tokens[$functionName] = new Token([\T_STRING, $functionReplacement]);
if (0 === $count && 'random_int' === $functionReplacement) {
$tokens->insertAt($currIndex + 1, [
new Token([\T_LNUMBER, '0']),
new Token(','),
new Token([\T_WHITESPACE, ' ']),
new Token([\T_STRING, 'getrandmax']),
new Token('('),
new Token(')'),
]);
$currIndex += 6;
}
} while (null !== $currIndex);
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('replacements', 'Mapping between replaced functions with the new ones.'))
->setAllowedTypes(['array<string, string>'])
->setAllowedValues([static function (array $value): bool {
foreach ($value as $functionName => $replacement) {
if (!\array_key_exists($functionName, self::ARGUMENT_COUNTS)) {
throw new InvalidOptionsException(\sprintf(
'Function "%s" is not handled by the fixer.',
$functionName,
));
}
}
return true;
}])
->setDefault([
'getrandmax' => 'mt_getrandmax',
'rand' => Future::getV4OrV3('random_int', 'mt_rand'),
'srand' => 'mt_srand',
])
->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/Alias/EregToPregFixer.php | src/Fixer/Alias/EregToPregFixer.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\Alias;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\PregException;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Matteo Beccati <matteo@beccati.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class EregToPregFixer extends AbstractFixer
{
/**
* @var non-empty-list<non-empty-array<int, string>> the list of the ext/ereg function names, their preg equivalent and the preg modifier(s), if any
* all condensed in an array of arrays
*/
private const FUNCTIONS = [
['ereg', 'preg_match', ''],
['eregi', 'preg_match', 'i'],
['ereg_replace', 'preg_replace', ''],
['eregi_replace', 'preg_replace', 'i'],
['split', 'preg_split', ''],
['spliti', 'preg_split', 'i'],
];
/**
* @var non-empty-list<string> the list of preg delimiters, in order of preference
*/
private const DELIMITERS = ['/', '#', '!'];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Replace deprecated `ereg` regular expression functions with `preg`.',
[new CodeSample("<?php \$x = ereg('[A-Z]');\n")],
null,
'Risky if the `ereg` function is overridden.',
);
}
/**
* {@inheritdoc}
*
* Must run after NoUselessConcatOperatorFixer.
*/
public function getPriority(): int
{
return 0;
}
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
{
$end = $tokens->count() - 1;
$functionsAnalyzer = new FunctionsAnalyzer();
foreach (self::FUNCTIONS as $map) {
// the sequence is the function name, followed by "(" and a quoted string
$seq = [[\T_STRING, $map[0]], '(', [\T_CONSTANT_ENCAPSED_STRING]];
$currIndex = 0;
while (true) {
$match = $tokens->findSequence($seq, $currIndex, $end, false);
// did we find a match?
if (null === $match) {
break;
}
// findSequence also returns the tokens, but we're only interested in the indices, i.e.:
// 0 => function name,
// 1 => parenthesis "("
// 2 => quoted string passed as 1st parameter
$match = array_keys($match);
// advance tokenizer cursor
$currIndex = $match[2];
if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $match[0])) {
continue;
}
// ensure the first parameter is just a string (e.g. has nothing appended)
$next = $tokens->getNextMeaningfulToken($match[2]);
if (null === $next || !$tokens[$next]->equalsAny([',', ')'])) {
continue;
}
// convert to PCRE
$regexTokenContent = $tokens[$match[2]]->getContent();
if ('b' === $regexTokenContent[0] || 'B' === $regexTokenContent[0]) {
$quote = $regexTokenContent[1];
$prefix = $regexTokenContent[0];
$string = substr($regexTokenContent, 2, -1);
} else {
$quote = $regexTokenContent[0];
$prefix = '';
$string = substr($regexTokenContent, 1, -1);
}
$delim = $this->getBestDelimiter($string);
$preg = $delim.addcslashes($string, $delim).$delim.'D'.$map[2];
// check if the preg is valid
if (!$this->checkPreg($preg)) {
continue;
}
// modify function and argument
$tokens[$match[0]] = new Token([\T_STRING, $map[1]]);
$tokens[$match[2]] = new Token([\T_CONSTANT_ENCAPSED_STRING, $prefix.$quote.$preg.$quote]);
}
}
}
/**
* Check the validity of a PCRE.
*
* @param string $pattern the regular expression
*/
private function checkPreg(string $pattern): bool
{
try {
Preg::match($pattern, '');
return true;
} catch (PregException $e) {
return false;
}
}
/**
* Get the delimiter that would require the least escaping in a regular expression.
*
* @param string $pattern the regular expression
*
* @return string the preg delimiter
*/
private function getBestDelimiter(string $pattern): string
{
// try to find something that's not used
$delimiters = [];
foreach (self::DELIMITERS as $k => $d) {
if (!str_contains($pattern, $d)) {
return $d;
}
$delimiters[$d] = [substr_count($pattern, $d), $k];
}
// return the least used delimiter, using the position in the list as a tiebreaker
uasort($delimiters, static function (array $a, array $b): int {
if ($a[0] === $b[0]) {
return $a[1] <=> $b[1];
}
return $a[0] <=> $b[0];
});
return array_key_first($delimiters);
}
}
| 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/Alias/ModernizeStrposFixer.php | src/Fixer/Alias/ModernizeStrposFixer.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\Alias;
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\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* modernize_stripos?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* modernize_stripos: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Alexander M. Turek <me@derrabus.de>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ModernizeStrposFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private const REPLACEMENTS = [
[
'operator' => [\T_IS_IDENTICAL, '==='],
'operand' => [\T_LNUMBER, '0'],
'replacement' => [\T_STRING, 'str_starts_with'],
'negate' => false,
],
[
'operator' => [\T_IS_NOT_IDENTICAL, '!=='],
'operand' => [\T_LNUMBER, '0'],
'replacement' => [\T_STRING, 'str_starts_with'],
'negate' => true,
],
[
'operator' => [\T_IS_NOT_IDENTICAL, '!=='],
'operand' => [\T_STRING, 'false'],
'replacement' => [\T_STRING, 'str_contains'],
'negate' => false,
],
[
'operator' => [\T_IS_IDENTICAL, '==='],
'operand' => [\T_STRING, 'false'],
'replacement' => [\T_STRING, 'str_contains'],
'negate' => true,
],
];
private bool $modernizeStripos = false;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Replace `strpos()` and `stripos()` calls with `str_starts_with()` or `str_contains()` if possible.',
[
new CodeSample(
<<<'PHP'
<?php
if (strpos($haystack, $needle) === 0) {}
if (strpos($haystack, $needle) !== 0) {}
if (strpos($haystack, $needle) !== false) {}
if (strpos($haystack, $needle) === false) {}
PHP,
),
new CodeSample(
<<<'PHP'
<?php
if (strpos($haystack, $needle) === 0) {}
if (strpos($haystack, $needle) !== 0) {}
if (strpos($haystack, $needle) !== false) {}
if (strpos($haystack, $needle) === false) {}
if (stripos($haystack, $needle) === 0) {}
if (stripos($haystack, $needle) !== 0) {}
if (stripos($haystack, $needle) !== false) {}
if (stripos($haystack, $needle) === false) {}
PHP,
['modernize_stripos' => true],
),
],
null,
'Risky if `strpos`, `stripos`, `str_starts_with`, `str_contains` or `strtolower` functions are overridden.',
);
}
/**
* {@inheritdoc}
*
* Must run before BinaryOperatorSpacesFixer, NoExtraBlankLinesFixer, NoSpacesInsideParenthesisFixer, NoTrailingWhitespaceFixer, NotOperatorWithSpaceFixer, NotOperatorWithSuccessorSpaceFixer, PhpUnitDedicateAssertFixer, SingleSpaceAfterConstructFixer, SingleSpaceAroundConstructFixer, SpacesInsideParenthesesFixer.
* Must run after StrictComparisonFixer.
*/
public function getPriority(): int
{
return 37;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_STRING) && $tokens->isAnyTokenKindsFound([\T_IS_IDENTICAL, \T_IS_NOT_IDENTICAL]);
}
public function isRisky(): bool
{
return true;
}
protected function configurePostNormalisation(): void
{
if (isset($this->configuration['modernize_stripos']) && true === $this->configuration['modernize_stripos']) {
$this->modernizeStripos = true;
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('modernize_stripos', 'Whether to modernize `stripos` calls as well.'))
->setAllowedTypes(['bool'])
->setDefault(Future::getV4OrV3(true, false))
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$functionsAnalyzer = new FunctionsAnalyzer();
$argumentsAnalyzer = new ArgumentsAnalyzer();
$modernizeCandidates = [[\T_STRING, 'strpos']];
if ($this->modernizeStripos) {
$modernizeCandidates[] = [\T_STRING, 'stripos'];
}
for ($index = \count($tokens) - 1; $index > 0; --$index) {
// find candidate function call
if (!$tokens[$index]->equalsAny($modernizeCandidates, false) || !$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) {
continue;
}
// assert called with 2 arguments
$openIndex = $tokens->getNextMeaningfulToken($index);
$closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex);
$arguments = $argumentsAnalyzer->getArguments($tokens, $openIndex, $closeIndex);
if (2 !== \count($arguments)) {
continue;
}
// check if part condition and fix if needed
$compareTokens = $this->getCompareTokens($tokens, $index, -1); // look behind
if (null === $compareTokens) {
$compareTokens = $this->getCompareTokens($tokens, $closeIndex, 1); // look ahead
}
if (null !== $compareTokens) {
$isCaseInsensitive = $tokens[$index]->equals([\T_STRING, 'stripos'], false);
$this->fixCall($tokens, $index, $compareTokens, $isCaseInsensitive);
}
}
}
/**
* @param array{operator_index: int, operand_index: int} $operatorIndices
*/
private function fixCall(Tokens $tokens, int $functionIndex, array $operatorIndices, bool $isCaseInsensitive): void
{
foreach (self::REPLACEMENTS as $replacement) {
if (!$tokens[$operatorIndices['operator_index']]->equals($replacement['operator'])) {
continue;
}
if (!$tokens[$operatorIndices['operand_index']]->equals($replacement['operand'], false)) {
continue;
}
$tokens->clearTokenAndMergeSurroundingWhitespace($operatorIndices['operator_index']);
$tokens->clearTokenAndMergeSurroundingWhitespace($operatorIndices['operand_index']);
$tokens->clearTokenAndMergeSurroundingWhitespace($functionIndex);
if ($replacement['negate']) {
$negateInsertIndex = $functionIndex;
$prevFunctionIndex = $tokens->getPrevMeaningfulToken($functionIndex);
if ($tokens[$prevFunctionIndex]->isGivenKind(\T_NS_SEPARATOR)) {
$negateInsertIndex = $prevFunctionIndex;
}
$tokens->insertAt($negateInsertIndex, new Token('!'));
++$functionIndex;
}
$tokens->insertAt($functionIndex, new Token($replacement['replacement']));
if ($isCaseInsensitive) {
$this->wrapArgumentsWithStrToLower($tokens, $functionIndex);
}
break;
}
}
private function wrapArgumentsWithStrToLower(Tokens $tokens, int $functionIndex): void
{
$argumentsAnalyzer = new ArgumentsAnalyzer();
$shouldAddNamespace = $tokens[$functionIndex - 1]->isGivenKind(\T_NS_SEPARATOR);
$openIndex = $tokens->getNextMeaningfulToken($functionIndex);
$closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex);
$arguments = $argumentsAnalyzer->getArguments($tokens, $openIndex, $closeIndex);
$firstArgumentIndexStart = array_key_first($arguments);
if (!isset($arguments[$firstArgumentIndexStart])) {
return;
}
$firstArgumentIndexEnd = $arguments[$firstArgumentIndexStart] + 3 + ($shouldAddNamespace ? 1 : 0);
$isSecondArgumentTokenWhiteSpace = $tokens[array_key_last($arguments)]->isGivenKind(\T_WHITESPACE);
if ($isSecondArgumentTokenWhiteSpace) {
$secondArgumentIndexStart = $tokens->getNextMeaningfulToken(array_key_last($arguments));
} else {
$secondArgumentIndexStart = array_key_last($arguments);
}
$secondArgumentIndexStart += 3 + ($shouldAddNamespace ? 1 : 0);
if (!isset($arguments[array_key_last($arguments)])) {
return;
}
$secondArgumentIndexEnd = $arguments[array_key_last($arguments)] + 6 + ($shouldAddNamespace ? 1 : 0) + ($isSecondArgumentTokenWhiteSpace ? 1 : 0);
if ($shouldAddNamespace) {
$tokens->insertAt($firstArgumentIndexStart, new Token([\T_NS_SEPARATOR, '\\']));
++$firstArgumentIndexStart;
}
$tokens->insertAt($firstArgumentIndexStart, [new Token([\T_STRING, 'strtolower']), new Token('(')]);
$tokens->insertAt($firstArgumentIndexEnd, new Token(')'));
if ($shouldAddNamespace) {
$tokens->insertAt($secondArgumentIndexStart, new Token([\T_NS_SEPARATOR, '\\']));
++$secondArgumentIndexStart;
}
$tokens->insertAt($secondArgumentIndexStart, [new Token([\T_STRING, 'strtolower']), new Token('(')]);
$tokens->insertAt($secondArgumentIndexEnd, new Token(')'));
}
/**
* @param -1|1 $direction
*
* @return null|array{operator_index: int, operand_index: int}
*/
private function getCompareTokens(Tokens $tokens, int $offsetIndex, int $direction): ?array
{
$operatorIndex = $tokens->getMeaningfulTokenSibling($offsetIndex, $direction);
if (null !== $operatorIndex && $tokens[$operatorIndex]->isGivenKind(\T_NS_SEPARATOR)) {
$operatorIndex = $tokens->getMeaningfulTokenSibling($operatorIndex, $direction);
}
if (null === $operatorIndex || !$tokens[$operatorIndex]->isGivenKind([\T_IS_IDENTICAL, \T_IS_NOT_IDENTICAL])) {
return null;
}
$operandIndex = $tokens->getMeaningfulTokenSibling($operatorIndex, $direction);
if (null === $operandIndex) {
return null;
}
$operand = $tokens[$operandIndex];
if (!$operand->equals([\T_LNUMBER, '0']) && !$operand->equals([\T_STRING, 'false'], false)) {
return null;
}
$precedenceTokenIndex = $tokens->getMeaningfulTokenSibling($operandIndex, $direction);
if (null !== $precedenceTokenIndex && $this->isOfHigherPrecedence($tokens[$precedenceTokenIndex])) {
return null;
}
return ['operator_index' => $operatorIndex, 'operand_index' => $operandIndex];
}
private function isOfHigherPrecedence(Token $token): bool
{
return
$token->isGivenKind([
\T_DEC, // --
\T_INC, // ++
\T_INSTANCEOF, // instanceof
\T_IS_GREATER_OR_EQUAL, // >=
\T_IS_SMALLER_OR_EQUAL, // <=
\T_POW, // **
\T_SL, // <<
\T_SR, // >>
])
|| $token->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/Alias/SetTypeToCastFixer.php | src/Fixer/Alias/SetTypeToCastFixer.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\Alias;
use PhpCsFixer\AbstractFunctionReferenceFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class SetTypeToCastFixer extends AbstractFunctionReferenceFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Cast shall be used, not `settype`.',
[
new CodeSample(
<<<'PHP'
<?php
settype($foo, "integer");
settype($bar, "string");
settype($bar, "null");
PHP,
),
],
null,
'Risky when the `settype` function is overridden or when used as the 2nd or 3rd expression in a `for` loop .',
);
}
/**
* {@inheritdoc}
*
* Must run after NoBinaryStringFixer, NoUselessConcatOperatorFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAllTokenKindsFound([\T_CONSTANT_ENCAPSED_STRING, \T_STRING, \T_VARIABLE]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$map = [
'array' => [\T_ARRAY_CAST, '(array)'],
'bool' => [\T_BOOL_CAST, '(bool)'],
'boolean' => [\T_BOOL_CAST, '(bool)'],
'double' => [\T_DOUBLE_CAST, '(float)'],
'float' => [\T_DOUBLE_CAST, '(float)'],
'int' => [\T_INT_CAST, '(int)'],
'integer' => [\T_INT_CAST, '(int)'],
'object' => [\T_OBJECT_CAST, '(object)'],
'string' => [\T_STRING_CAST, '(string)'],
// note: `'null' is dealt with later on
];
$argumentsAnalyzer = new ArgumentsAnalyzer();
foreach (array_reverse($this->findSettypeCalls($tokens)) as $candidate) {
$functionNameIndex = $candidate[0];
$arguments = $argumentsAnalyzer->getArguments($tokens, $candidate[1], $candidate[2]);
if (2 !== \count($arguments)) {
continue; // function must be overridden or used incorrectly
}
$prev = $tokens->getPrevMeaningfulToken($functionNameIndex);
if (!$tokens[$prev]->equalsAny([';', '{', '}', [\T_OPEN_TAG]])) {
continue; // return value of the function is used
}
reset($arguments);
// --- Test first argument --------------------
$firstArgumentStart = key($arguments);
if ($tokens[$firstArgumentStart]->isComment() || $tokens[$firstArgumentStart]->isWhitespace()) {
$firstArgumentStart = $tokens->getNextMeaningfulToken($firstArgumentStart);
}
if (!$tokens[$firstArgumentStart]->isGivenKind(\T_VARIABLE)) {
continue; // settype only works with variables pass by reference, function must be overridden
}
$commaIndex = $tokens->getNextMeaningfulToken($firstArgumentStart);
if (null === $commaIndex || !$tokens[$commaIndex]->equals(',')) {
continue; // first argument is complex statement; function must be overridden
}
// --- Test second argument -------------------
next($arguments);
$secondArgumentStart = key($arguments);
$secondArgumentEnd = $arguments[$secondArgumentStart];
if ($tokens[$secondArgumentStart]->isComment() || $tokens[$secondArgumentStart]->isWhitespace()) {
$secondArgumentStart = $tokens->getNextMeaningfulToken($secondArgumentStart);
}
if (
!$tokens[$secondArgumentStart]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)
|| $tokens->getNextMeaningfulToken($secondArgumentStart) < $secondArgumentEnd
) {
continue; // second argument is of the wrong type or is a (complex) statement of some sort (function is overridden)
}
// --- Test type ------------------------------
$type = strtolower(trim($tokens[$secondArgumentStart]->getContent(), '"\''));
if ('null' !== $type && !isset($map[$type])) {
continue; // we don't know how to map
}
// --- Fixing ---------------------------------
$argumentToken = $tokens[$firstArgumentStart];
$this->removeSettypeCall(
$tokens,
$functionNameIndex,
$candidate[1],
$firstArgumentStart,
$commaIndex,
$secondArgumentStart,
$candidate[2],
);
if ('null' === $type) {
$this->fixSettypeNullCall($tokens, $functionNameIndex, $argumentToken);
} else {
$this->fixSettypeCall($tokens, $functionNameIndex, $argumentToken, new Token($map[$type]));
}
}
}
/**
* @return list<array{int, int, int}>
*/
private function findSettypeCalls(Tokens $tokens): array
{
$candidates = [];
$end = \count($tokens);
for ($i = 1; $i < $end; ++$i) {
$candidate = $this->find('settype', $tokens, $i, $end);
if (null === $candidate) {
break;
}
$i = $candidate[1]; // proceed to openParenthesisIndex
$candidates[] = $candidate;
}
return $candidates;
}
private function removeSettypeCall(
Tokens $tokens,
int $functionNameIndex,
int $openParenthesisIndex,
int $firstArgumentStart,
int $commaIndex,
int $secondArgumentStart,
int $closeParenthesisIndex
): void {
$tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesisIndex);
$prevIndex = $tokens->getPrevMeaningfulToken($closeParenthesisIndex);
if ($tokens[$prevIndex]->equals(',')) {
$tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex);
}
$tokens->clearTokenAndMergeSurroundingWhitespace($secondArgumentStart);
$tokens->clearTokenAndMergeSurroundingWhitespace($commaIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($firstArgumentStart);
$tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesisIndex);
$tokens->clearAt($functionNameIndex); // we'll be inserting here so no need to merge the space tokens
$tokens->clearEmptyTokens();
}
private function fixSettypeCall(
Tokens $tokens,
int $functionNameIndex,
Token $argumentToken,
Token $castToken
): void {
$tokens->insertAt(
$functionNameIndex,
[
clone $argumentToken,
new Token([\T_WHITESPACE, ' ']),
new Token('='),
new Token([\T_WHITESPACE, ' ']),
$castToken,
new Token([\T_WHITESPACE, ' ']),
clone $argumentToken,
],
);
$tokens->removeTrailingWhitespace($functionNameIndex + 6); // 6 = number of inserted tokens -1 for offset correction
}
private function fixSettypeNullCall(
Tokens $tokens,
int $functionNameIndex,
Token $argumentToken
): void {
$tokens->insertAt(
$functionNameIndex,
[
clone $argumentToken,
new Token([\T_WHITESPACE, ' ']),
new Token('='),
new Token([\T_WHITESPACE, ' ']),
new Token([\T_STRING, 'null']),
],
);
$tokens->removeTrailingWhitespace($functionNameIndex + 4); // 4 = number of inserted tokens -1 for offset correction
}
}
| 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/Alias/PowToExponentiationFixer.php | src/Fixer/Alias/PowToExponentiationFixer.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\Alias;
use PhpCsFixer\AbstractFunctionReferenceFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class PowToExponentiationFixer extends AbstractFunctionReferenceFixer
{
public function isCandidate(Tokens $tokens): bool
{
// minimal candidate to fix is seven tokens: pow(x,y);
return $tokens->count() > 7 && $tokens->isTokenKindFound(\T_STRING);
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Converts `pow` to the `**` operator.',
[
new CodeSample(
"<?php\n pow(\$a, 1);\n",
),
],
null,
'Risky when the function `pow` is overridden.',
);
}
/**
* {@inheritdoc}
*
* Must run before BinaryOperatorSpacesFixer, MethodArgumentSpaceFixer, NativeFunctionCasingFixer, NoSpacesAfterFunctionNameFixer, NoSpacesInsideParenthesisFixer, SpacesInsideParenthesesFixer.
*/
public function getPriority(): int
{
return 32;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$candidates = $this->findPowCalls($tokens);
$argumentsAnalyzer = new ArgumentsAnalyzer();
$numberOfTokensAdded = 0;
$previousCloseParenthesisIndex = \count($tokens);
foreach (array_reverse($candidates) as $candidate) {
// if in the previous iteration(s) tokens were added to the collection and this is done within the tokens
// indices of the current candidate than the index of the close ')' of the candidate has moved and so
// the index needs to be updated
if ($previousCloseParenthesisIndex < $candidate[2]) {
$previousCloseParenthesisIndex = $candidate[2];
$candidate[2] += $numberOfTokensAdded;
} else {
$previousCloseParenthesisIndex = $candidate[2];
$numberOfTokensAdded = 0;
}
$arguments = $argumentsAnalyzer->getArguments($tokens, $candidate[1], $candidate[2]);
if (2 !== \count($arguments)) {
continue;
}
for ($i = $candidate[1]; $i < $candidate[2]; ++$i) {
if ($tokens[$i]->isGivenKind(\T_ELLIPSIS)) {
continue 2;
}
}
$numberOfTokensAdded += $this->fixPowToExponentiation(
$tokens,
$candidate[0], // functionNameIndex,
$candidate[1], // openParenthesisIndex,
$candidate[2], // closeParenthesisIndex,
$arguments,
);
}
}
/**
* @return list<array{int, int, int}>
*/
private function findPowCalls(Tokens $tokens): array
{
$candidates = [];
// Minimal candidate to fix is seven tokens: pow(x,y);
$end = \count($tokens) - 6;
// First possible location is after the open token: 1
for ($i = 1; $i < $end; ++$i) {
$candidate = $this->find('pow', $tokens, $i, $end);
if (null === $candidate) {
break;
}
$i = $candidate[1]; // proceed to openParenthesisIndex
$candidates[] = $candidate;
}
return $candidates;
}
/**
* @param array<int, int> $arguments
*
* @return int number of tokens added to the collection
*/
private function fixPowToExponentiation(Tokens $tokens, int $functionNameIndex, int $openParenthesisIndex, int $closeParenthesisIndex, array $arguments): int
{
// find the argument separator ',' directly after the last token of the first argument;
// replace it with T_POW '**'
$tokens[$tokens->getNextTokenOfKind(reset($arguments), [','])] = new Token([\T_POW, '**']);
// clean up the function call tokens prt. I
$tokens->clearAt($closeParenthesisIndex);
$previousIndex = $tokens->getPrevMeaningfulToken($closeParenthesisIndex);
if ($tokens[$previousIndex]->equals(',')) {
$tokens->clearAt($previousIndex); // trailing ',' in function call (PHP 7.3)
}
$added = 0;
// check if the arguments need to be wrapped in parentheses
foreach (array_reverse($arguments, true) as $argumentStartIndex => $argumentEndIndex) {
if ($this->isParenthesisNeeded($tokens, $argumentStartIndex, $argumentEndIndex)) {
$tokens->insertAt($argumentEndIndex + 1, new Token(')'));
$tokens->insertAt($argumentStartIndex, new Token('('));
$added += 2;
}
}
// clean up the function call tokens prt. II
$tokens->clearAt($openParenthesisIndex);
$tokens->clearAt($functionNameIndex);
$prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($functionNameIndex);
if ($tokens[$prevMeaningfulTokenIndex]->isGivenKind(\T_NS_SEPARATOR)) {
$tokens->clearAt($prevMeaningfulTokenIndex);
}
return $added;
}
private function isParenthesisNeeded(Tokens $tokens, int $argumentStartIndex, int $argumentEndIndex): bool
{
static $allowedKinds = null;
if (null === $allowedKinds) {
$allowedKinds = $this->getAllowedKinds();
}
for ($i = $argumentStartIndex; $i <= $argumentEndIndex; ++$i) {
if ($tokens[$i]->isGivenKind($allowedKinds) || $tokens->isEmptyAt($i)) {
continue;
}
$blockType = Tokens::detectBlockType($tokens[$i]);
if (null !== $blockType) {
$i = $tokens->findBlockEnd($blockType['type'], $i);
continue;
}
if ($tokens[$i]->equals('$')) {
$i = $tokens->getNextMeaningfulToken($i);
if ($tokens[$i]->isGivenKind(CT::T_DYNAMIC_VAR_BRACE_OPEN)) {
$i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE, $i);
continue;
}
}
if ($tokens[$i]->equals('+') && $tokens->getPrevMeaningfulToken($i) < $argumentStartIndex) {
continue;
}
return true;
}
return false;
}
/**
* @return non-empty-list<int>
*/
private function getAllowedKinds(): array
{
return [
\T_DNUMBER, \T_LNUMBER, \T_VARIABLE, \T_STRING, \T_CONSTANT_ENCAPSED_STRING, \T_DOUBLE_CAST,
\T_INT_CAST, \T_INC, \T_DEC, \T_NS_SEPARATOR, \T_WHITESPACE, \T_DOUBLE_COLON, \T_LINE, \T_COMMENT, \T_DOC_COMMENT,
CT::T_NAMESPACE_OPERATOR,
...Token::getObjectOperatorKinds(),
];
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/StringNotation/HeredocClosingMarkerFixer.php | src/Fixer/StringNotation/HeredocClosingMarkerFixer.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\StringNotation;
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{
* closing_marker?: string,
* explicit_heredoc_style?: bool,
* reserved_closing_markers?: list<string>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* closing_marker: string,
* explicit_heredoc_style: bool,
* reserved_closing_markers: list<string>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Michael Vorisek <https://github.com/mvorisek>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class HeredocClosingMarkerFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @var non-empty-list<string>
*/
public const RESERVED_CLOSING_MARKERS = [
'CSS',
'DIFF',
'HTML',
'JS',
'JSON',
'MD',
'PHP',
'PYTHON',
'RST',
'TS',
'SQL',
'XML',
'YAML',
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Unify `heredoc` or `nowdoc` closing marker.',
[
new CodeSample(
<<<'EOD'
<?php $a = <<<"TEST"
Foo
TEST;
EOD,
),
new CodeSample(
<<<'EOD'
<?php $a = <<<'TEST'
Foo
TEST;
EOD,
['closing_marker' => 'EOF'],
),
new CodeSample(
<<<'EOD_'
<?php $a = <<<EOD
Foo
EOD;
EOD_,
['explicit_heredoc_style' => true],
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_START_HEREDOC);
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder(
'closing_marker',
'Preferred closing marker.',
))
->setAllowedTypes(['string'])
->setDefault('EOD')
->getOption(),
(new FixerOptionBuilder(
'reserved_closing_markers',
'Reserved closing markers to be kept unchanged.',
))
->setAllowedTypes(['string[]'])
->setDefault(self::RESERVED_CLOSING_MARKERS)
->getOption(),
(new FixerOptionBuilder(
'explicit_heredoc_style',
'Whether the closing marker should be wrapped in double quotes.',
))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$reservedClosingMarkersMap = null;
$startIndex = null;
foreach ($tokens as $index => $token) {
if ($token->isGivenKind(\T_START_HEREDOC)) {
$startIndex = $index;
continue;
}
if (null !== $startIndex && $token->isGivenKind(\T_END_HEREDOC)) {
$existingClosingMarker = trim($token->getContent());
if (null === $reservedClosingMarkersMap) {
$reservedClosingMarkersMap = [];
foreach ($this->configuration['reserved_closing_markers'] as $v) {
$reservedClosingMarkersMap[mb_strtoupper($v)] = $v;
}
}
$existingClosingMarker = mb_strtoupper($existingClosingMarker);
do {
$newClosingMarker = $reservedClosingMarkersMap[$existingClosingMarker] ?? null;
if (!str_ends_with($existingClosingMarker, '_')) {
break;
}
$existingClosingMarker = substr($existingClosingMarker, 0, -1);
} while (null === $newClosingMarker);
if (null === $newClosingMarker) {
$newClosingMarker = $this->configuration['closing_marker'];
}
$content = $tokens->generatePartialCode($startIndex + 1, $index - 1);
while (Preg::match('~(^|[\r\n])\s*'.preg_quote($newClosingMarker, '~').'(?!\w)~', $content)) {
$newClosingMarker .= '_';
}
[$tokens[$startIndex], $tokens[$index]] = $this->convertClosingMarker($tokens[$startIndex], $token, $newClosingMarker);
$startIndex = null;
continue;
}
}
}
/**
* @return array{Token, Token}
*/
private function convertClosingMarker(Token $startToken, Token $endToken, string $newClosingMarker): array
{
$isNowdoc = str_contains($startToken->getContent(), '\'');
$markerQuote = $isNowdoc
? '\''
: (true === $this->configuration['explicit_heredoc_style'] ? '"' : '');
return [new Token([
$startToken->getId(),
Preg::replace('/<<<\h*\K["\']?[^\s"\']+["\']?/', $markerQuote.$newClosingMarker.$markerQuote, $startToken->getContent()),
]), new Token([
$endToken->getId(),
Preg::replace('/\S+/', $newClosingMarker, $endToken->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/StringNotation/SingleQuoteFixer.php | src/Fixer/StringNotation/SingleQuoteFixer.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\StringNotation;
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{
* strings_containing_single_quote_chars?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* strings_containing_single_quote_chars: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Gregor Harlan <gharlan@web.de>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class SingleQuoteFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
$codeSample = <<<'EOF'
<?php
$a = "sample";
$b = "sample with 'single-quotes'";
EOF;
return new FixerDefinition(
'Convert double quotes to single quotes for simple strings.',
[
new CodeSample($codeSample),
new CodeSample(
$codeSample,
['strings_containing_single_quote_chars' => true],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before NoUselessConcatOperatorFixer.
* Must run after BacktickToShellExecFixer, EscapeImplicitBackslashesFixer, StringImplicitBackslashesFixer.
*/
public function getPriority(): int
{
return 10;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_CONSTANT_ENCAPSED_STRING);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) {
continue;
}
$content = $token->getContent();
$prefix = '';
if ('b' === strtolower($content[0])) {
$prefix = $content[0];
$content = substr($content, 1);
}
if (
'"' === $content[0]
&& (true === $this->configuration['strings_containing_single_quote_chars'] || !str_contains($content, "'"))
// regex: odd number of backslashes, not followed by double quote or dollar
&& !Preg::match('/(?<!\\\)(?:\\\{2})*\\\(?!["$\\\])/', $content)
) {
$content = substr($content, 1, -1);
$content = str_replace(['\"', '\$', '\''], ['"', '$', '\\\''], $content);
$tokens[$index] = new Token([\T_CONSTANT_ENCAPSED_STRING, $prefix.'\''.$content.'\'']);
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('strings_containing_single_quote_chars', 'Whether to fix double-quoted strings that contains single-quotes.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->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/StringNotation/MultilineStringToHeredocFixer.php | src/Fixer/StringNotation/MultilineStringToHeredocFixer.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\StringNotation;
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 Michael Vorisek <https://github.com/mvorisek>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class MultilineStringToHeredocFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Convert multiline string to `heredoc` or `nowdoc`.',
[
new CodeSample(
<<<'EOD'
<?php
$a = 'line1
line2';
EOD."\n",
),
new CodeSample(
<<<'EOD'
<?php
$a = "line1
{$obj->getName()}";
EOD."\n",
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([\T_CONSTANT_ENCAPSED_STRING, \T_ENCAPSED_AND_WHITESPACE]);
}
/**
* {@inheritdoc}
*
* Must run before EscapeImplicitBackslashesFixer, HeredocIndentationFixer, StringImplicitBackslashesFixer.
*/
public function getPriority(): int
{
return 16;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$complexStringStartIndex = null;
foreach ($tokens as $index => $token) {
if (null === $complexStringStartIndex) {
if ($token->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) {
$this->convertStringToHeredoc($tokens, $index, $index);
} elseif ($token->equalsAny(['"', 'b"', 'B"'])) {
$complexStringStartIndex = $index;
}
} elseif ($token->equals('"')) {
$this->convertStringToHeredoc($tokens, $complexStringStartIndex, $index);
$complexStringStartIndex = null;
}
}
}
private function convertStringToHeredoc(Tokens $tokens, int $stringStartIndex, int $stringEndIndex): void
{
$closingMarker = 'EOD';
if ($tokens[$stringStartIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) {
$content = $tokens[$stringStartIndex]->getContent();
if ('b' === strtolower(substr($content, 0, 1))) {
$content = substr($content, 1);
}
$isSingleQuoted = str_starts_with($content, '\'');
$content = substr($content, 1, -1);
if ($isSingleQuoted) {
$content = Preg::replace('~\\\([\\\\\'])~', '$1', $content);
} else {
$content = Preg::replace('~(\\\\\\\)|\\\(")~', '$1$2', $content);
}
$constantStringToken = new Token([\T_ENCAPSED_AND_WHITESPACE, $content."\n"]);
} else {
$content = $tokens->generatePartialCode($stringStartIndex + 1, $stringEndIndex - 1);
$isSingleQuoted = false;
$constantStringToken = null;
}
if (!str_contains($content, "\n") && !str_contains($content, "\r")) {
return;
}
while (Preg::match('~(^|[\r\n])\s*'.preg_quote($closingMarker, '~').'(?!\w)~', $content)) {
$closingMarker .= '_';
}
$quoting = $isSingleQuoted ? '\'' : '';
$heredocStartToken = new Token([\T_START_HEREDOC, '<<<'.$quoting.$closingMarker.$quoting."\n"]);
$heredocEndToken = new Token([\T_END_HEREDOC, $closingMarker]);
if (null !== $constantStringToken) {
$tokens->overrideRange($stringStartIndex, $stringEndIndex, [
$heredocStartToken,
$constantStringToken,
$heredocEndToken,
]);
} else {
for ($i = $stringStartIndex + 1; $i < $stringEndIndex; ++$i) {
if ($tokens[$i]->isGivenKind(\T_ENCAPSED_AND_WHITESPACE)) {
$tokens[$i] = new Token([
$tokens[$i]->getId(),
Preg::replace('~(\\\\\\\)|\\\(")~', '$1$2', $tokens[$i]->getContent()),
]);
}
}
$tokens[$stringStartIndex] = $heredocStartToken;
$tokens[$stringEndIndex] = $heredocEndToken;
if ($tokens[$stringEndIndex - 1]->isGivenKind(\T_ENCAPSED_AND_WHITESPACE)) {
$tokens[$stringEndIndex - 1] = new Token([
$tokens[$stringEndIndex - 1]->getId(),
$tokens[$stringEndIndex - 1]->getContent()."\n",
]);
} else {
$tokens->insertAt($stringEndIndex, new Token([
\T_ENCAPSED_AND_WHITESPACE,
"\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/StringNotation/StringLengthToEmptyFixer.php | src/Fixer/StringNotation/StringLengthToEmptyFixer.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\StringNotation;
use PhpCsFixer\AbstractFunctionReferenceFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class StringLengthToEmptyFixer extends AbstractFunctionReferenceFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'String tests for empty must be done against `\'\'`, not with `strlen`.',
[new CodeSample("<?php \$a = 0 === strlen(\$b) || \\STRLEN(\$c) < 1;\n")],
null,
'Risky when `strlen` is overridden, when called using a `stringable` object, also no longer triggers warning when called using non-string(able).',
);
}
/**
* {@inheritdoc}
*
* Must run before NoExtraBlankLinesFixer, NoTrailingWhitespaceFixer.
* Must run after NoSpacesInsideParenthesisFixer, SpacesInsideParenthesesFixer.
*/
public function getPriority(): int
{
return 1;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$argumentsAnalyzer = new ArgumentsAnalyzer();
foreach ($this->findStrLengthCalls($tokens) as $candidate) {
[$functionNameIndex, $openParenthesisIndex, $closeParenthesisIndex] = $candidate;
$arguments = $argumentsAnalyzer->getArguments($tokens, $openParenthesisIndex, $closeParenthesisIndex);
if (1 !== \count($arguments)) {
continue; // must be one argument
}
// test for leading `\` before `strlen` call
$nextIndex = $tokens->getNextMeaningfulToken($closeParenthesisIndex);
$previousIndex = $tokens->getPrevMeaningfulToken($functionNameIndex);
if ($tokens[$previousIndex]->isGivenKind(\T_NS_SEPARATOR)) {
$namespaceSeparatorIndex = $previousIndex;
$previousIndex = $tokens->getPrevMeaningfulToken($previousIndex);
} else {
$namespaceSeparatorIndex = null;
}
// test for yoda vs non-yoda fix case
if ($this->isOperatorOfInterest($tokens[$previousIndex])) { // test if valid yoda case to fix
$operatorIndex = $previousIndex;
$operandIndex = $tokens->getPrevMeaningfulToken($previousIndex);
if (!$this->isOperandOfInterest($tokens[$operandIndex])) { // test if operand is `0` or `1`
continue;
}
$replacement = $this->getReplacementYoda($tokens[$operatorIndex], $tokens[$operandIndex]);
if (null === $replacement) {
continue;
}
if ($this->isOfHigherPrecedence($tokens[$nextIndex])) { // is of higher precedence right; continue
continue;
}
if ($this->isOfHigherPrecedence($tokens[$tokens->getPrevMeaningfulToken($operandIndex)])) { // is of higher precedence left; continue
continue;
}
} elseif ($this->isOperatorOfInterest($tokens[$nextIndex])) { // test if valid !yoda case to fix
$operatorIndex = $nextIndex;
$operandIndex = $tokens->getNextMeaningfulToken($nextIndex);
if (!$this->isOperandOfInterest($tokens[$operandIndex])) { // test if operand is `0` or `1`
continue;
}
$replacement = $this->getReplacementNotYoda($tokens[$operatorIndex], $tokens[$operandIndex]);
if (null === $replacement) {
continue;
}
if ($this->isOfHigherPrecedence($tokens[$tokens->getNextMeaningfulToken($operandIndex)])) { // is of higher precedence right; continue
continue;
}
if ($this->isOfHigherPrecedence($tokens[$previousIndex])) { // is of higher precedence left; continue
continue;
}
} else {
continue;
}
// prepare for fixing
$keepParentheses = $this->keepParentheses($tokens, $openParenthesisIndex, $closeParenthesisIndex);
if (\T_IS_IDENTICAL === $replacement) {
$operandContent = '===';
} else { // T_IS_NOT_IDENTICAL === $replacement
$operandContent = '!==';
}
// apply fixing
$tokens[$operandIndex] = new Token([\T_CONSTANT_ENCAPSED_STRING, "''"]);
$tokens[$operatorIndex] = new Token([$replacement, $operandContent]);
if (!$keepParentheses) {
$tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesisIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesisIndex);
}
$tokens->clearTokenAndMergeSurroundingWhitespace($functionNameIndex);
if (null !== $namespaceSeparatorIndex) {
$tokens->clearTokenAndMergeSurroundingWhitespace($namespaceSeparatorIndex);
}
}
}
private function getReplacementYoda(Token $operator, Token $operand): ?int
{
/* Yoda 0
0 === strlen($b) | '' === $b
0 !== strlen($b) | '' !== $b
0 <= strlen($b) | X makes no sense, assume overridden
0 >= strlen($b) | '' === $b
0 < strlen($b) | '' !== $b
0 > strlen($b) | X makes no sense, assume overridden
*/
if ('0' === $operand->getContent()) {
if ($operator->isGivenKind([\T_IS_IDENTICAL, \T_IS_GREATER_OR_EQUAL])) {
return \T_IS_IDENTICAL;
}
if ($operator->isGivenKind(\T_IS_NOT_IDENTICAL) || $operator->equals('<')) {
return \T_IS_NOT_IDENTICAL;
}
return null;
}
/* Yoda 1
1 === strlen($b) | X cannot simplify
1 !== strlen($b) | X cannot simplify
1 <= strlen($b) | '' !== $b
1 >= strlen($b) | cannot simplify
1 < strlen($b) | cannot simplify
1 > strlen($b) | '' === $b
*/
if ($operator->isGivenKind(\T_IS_SMALLER_OR_EQUAL)) {
return \T_IS_NOT_IDENTICAL;
}
if ($operator->equals('>')) {
return \T_IS_IDENTICAL;
}
return null;
}
private function getReplacementNotYoda(Token $operator, Token $operand): ?int
{
/* Not Yoda 0
strlen($b) === 0 | $b === ''
strlen($b) !== 0 | $b !== ''
strlen($b) <= 0 | $b === ''
strlen($b) >= 0 | X makes no sense, assume overridden
strlen($b) < 0 | X makes no sense, assume overridden
strlen($b) > 0 | $b !== ''
*/
if ('0' === $operand->getContent()) {
if ($operator->isGivenKind([\T_IS_IDENTICAL, \T_IS_SMALLER_OR_EQUAL])) {
return \T_IS_IDENTICAL;
}
if ($operator->isGivenKind(\T_IS_NOT_IDENTICAL) || $operator->equals('>')) {
return \T_IS_NOT_IDENTICAL;
}
return null;
}
/* Not Yoda 1
strlen($b) === 1 | X cannot simplify
strlen($b) !== 1 | X cannot simplify
strlen($b) <= 1 | X cannot simplify
strlen($b) >= 1 | $b !== ''
strlen($b) < 1 | $b === ''
strlen($b) > 1 | X cannot simplify
*/
if ($operator->isGivenKind(\T_IS_GREATER_OR_EQUAL)) {
return \T_IS_NOT_IDENTICAL;
}
if ($operator->equals('<')) {
return \T_IS_IDENTICAL;
}
return null;
}
private function isOperandOfInterest(Token $token): bool
{
if (!$token->isGivenKind(\T_LNUMBER)) {
return false;
}
$content = $token->getContent();
return '0' === $content || '1' === $content;
}
private function isOperatorOfInterest(Token $token): bool
{
return
$token->isGivenKind([\T_IS_IDENTICAL, \T_IS_NOT_IDENTICAL, \T_IS_SMALLER_OR_EQUAL, \T_IS_GREATER_OR_EQUAL])
|| $token->equals('<') || $token->equals('>');
}
private function isOfHigherPrecedence(Token $token): bool
{
return $token->isGivenKind([\T_INSTANCEOF, \T_POW, \T_SL, \T_SR]) || $token->equalsAny([
'!',
'%',
'*',
'+',
'-',
'.',
'/',
'~',
'?',
]);
}
private function keepParentheses(Tokens $tokens, int $openParenthesisIndex, int $closeParenthesisIndex): bool
{
$i = $tokens->getNextMeaningfulToken($openParenthesisIndex);
if ($tokens[$i]->isCast()) {
$i = $tokens->getNextMeaningfulToken($i);
}
for (; $i < $closeParenthesisIndex; ++$i) {
$token = $tokens[$i];
if ($token->isGivenKind([\T_VARIABLE, \T_STRING]) || $token->isObjectOperator() || $token->isWhitespace() || $token->isComment()) {
continue;
}
$blockType = Tokens::detectBlockType($token);
if (null !== $blockType && $blockType['isStart']) {
$i = $tokens->findBlockEnd($blockType['type'], $i);
continue;
}
return true;
}
return false;
}
private function findStrLengthCalls(Tokens $tokens): \Generator
{
$candidates = [];
$count = \count($tokens);
for ($i = 0; $i < $count; ++$i) {
$candidate = $this->find('strlen', $tokens, $i, $count);
if (null === $candidate) {
break;
}
$i = $candidate[1]; // proceed to openParenthesisIndex
$candidates[] = $candidate;
}
foreach (array_reverse($candidates) as $candidate) {
yield $candidate;
}
}
}
| 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/StringNotation/EscapeImplicitBackslashesFixer.php | src/Fixer/StringNotation/EscapeImplicitBackslashesFixer.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\StringNotation;
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\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
/**
* @deprecated Use `string_implicit_backslashes` with config: ['single_quoted' => 'ignore', 'double_quoted' => 'escape', 'heredoc' => 'escape'] (default)
*
* @phpstan-type _AutogeneratedInputConfiguration array{
* double_quoted?: bool,
* heredoc_syntax?: bool,
* single_quoted?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* double_quoted: bool,
* heredoc_syntax: bool,
* single_quoted: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Filippo Tessarotto <zoeslam@gmail.com>
* @author Michael Vorisek <https://github.com/mvorisek>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class EscapeImplicitBackslashesFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, DeprecatedFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getSuccessorsNames(): array
{
return array_keys($this->proxyFixers);
}
public function getDefinition(): FixerDefinitionInterface
{
$codeSample = <<<'EOF'
<?php
$singleQuoted = 'String with \" and My\Prefix\\';
$doubleQuoted = "Interpret my \n but not my \a";
$hereDoc = <<<HEREDOC
Interpret my \100 but not my \999
HEREDOC;
EOF;
return new FixerDefinition(
'Escape implicit backslashes in strings and heredocs to ease the understanding of which are special chars interpreted by PHP and which not.',
[
new CodeSample($codeSample),
new CodeSample(
$codeSample,
['single_quoted' => true],
),
new CodeSample(
$codeSample,
['double_quoted' => false],
),
new CodeSample(
$codeSample,
['heredoc_syntax' => false],
),
],
'In PHP double-quoted strings and heredocs some chars like `n`, `$` or `u` have special meanings if preceded by a backslash '
.'(and some are special only if followed by other special chars), while a backslash preceding other chars are interpreted like a plain '
.'backslash. The precise list of those special chars is hard to remember and to identify quickly: this fixer escapes backslashes '
."that do not start a special interpretation with the char after them.\n"
.'It is possible to fix also single-quoted strings: in this case there is no special chars apart from single-quote and backslash '
.'itself, so the fixer simply ensure that all backslashes are escaped. Both single and double backslashes are allowed in single-quoted '
.'strings, so the purpose in this context is mainly to have a uniformed way to have them written all over the codebase.',
);
}
/**
* {@inheritdoc}
*
* Must run before HeredocToNowdocFixer, SingleQuoteFixer.
* Must run after MultilineStringToHeredocFixer.
*/
public function getPriority(): int
{
return parent::getPriority();
}
protected function configurePostNormalisation(): void
{
/** @var StringImplicitBackslashesFixer */
$stringImplicitBackslashesFixer = $this->proxyFixers['string_implicit_backslashes'];
$stringImplicitBackslashesFixer->configure([
'single_quoted' => true === $this->configuration['single_quoted'] ? 'escape' : 'ignore',
'double_quoted' => true === $this->configuration['double_quoted'] ? 'escape' : 'ignore',
'heredoc' => true === $this->configuration['heredoc_syntax'] ? 'escape' : 'ignore',
]);
}
protected function createProxyFixers(): array
{
$stringImplicitBackslashesFixer = new StringImplicitBackslashesFixer();
$stringImplicitBackslashesFixer->configure([
'single_quoted' => 'ignore',
'double_quoted' => 'escape',
'heredoc' => 'escape',
]);
return [
$stringImplicitBackslashesFixer,
];
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('single_quoted', 'Whether to fix single-quoted strings.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
(new FixerOptionBuilder('double_quoted', 'Whether to fix double-quoted strings.'))
->setAllowedTypes(['bool'])
->setDefault(true)
->getOption(),
(new FixerOptionBuilder('heredoc_syntax', 'Whether to fix heredoc syntax.'))
->setAllowedTypes(['bool'])
->setDefault(true)
->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/StringNotation/StringImplicitBackslashesFixer.php | src/Fixer/StringNotation/StringImplicitBackslashesFixer.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\StringNotation;
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{
* double_quoted?: 'escape'|'ignore'|'unescape',
* heredoc?: 'escape'|'ignore'|'unescape',
* single_quoted?: 'escape'|'ignore'|'unescape',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* double_quoted: 'escape'|'ignore'|'unescape',
* heredoc: 'escape'|'ignore'|'unescape',
* single_quoted: 'escape'|'ignore'|'unescape',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Filippo Tessarotto <zoeslam@gmail.com>
* @author Michael Vorisek <https://github.com/mvorisek>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class StringImplicitBackslashesFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
$codeSample = <<<'EOF'
<?php
$singleQuoted = 'String with \" and My\Prefix\\';
$doubleQuoted = "Interpret my \n but not my \a";
$hereDoc = <<<HEREDOC
Interpret my \100 but not my \999
HEREDOC;
EOF;
return new FixerDefinition(
'Handles implicit backslashes in strings and heredocs. Depending on the chosen strategy, it can escape implicit backslashes to ease the understanding of which are special chars interpreted by PHP and which not (`escape`), or it can remove these additional backslashes if you find them superfluous (`unescape`). You can also leave them as-is using `ignore` strategy.',
[
new CodeSample($codeSample),
new CodeSample(
$codeSample,
['single_quoted' => 'escape'],
),
new CodeSample(
$codeSample,
['double_quoted' => 'unescape'],
),
new CodeSample(
$codeSample,
['heredoc' => 'unescape'],
),
],
'In PHP double-quoted strings and heredocs some chars like `n`, `$` or `u` have special meanings if preceded by a backslash '
.'(and some are special only if followed by other special chars), while a backslash preceding other chars are interpreted like a plain '
.'backslash. The precise list of those special chars is hard to remember and to identify quickly: this fixer escapes backslashes '
."that do not start a special interpretation with the char after them.\n"
.'It is possible to fix also single-quoted strings: in this case there is no special chars apart from single-quote and backslash '
.'itself, so the fixer simply ensure that all backslashes are escaped. Both single and double backslashes are allowed in single-quoted '
.'strings, so the purpose in this context is mainly to have a uniformed way to have them written all over the codebase.',
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([\T_ENCAPSED_AND_WHITESPACE, \T_CONSTANT_ENCAPSED_STRING]);
}
/**
* {@inheritdoc}
*
* Must run before HeredocToNowdocFixer, SingleQuoteFixer.
* Must run after MultilineStringToHeredocFixer.
*/
public function getPriority(): int
{
return 15;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$singleQuotedReservedRegex = '[\'\\\]';
$doubleQuotedReservedRegex = '(?:[efnrtv$"\\\0-7]|x[0-9A-Fa-f]|u{|$)';
$heredocSyntaxReservedRegex = '(?:[efnrtv$\\\0-7]|x[0-9A-Fa-f]|u{|$)';
$doubleQuoteOpened = false;
foreach ($tokens as $index => $token) {
if ($token->equalsAny(['"', 'b"', 'B"'])) {
$doubleQuoteOpened = !$doubleQuoteOpened;
}
if (!$token->isGivenKind([\T_ENCAPSED_AND_WHITESPACE, \T_CONSTANT_ENCAPSED_STRING])) {
continue;
}
$content = $token->getContent();
if (!str_contains($content, '\\')) {
continue;
}
// nowdoc syntax
if ($token->isGivenKind(\T_ENCAPSED_AND_WHITESPACE) && '\'' === substr(rtrim($tokens[$index - 1]->getContent()), -1)) {
continue;
}
$firstTwoCharacters = strtolower(substr($content, 0, 2));
$isSingleQuotedString = $token->isGivenKind(\T_CONSTANT_ENCAPSED_STRING) && ('\'' === $content[0] || 'b\'' === $firstTwoCharacters);
$isDoubleQuotedString = ($token->isGivenKind(\T_CONSTANT_ENCAPSED_STRING) && ('"' === $content[0] || 'b"' === $firstTwoCharacters))
|| ($token->isGivenKind(\T_ENCAPSED_AND_WHITESPACE) && $doubleQuoteOpened);
if ($isSingleQuotedString
? 'ignore' === $this->configuration['single_quoted']
: ($isDoubleQuotedString
? 'ignore' === $this->configuration['double_quoted']
: 'ignore' === $this->configuration['heredoc'])
) {
continue;
}
$escapeBackslashes = $isSingleQuotedString
? 'escape' === $this->configuration['single_quoted']
: ($isDoubleQuotedString
? 'escape' === $this->configuration['double_quoted']
: 'escape' === $this->configuration['heredoc']);
$reservedRegex = $isSingleQuotedString
? $singleQuotedReservedRegex
: ($isDoubleQuotedString
? $doubleQuotedReservedRegex
: $heredocSyntaxReservedRegex);
if ($escapeBackslashes) {
$regex = '/(?<!\\\)\\\((?:\\\\\\\)*)(?!'.$reservedRegex.')/';
$newContent = Preg::replace($regex, '\\\\\\\$1', $content);
} else {
$regex = '/(?<!\\\)\\\\\\\((?:\\\\\\\)*)(?!'.$reservedRegex.')/';
$newContent = Preg::replace($regex, '\\\$1', $content);
}
if ($newContent !== $content) {
$tokens[$index] = new Token([$token->getId(), $newContent]);
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('single_quoted', 'Whether to escape backslashes in single-quoted strings.'))
->setAllowedValues(['escape', 'unescape', 'ignore'])
->setDefault('unescape')
->getOption(),
(new FixerOptionBuilder('double_quoted', 'Whether to escape backslashes in double-quoted strings.'))
->setAllowedValues(['escape', 'unescape', 'ignore'])
->setDefault('escape')
->getOption(),
(new FixerOptionBuilder('heredoc', 'Whether to escape backslashes in heredoc syntax.'))
->setAllowedValues(['escape', 'unescape', 'ignore'])
->setDefault('escape')
->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/StringNotation/NoTrailingWhitespaceInStringFixer.php | src/Fixer/StringNotation/NoTrailingWhitespaceInStringFixer.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\StringNotation;
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 Gregor Harlan
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoTrailingWhitespaceInStringFixer extends AbstractFixer
{
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([\T_CONSTANT_ENCAPSED_STRING, \T_ENCAPSED_AND_WHITESPACE, \T_INLINE_HTML]);
}
public function isRisky(): bool
{
return true;
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There must be no trailing whitespace at the end of lines in strings.',
[
new CodeSample(
"<?php \$a = ' \n foo \n';\n",
),
],
null,
'Changing the whitespaces in strings might affect string comparisons and outputs.',
);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1, $last = true; $index >= 0; --$index, $last = false) {
$token = $tokens[$index];
if (!$token->isGivenKind([\T_CONSTANT_ENCAPSED_STRING, \T_ENCAPSED_AND_WHITESPACE, \T_INLINE_HTML])) {
continue;
}
$isInlineHtml = $token->isGivenKind(\T_INLINE_HTML);
$regex = $isInlineHtml && $last ? '/\h+(?=\R|$)/' : '/\h+(?=\R)/';
$content = Preg::replace($regex, '', $token->getContent());
if ($token->getContent() === $content) {
continue;
}
if (!$isInlineHtml || 0 === $index) {
$this->updateContent($tokens, $index, $content);
continue;
}
$prev = $index - 1;
if ($tokens[$prev]->equals([\T_CLOSE_TAG, '?>']) && Preg::match('/^\R/', $content, $match)) {
$tokens[$prev] = new Token([\T_CLOSE_TAG, $tokens[$prev]->getContent().$match[0]]);
$content = substr($content, \strlen($match[0]));
$content = false === $content ? '' : $content; // @phpstan-ignore-line due to https://github.com/phpstan/phpstan/issues/1215 , awaiting PHP8 as min requirement of Fixer
}
$this->updateContent($tokens, $index, $content);
}
}
private function updateContent(Tokens $tokens, int $index, string $content): void
{
if ('' === $content) {
$tokens->clearAt($index);
return;
}
$tokens[$index] = new Token([$tokens[$index]->getId(), $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/StringNotation/SimpleToComplexStringVariableFixer.php | src/Fixer/StringNotation/SimpleToComplexStringVariableFixer.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\StringNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Dave van der Brugge <dmvdbrugge@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class SimpleToComplexStringVariableFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Converts explicit variables in double-quoted strings and heredoc syntax from simple to complex format (`${` to `{$`).',
[
new CodeSample(
<<<'EOT'
<?php
$name = 'World';
echo "Hello ${name}!";
EOT,
),
new CodeSample(
<<<'EOT'
<?php
$name = 'World';
echo <<<TEST
Hello ${name}!
TEST;
EOT,
),
],
"Doesn't touch implicit variables. Works together nicely with `explicit_string_variable`.",
);
}
/**
* {@inheritdoc}
*
* Must run after ExplicitStringVariableFixer.
*/
public function getPriority(): int
{
return -10;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_DOLLAR_OPEN_CURLY_BRACES);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = \count($tokens) - 3; $index > 0; --$index) {
if (!$tokens[$index]->isGivenKind(\T_DOLLAR_OPEN_CURLY_BRACES)) {
continue;
}
$varnameToken = $tokens[$index + 1];
if (!$varnameToken->isGivenKind(\T_STRING_VARNAME)) {
continue;
}
$dollarCloseToken = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_COMPLEX_STRING_VARIABLE, $index);
$prevTokenContent = $tokens[$index - 1]->getContent();
if (str_ends_with($prevTokenContent, '$') && !str_ends_with($prevTokenContent, '\$')) {
$tokens[$index - 1] = new Token([\T_ENCAPSED_AND_WHITESPACE, substr($prevTokenContent, 0, -1).'\$']);
}
$tokens[$index] = new Token([\T_CURLY_OPEN, '{']);
$tokens[$index + 1] = new Token([\T_VARIABLE, '$'.$varnameToken->getContent()]);
$tokens[$dollarCloseToken] = new Token([CT::T_CURLY_CLOSE, '}']);
}
}
}
| 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/StringNotation/ExplicitStringVariableFixer.php | src/Fixer/StringNotation/ExplicitStringVariableFixer.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\StringNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Filippo Tessarotto <zoeslam@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ExplicitStringVariableFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Converts implicit variables into explicit ones in double-quoted strings or heredoc syntax.',
[new CodeSample(
<<<'EOT'
<?php
$a = "My name is $name !";
$b = "I live in $state->country !";
$c = "I have $farm[0] chickens !";
EOT,
)],
'The reasoning behind this rule is the following:'
."\n".'- When there are two valid ways of doing the same thing, using both is confusing, there should be a coding standard to follow.'
."\n".'- PHP manual marks `"$var"` syntax as implicit and `"{$var}"` syntax as explicit: explicit code should always be preferred.'
."\n".'- Explicit syntax allows word concatenation inside strings, e.g. `"{$var}IsAVar"`, implicit doesn\'t.'
."\n".'- Explicit syntax is easier to detect for IDE/editors and therefore has colors/highlight with higher contrast, which is easier to read.'
."\n".'Backtick operator is skipped because it is harder to handle; you can use `backtick_to_shell_exec` fixer to normalize backticks to strings.',
);
}
/**
* {@inheritdoc}
*
* Must run before NoUselessConcatOperatorFixer.
* Must run after BacktickToShellExecFixer.
*/
public function getPriority(): int
{
return 6;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_VARIABLE);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$backtickStarted = false;
for ($index = \count($tokens) - 1; $index > 0; --$index) {
$token = $tokens[$index];
if ($token->equals('`')) {
$backtickStarted = !$backtickStarted;
continue;
}
if ($backtickStarted || !$token->isGivenKind(\T_VARIABLE)) {
continue;
}
$prevToken = $tokens[$index - 1];
if (!$this->isStringPartToken($prevToken)) {
continue;
}
$distinctVariableIndex = $index;
$variableTokens = [
$distinctVariableIndex => [
'tokens' => [$index => $token],
'firstVariableTokenIndex' => $index,
'lastVariableTokenIndex' => $index,
],
];
$nextIndex = $index + 1;
$squareBracketCount = 0;
while (!$this->isStringPartToken($tokens[$nextIndex])) {
if ($tokens[$nextIndex]->isGivenKind(\T_CURLY_OPEN)) {
$nextIndex = $tokens->getNextTokenOfKind($nextIndex, [[CT::T_CURLY_CLOSE]]);
} elseif ($tokens[$nextIndex]->isGivenKind(\T_VARIABLE) && 1 !== $squareBracketCount) {
$distinctVariableIndex = $nextIndex;
$variableTokens[$distinctVariableIndex] = [
'tokens' => [$nextIndex => $tokens[$nextIndex]],
'firstVariableTokenIndex' => $nextIndex,
'lastVariableTokenIndex' => $nextIndex,
];
} else {
$variableTokens[$distinctVariableIndex]['tokens'][$nextIndex] = $tokens[$nextIndex];
$variableTokens[$distinctVariableIndex]['lastVariableTokenIndex'] = $nextIndex;
if ($tokens[$nextIndex]->equalsAny(['[', ']'])) {
++$squareBracketCount;
}
}
++$nextIndex;
}
krsort($variableTokens, \SORT_NUMERIC);
foreach ($variableTokens as $distinctVariableSet) {
if (1 === \count($distinctVariableSet['tokens'])) {
$singleVariableIndex = array_key_first($distinctVariableSet['tokens']);
$singleVariableToken = current($distinctVariableSet['tokens']);
$tokens->overrideRange($singleVariableIndex, $singleVariableIndex, [
new Token([\T_CURLY_OPEN, '{']),
new Token([\T_VARIABLE, $singleVariableToken->getContent()]),
new Token([CT::T_CURLY_CLOSE, '}']),
]);
} else {
foreach ($distinctVariableSet['tokens'] as $variablePartIndex => $variablePartToken) {
if ($variablePartToken->isGivenKind(\T_NUM_STRING)) {
$tokens[$variablePartIndex] = new Token([\T_LNUMBER, $variablePartToken->getContent()]);
continue;
}
if ($variablePartToken->isGivenKind(\T_STRING) && $tokens[$variablePartIndex + 1]->equals(']')) {
$tokens[$variablePartIndex] = new Token([\T_CONSTANT_ENCAPSED_STRING, "'".$variablePartToken->getContent()."'"]);
}
}
$tokens->insertAt($distinctVariableSet['lastVariableTokenIndex'] + 1, new Token([CT::T_CURLY_CLOSE, '}']));
$tokens->insertAt($distinctVariableSet['firstVariableTokenIndex'], new Token([\T_CURLY_OPEN, '{']));
}
}
}
}
/**
* Check if token is a part of a string.
*
* @param Token $token The token to check
*/
private function isStringPartToken(Token $token): bool
{
return $token->isGivenKind(\T_ENCAPSED_AND_WHITESPACE)
|| $token->isGivenKind(\T_START_HEREDOC)
|| '"' === $token->getContent()
|| 'b"' === strtolower($token->getContent());
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/StringNotation/StringLineEndingFixer.php | src/Fixer/StringNotation/StringLineEndingFixer.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\StringNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* Fixes the line endings in multi-line strings.
*
* @author Ilija Tovilo <ilija.tovilo@me.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class StringLineEndingFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([\T_CONSTANT_ENCAPSED_STRING, \T_ENCAPSED_AND_WHITESPACE, \T_INLINE_HTML]);
}
public function isRisky(): bool
{
return true;
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'All multi-line strings must use correct line ending.',
[
new CodeSample(
"<?php \$a = 'my\r\nmulti\nline\r\nstring';\r\n",
),
],
null,
'Changing the line endings of multi-line strings might affect string comparisons and outputs.',
);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$ending = $this->whitespacesConfig->getLineEnding();
foreach ($tokens as $tokenIndex => $token) {
if (!$token->isGivenKind([\T_CONSTANT_ENCAPSED_STRING, \T_ENCAPSED_AND_WHITESPACE, \T_INLINE_HTML])) {
continue;
}
$tokens[$tokenIndex] = new Token([
$token->getId(),
Preg::replace(
'#\R#u',
$ending,
$token->getContent(),
),
]);
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/StringNotation/NoBinaryStringFixer.php | src/Fixer/StringNotation/NoBinaryStringFixer.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\StringNotation;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author ntzm
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoBinaryStringFixer extends AbstractFixer
{
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound(
[
\T_CONSTANT_ENCAPSED_STRING,
\T_START_HEREDOC,
'b"',
],
);
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There should not be a binary flag before strings.',
[
new CodeSample("<?php \$a = b'foo';\n"),
new CodeSample("<?php \$a = b<<<EOT\nfoo\nEOT;\n"),
],
);
}
/**
* {@inheritdoc}
*
* Must run before NoUselessConcatOperatorFixer, PhpUnitDedicateAssertInternalTypeFixer, RegularCallableCallFixer, SetTypeToCastFixer.
*/
public function getPriority(): int
{
return 40;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if ($token->isGivenKind([\T_CONSTANT_ENCAPSED_STRING, \T_START_HEREDOC])) {
$content = $token->getContent();
if ('b' === strtolower($content[0])) {
$tokens[$index] = new Token([$token->getId(), substr($content, 1)]);
}
} elseif ($token->equals('b"')) {
$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/StringNotation/HeredocToNowdocFixer.php | src/Fixer/StringNotation/HeredocToNowdocFixer.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\StringNotation;
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 Gregor Harlan <gharlan@web.de>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class HeredocToNowdocFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Convert `heredoc` to `nowdoc` where possible.',
[
new CodeSample(
<<<'EOF'
<?php $a = <<<"TEST"
Foo
TEST;
EOF,
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after EscapeImplicitBackslashesFixer, StringImplicitBackslashesFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_START_HEREDOC);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(\T_START_HEREDOC) || str_contains($token->getContent(), "'")) {
continue;
}
if ($tokens[$index + 1]->isGivenKind(\T_END_HEREDOC)) {
$tokens[$index] = $this->convertToNowdoc($token);
continue;
}
if (
!$tokens[$index + 1]->isGivenKind(\T_ENCAPSED_AND_WHITESPACE)
|| !$tokens[$index + 2]->isGivenKind(\T_END_HEREDOC)
) {
continue;
}
$content = $tokens[$index + 1]->getContent();
// regex: odd number of backslashes, not followed by dollar
if (Preg::match('/(?<!\\\)(?:\\\{2})*\\\(?![$\\\])/', $content)) {
continue;
}
$tokens[$index] = $this->convertToNowdoc($token);
$content = str_replace(['\\\\', '\$'], ['\\', '$'], $content);
$tokens[$index + 1] = new Token([
$tokens[$index + 1]->getId(),
$content,
]);
}
}
/**
* Transforms the heredoc start token to nowdoc notation.
*/
private function convertToNowdoc(Token $token): Token
{
return new Token([
$token->getId(),
Preg::replace('/^([Bb]?<<<)(\h*)"?([^\s"]+)"?/', '$1$2\'$3\'', $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/Comment/SingleLineCommentStyleFixer.php | src/Fixer/Comment/SingleLineCommentStyleFixer.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\Comment;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* comment_types?: list<'asterisk'|'hash'>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* comment_types: list<'asterisk'|'hash'>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Filippo Tessarotto <zoeslam@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class SingleLineCommentStyleFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private bool $asteriskEnabled;
private bool $hashEnabled;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Single-line comments and multi-line comments with only one line of actual content should use the `//` syntax.',
[
new CodeSample(
<<<'PHP'
<?php
/* asterisk comment */
$a = 1;
# hash comment
$b = 2;
/*
* multi-line
* comment
*/
$c = 3;
PHP,
),
new CodeSample(
<<<'PHP'
<?php
/* first comment */
$a = 1;
/*
* second comment
*/
$b = 2;
/*
* third
* comment
*/
$c = 3;
PHP,
['comment_types' => ['asterisk']],
),
new CodeSample(
"<?php # comment\n",
['comment_types' => ['hash']],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after HeaderCommentFixer, NoUselessReturnFixer, PhpdocToCommentFixer.
*/
public function getPriority(): int
{
return -31;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_COMMENT);
}
protected function configurePostNormalisation(): void
{
$this->asteriskEnabled = \in_array('asterisk', $this->configuration['comment_types'], true);
$this->hashEnabled = \in_array('hash', $this->configuration['comment_types'], true);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind(\T_COMMENT)) {
continue;
}
$content = $token->getContent();
/** @TODO PHP 8.0 - no more need for `?: ''` */
$commentContent = substr($content, 2, -2) ?: ''; // @phpstan-ignore-line
if ($this->hashEnabled && str_starts_with($content, '#')) {
if (isset($content[1]) && '[' === $content[1]) {
continue; // This might be an attribute on PHP8, do not change
}
$tokens[$index] = new Token([$token->getId(), '//'.substr($content, 1)]);
continue;
}
if (
!$this->asteriskEnabled
|| str_contains($commentContent, '?>')
|| !str_starts_with($content, '/*')
|| Preg::match('/[^\s\*].*\R.*[^\s\*]/s', $commentContent)
) {
continue;
}
$nextTokenIndex = $index + 1;
if (isset($tokens[$nextTokenIndex])) {
$nextToken = $tokens[$nextTokenIndex];
if (!$nextToken->isWhitespace() || !Preg::match('/\R/', $nextToken->getContent())) {
continue;
}
$tokens[$nextTokenIndex] = new Token([$nextToken->getId(), ltrim($nextToken->getContent(), " \t")]);
}
$content = '//';
if (Preg::match('/[^\s\*]/', $commentContent)) {
$content = '// '.Preg::replace('/[\s\*]*([^\s\*](?:.+[^\s\*])?)[\s\*]*/', '\1', $commentContent);
}
$tokens[$index] = new Token([$token->getId(), $content]);
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('comment_types', 'List of comment types to fix.'))
->setAllowedTypes(['string[]'])
->setAllowedValues([new AllowedValueSubset(['asterisk', 'hash'])])
->setDefault(['asterisk', 'hash'])
->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/Comment/SingleLineCommentSpacingFixer.php | src/Fixer/Comment/SingleLineCommentSpacingFixer.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\Comment;
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 SingleLineCommentSpacingFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Single-line comments must have proper spacing.',
[
new CodeSample(
<<<'PHP'
<?php
//comment 1
#comment 2
/*comment 3*/
PHP,
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after PhpdocToCommentFixer.
*/
public function getPriority(): int
{
return 1;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_COMMENT);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = \count($tokens) - 1; 0 <= $index; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(\T_COMMENT)) {
continue;
}
$content = $token->getContent();
$contentLength = \strlen($content);
if ('/' === $content[0]) {
if ($contentLength < 3) {
continue; // cheap check for "//"
}
if ('*' === $content[1]) { // slash asterisk comment
if ($contentLength < 5 || '*' === $content[2] || str_contains($content, "\n")) {
continue; // cheap check for "/**/", comment that looks like a PHPDoc, or multi line comment
}
$newContent = rtrim(substr($content, 0, -2)).' '.substr($content, -2);
$newContent = $this->fixCommentLeadingSpace($newContent, '/*');
} else { // double slash comment
$newContent = $this->fixCommentLeadingSpace($content, '//');
}
} else { // hash comment
if ($contentLength < 2 || '[' === $content[1]) { // cheap check for "#" or annotation (like) comment
continue;
}
$newContent = $this->fixCommentLeadingSpace($content, '#');
}
if ($newContent !== $content) {
$tokens[$index] = new Token([\T_COMMENT, $newContent]);
}
}
}
// fix space between comment open and leading text
private function fixCommentLeadingSpace(string $content, string $prefix): string
{
if (Preg::match(\sprintf('@^%s\h+.*$@', preg_quote($prefix, '@')), $content)) {
return $content;
}
$position = \strlen($prefix);
return substr($content, 0, $position).' '.substr($content, $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/Comment/CommentToPhpdocFixer.php | src/Fixer/Comment/CommentToPhpdocFixer.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\Comment;
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\CommentsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Utils;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* ignored_tags?: list<string>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* ignored_tags: list<string>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Kuba Werłos <werlos@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class CommentToPhpdocFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @var list<string>
*/
private array $ignoredTags = [];
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_COMMENT);
}
public function isRisky(): bool
{
return true;
}
/**
* {@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, PhpdocToCommentFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer.
* Must run after AlignMultilineCommentFixer.
*/
public function getPriority(): int
{
// Should be run before all other PHPDoc fixers
return 26;
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Comments with annotation should be docblock when used on structural elements.',
[
new CodeSample("<?php /* header */ \$x = true; /* @var bool \$isFoo */ \$isFoo = true;\n"),
new CodeSample("<?php\n// @todo do something later\n\$foo = 1;\n\n// @var int \$a\n\$a = foo();\n", ['ignored_tags' => ['todo']]),
],
null,
'Risky as new docblocks might mean more, e.g. a Doctrine entity might have a new column in database.',
);
}
protected function configurePostNormalisation(): void
{
$this->ignoredTags = array_map(
static fn (string $tag): string => strtolower($tag),
$this->configuration['ignored_tags'],
);
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('ignored_tags', 'List of ignored tags.'))
->setAllowedTypes(['string[]'])
->setDefault([])
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$commentsAnalyzer = new CommentsAnalyzer();
for ($index = 0, $limit = \count($tokens); $index < $limit; ++$index) {
$token = $tokens[$index];
if (!$token->isGivenKind(\T_COMMENT)) {
continue;
}
if ($commentsAnalyzer->isHeaderComment($tokens, $index)) {
continue;
}
if (!$commentsAnalyzer->isBeforeStructuralElement($tokens, $index)) {
continue;
}
if (Preg::match('~(?:#|//|/\*+|\R(?:\s*\*)?)\s*\@(?=\w+-(ignore|suppress))([a-zA-Z0-9_\\\-]+)(?=\s|\(|$)~', $tokens[$index]->getContent())) {
continue;
}
$commentIndices = $commentsAnalyzer->getCommentBlockIndices($tokens, $index);
if ($this->isCommentCandidate($tokens, $commentIndices)) {
$this->fixComment($tokens, $commentIndices);
}
$index = max($commentIndices);
}
}
/**
* @param list<int> $indices
*/
private function isCommentCandidate(Tokens $tokens, array $indices): bool
{
return array_reduce(
$indices,
function (bool $carry, int $index) use ($tokens): bool {
if ($carry) {
return true;
}
if (!Preg::match('~(?:#|//|/\*+|\R(?:\s*\*)?)\s*\@([a-zA-Z0-9_\\\-]+)(?=\s|\(|$)~', $tokens[$index]->getContent(), $matches)) {
return false;
}
return !\in_array(strtolower($matches[1]), $this->ignoredTags, true);
},
false,
);
}
/**
* @param non-empty-list<int> $indices
*/
private function fixComment(Tokens $tokens, array $indices): void
{
if (1 === \count($indices)) {
$this->fixCommentSingleLine($tokens, $indices[0]);
} else {
$this->fixCommentMultiLine($tokens, $indices);
}
}
private function fixCommentSingleLine(Tokens $tokens, int $index): void
{
$message = $this->getMessage($tokens[$index]->getContent());
if ('' !== trim(substr($message, 0, 1))) {
$message = ' '.$message;
}
if ('' !== trim(substr($message, -1))) {
$message .= ' ';
}
$tokens[$index] = new Token([\T_DOC_COMMENT, '/**'.$message.'*/']);
}
/**
* @param non-empty-list<int> $indices
*/
private function fixCommentMultiLine(Tokens $tokens, array $indices): void
{
$startIndex = $indices[0];
$indent = Utils::calculateTrailingWhitespaceIndent($tokens[$startIndex - 1]);
$newContent = '/**'.$this->whitespacesConfig->getLineEnding();
$count = max($indices);
for ($index = $startIndex; $index <= $count; ++$index) {
if (!$tokens[$index]->isComment()) {
continue;
}
if (str_contains($tokens[$index]->getContent(), '*/')) {
return;
}
$message = $this->getMessage($tokens[$index]->getContent());
if ('' !== trim(substr($message, 0, 1))) {
$message = ' '.$message;
}
$newContent .= $indent.' *'.$message.$this->whitespacesConfig->getLineEnding();
}
for ($index = $startIndex; $index <= $count; ++$index) {
$tokens->clearAt($index);
}
$newContent .= $indent.' */';
$tokens->insertAt($startIndex, new Token([\T_DOC_COMMENT, $newContent]));
}
private function getMessage(string $content): string
{
if (str_starts_with($content, '#')) {
return substr($content, 1);
}
if (str_starts_with($content, '//')) {
return substr($content, 2);
}
return rtrim(ltrim($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/Comment/HeaderCommentFixer.php | src/Fixer/Comment/HeaderCommentFixer.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\Comment;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\PregException;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Options;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* comment_type?: 'PHPDoc'|'comment',
* header: string,
* location?: 'after_declare_strict'|'after_open',
* separate?: 'both'|'bottom'|'none'|'top',
* validator?: null|string,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* comment_type: 'PHPDoc'|'comment',
* header: string,
* location: 'after_declare_strict'|'after_open',
* separate: 'both'|'bottom'|'none'|'top',
* validator: null|string,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Antonio J. García Lagar <aj@garcialagar.es>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class HeaderCommentFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @internal
*/
public const HEADER_PHPDOC = 'PHPDoc';
/**
* @internal
*/
public const HEADER_COMMENT = 'comment';
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Add, replace or remove header comment.',
[
new CodeSample(
<<<'PHP'
<?php
declare(strict_types=1);
namespace A\B;
echo 1;
PHP,
[
'header' => 'Made with love.',
],
),
new CodeSample(
<<<'PHP'
<?php
declare(strict_types=1);
namespace A\B;
echo 1;
PHP,
[
'header' => 'Made with love.',
'comment_type' => self::HEADER_PHPDOC,
'location' => 'after_open',
'separate' => 'bottom',
],
),
new CodeSample(
<<<'PHP'
<?php
declare(strict_types=1);
namespace A\B;
echo 1;
PHP,
[
'header' => 'Made with love.',
'comment_type' => self::HEADER_COMMENT,
'location' => 'after_declare_strict',
],
),
new CodeSample(
<<<'PHP'
<?php
declare(strict_types=1);
/*
* Made with love.
*
* Extra content.
*/
namespace A\B;
echo 1;
PHP,
[
'header' => 'Made with love.',
'validator' => '/Made with love(?P<EXTRA>.*)??/s',
'comment_type' => self::HEADER_COMMENT,
'location' => 'after_declare_strict',
],
),
new CodeSample(
<<<'PHP'
<?php
declare(strict_types=1);
/*
* Comment is not wanted here.
*/
namespace A\B;
echo 1;
PHP,
[
'header' => '',
],
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isMonolithicPhp() && !$tokens->isTokenKindFound(\T_OPEN_TAG_WITH_ECHO);
}
/**
* {@inheritdoc}
*
* Must run before BlankLinesBeforeNamespaceFixer, SingleBlankLineBeforeNamespaceFixer, SingleLineCommentStyleFixer.
* Must run after DeclareStrictTypesFixer, NoBlankLinesAfterPhpdocFixer.
*/
public function getPriority(): int
{
// When this fixer is configured with ["separate" => "bottom", "comment_type" => "PHPDoc"]
// and the target file has no namespace or declare() construct,
// the fixed header comment gets trimmed by NoBlankLinesAfterPhpdocFixer if we run before it.
return -30;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$headerAsComment = $this->getHeaderAsComment();
$location = $this->configuration['location'];
$locationIndices = [];
foreach (['after_open', 'after_declare_strict'] as $possibleLocation) {
$locationIndex = $this->findHeaderCommentInsertionIndex($tokens, $possibleLocation);
if (!isset($locationIndices[$locationIndex]) || $possibleLocation === $location) {
$locationIndices[$locationIndex] = $possibleLocation;
}
}
// pre-run to find existing comment, if dynamic content is allowed
if (null !== $this->configuration['validator']) {
foreach ($locationIndices as $possibleLocation) {
// figure out where the comment should be placed
$headerNewIndex = $this->findHeaderCommentInsertionIndex($tokens, $possibleLocation);
// check if there is already a comment
$headerCurrentIndex = $this->findHeaderCommentCurrentIndex($tokens, $headerAsComment, $headerNewIndex - 1);
if (null === $headerCurrentIndex) {
continue;
}
$currentHeaderComment = $tokens[$headerCurrentIndex]->getContent();
if ($this->doesTokenFulfillValidator($tokens[$headerCurrentIndex])) {
$headerAsComment = $currentHeaderComment;
}
}
}
foreach ($locationIndices as $possibleLocation) {
// figure out where the comment should be placed
$headerNewIndex = $this->findHeaderCommentInsertionIndex($tokens, $possibleLocation);
// check if there is already a comment
$headerCurrentIndex = $this->findHeaderCommentCurrentIndex($tokens, $headerAsComment, $headerNewIndex - 1);
if (null === $headerCurrentIndex) {
if ('' === $this->configuration['header'] || $possibleLocation !== $location) {
continue;
}
$this->insertHeader($tokens, $headerAsComment, $headerNewIndex);
continue;
}
$currentHeaderComment = $tokens[$headerCurrentIndex]->getContent();
$sameComment = $headerAsComment === $currentHeaderComment;
$expectedLocation = $possibleLocation === $location;
if (!$sameComment || !$expectedLocation) {
if ($expectedLocation xor $sameComment) {
$this->removeHeader($tokens, $headerCurrentIndex);
}
if ('' === $this->configuration['header']) {
continue;
}
if ($possibleLocation === $location) {
$this->insertHeader($tokens, $headerAsComment, $headerNewIndex);
}
continue;
}
$this->fixWhiteSpaceAroundHeader($tokens, $headerCurrentIndex);
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
$fixerName = $this->getName();
return new FixerConfigurationResolver([
(new FixerOptionBuilder('header', 'Proper header content.'))
->setAllowedTypes(['string'])
->setNormalizer(static function (Options $options, string $value) use ($fixerName): string {
if ('' === trim($value)) {
return '';
}
if (str_contains($value, '*/')) {
throw new InvalidFixerConfigurationException($fixerName, 'Cannot use \'*/\' in header.');
}
return $value;
})
->getOption(),
(new FixerOptionBuilder('validator', 'RegEx validator for header content.'))
->setAllowedTypes(['string', 'null'])
->setNormalizer(static function (Options $options, ?string $value) use ($fixerName): ?string {
if (null !== $value) {
try {
Preg::match($value, '');
} catch (PregException $exception) {
throw new InvalidFixerConfigurationException($fixerName, 'Provided RegEx is not valid.');
}
}
return $value;
})
->setDefault(null)
->getOption(),
(new FixerOptionBuilder('comment_type', 'Comment syntax type.'))
->setAllowedValues([self::HEADER_PHPDOC, self::HEADER_COMMENT])
->setDefault(self::HEADER_COMMENT)
->getOption(),
(new FixerOptionBuilder('location', 'The location of the inserted header.'))
->setAllowedValues(['after_open', 'after_declare_strict'])
->setDefault('after_declare_strict')
->getOption(),
(new FixerOptionBuilder('separate', 'Whether the header should be separated from the file content with a new line.'))
->setAllowedValues(['both', 'top', 'bottom', 'none'])
->setDefault('both')
->getOption(),
]);
}
private function doesTokenFulfillValidator(Token $token): bool
{
if (null === $this->configuration['validator']) {
throw new \LogicException(\sprintf("Cannot call '%s' method while missing config:validator.", __METHOD__));
}
$currentHeaderComment = $token->getContent();
$lines = implode("\n", array_map(
static fn (string $line): string => ' *' === $line ? '' : (str_starts_with($line, ' * ') ? substr($line, 3) : $line),
\array_slice(explode("\n", $currentHeaderComment), 1, -1),
));
return Preg::match($this->configuration['validator'], $lines);
}
/**
* Enclose the given text in a comment block.
*/
private function getHeaderAsComment(): string
{
$lineEnding = $this->whitespacesConfig->getLineEnding();
$comment = (self::HEADER_COMMENT === $this->configuration['comment_type'] ? '/*' : '/**').$lineEnding;
$lines = explode("\n", str_replace("\r", '', $this->configuration['header']));
foreach ($lines as $line) {
$comment .= rtrim(' * '.$line).$lineEnding;
}
return $comment.' */';
}
private function findHeaderCommentCurrentIndex(Tokens $tokens, string $headerAsComment, int $headerNewIndex): ?int
{
$index = $tokens->getNextNonWhitespace($headerNewIndex);
if (null === $index || !$tokens[$index]->isComment()) {
return null;
}
$next = $index + 1;
if (!isset($tokens[$next]) || \in_array($this->configuration['separate'], ['top', 'none'], true) || !$tokens[$index]->isGivenKind(\T_DOC_COMMENT)) {
return $index;
}
if ($tokens[$next]->isWhitespace()) {
if (!Preg::match('/^\h*\R\h*$/D', $tokens[$next]->getContent())) {
return $index;
}
++$next;
}
if (!isset($tokens[$next]) || !$tokens[$next]->isClassy() && !$tokens[$next]->isGivenKind(\T_FUNCTION)) {
return $index;
}
if (
$headerAsComment === $tokens[$index]->getContent()
|| (null !== $this->configuration['validator'] && $this->doesTokenFulfillValidator($tokens[$index]))
) {
return $index;
}
return null;
}
/**
* Find the index where the header comment must be inserted.
*/
private function findHeaderCommentInsertionIndex(Tokens $tokens, string $location): int
{
$openTagIndex = $tokens[0]->isGivenKind(\T_INLINE_HTML) ? 1 : 0;
if ('after_open' === $location) {
return $openTagIndex + 1;
}
$index = $tokens->getNextMeaningfulToken($openTagIndex);
if (null === $index) {
return $openTagIndex + 1; // file without meaningful tokens but an open tag, comment should always be placed directly after the open tag
}
if (!$tokens[$index]->isGivenKind(\T_DECLARE)) {
return $openTagIndex + 1;
}
$next = $tokens->getNextMeaningfulToken($index);
if (null === $next || !$tokens[$next]->equals('(')) {
return $openTagIndex + 1;
}
$next = $tokens->getNextMeaningfulToken($next);
if (null === $next || !$tokens[$next]->equals([\T_STRING, 'strict_types'], false)) {
return $openTagIndex + 1;
}
$next = $tokens->getNextMeaningfulToken($next);
if (null === $next || !$tokens[$next]->equals('=')) {
return $openTagIndex + 1;
}
$next = $tokens->getNextMeaningfulToken($next);
if (null === $next || !$tokens[$next]->isGivenKind(\T_LNUMBER)) {
return $openTagIndex + 1;
}
$next = $tokens->getNextMeaningfulToken($next);
if (null === $next || !$tokens[$next]->equals(')')) {
return $openTagIndex + 1;
}
$next = $tokens->getNextMeaningfulToken($next);
if (null === $next || !$tokens[$next]->equals(';')) { // don't insert after close tag
return $openTagIndex + 1;
}
return $next + 1;
}
private function fixWhiteSpaceAroundHeader(Tokens $tokens, int $headerIndex): void
{
$lineEnding = $this->whitespacesConfig->getLineEnding();
// fix lines after header comment
if (
('both' === $this->configuration['separate'] || 'bottom' === $this->configuration['separate'])
&& null !== $tokens->getNextMeaningfulToken($headerIndex)
) {
$expectedLineCount = 2;
} else {
$expectedLineCount = 1;
}
if ($headerIndex === \count($tokens) - 1) {
$tokens->insertAt($headerIndex + 1, new Token([\T_WHITESPACE, str_repeat($lineEnding, $expectedLineCount)]));
} else {
$lineBreakCount = $this->getLineBreakCount($tokens, $headerIndex, 1);
if ($lineBreakCount < $expectedLineCount) {
$missing = str_repeat($lineEnding, $expectedLineCount - $lineBreakCount);
if ($tokens[$headerIndex + 1]->isWhitespace()) {
$tokens[$headerIndex + 1] = new Token([\T_WHITESPACE, $missing.$tokens[$headerIndex + 1]->getContent()]);
} else {
$tokens->insertAt($headerIndex + 1, new Token([\T_WHITESPACE, $missing]));
}
} elseif ($lineBreakCount > $expectedLineCount && $tokens[$headerIndex + 1]->isWhitespace()) {
$newLinesToRemove = $lineBreakCount - $expectedLineCount;
$tokens[$headerIndex + 1] = new Token([
\T_WHITESPACE,
Preg::replace("/^\\R{{$newLinesToRemove}}/", '', $tokens[$headerIndex + 1]->getContent()),
]);
}
}
// fix lines before header comment
$expectedLineCount = 'both' === $this->configuration['separate'] || 'top' === $this->configuration['separate'] ? 2 : 1;
$prev = $tokens->getPrevNonWhitespace($headerIndex);
$regex = '/\h$/';
if ($tokens[$prev]->isGivenKind(\T_OPEN_TAG) && Preg::match($regex, $tokens[$prev]->getContent())) {
$tokens[$prev] = new Token([\T_OPEN_TAG, Preg::replace($regex, $lineEnding, $tokens[$prev]->getContent())]);
}
$lineBreakCount = $this->getLineBreakCount($tokens, $headerIndex, -1);
if ($lineBreakCount < $expectedLineCount) {
// because of the way the insert index was determined for header comment there cannot be an empty token here
$tokens->insertAt($headerIndex, new Token([\T_WHITESPACE, str_repeat($lineEnding, $expectedLineCount - $lineBreakCount)]));
}
}
private function getLineBreakCount(Tokens $tokens, int $index, int $direction): int
{
$whitespace = '';
for ($index += $direction; isset($tokens[$index]); $index += $direction) {
$token = $tokens[$index];
if ($token->isWhitespace()) {
$whitespace .= $token->getContent();
continue;
}
if (-1 === $direction && $token->isGivenKind(\T_OPEN_TAG)) {
$whitespace .= $token->getContent();
}
if ('' !== $token->getContent()) {
break;
}
}
return substr_count($whitespace, "\n");
}
private function removeHeader(Tokens $tokens, int $index): void
{
$prevIndex = $index - 1;
$prevToken = $tokens[$prevIndex];
$newlineRemoved = false;
if ($prevToken->isWhitespace()) {
$content = $prevToken->getContent();
if (Preg::match('/\R/', $content)) {
$newlineRemoved = true;
}
$content = Preg::replace('/\R?\h*$/', '', $content);
$tokens->ensureWhitespaceAtIndex($prevIndex, 0, $content);
}
$nextIndex = $index + 1;
$nextToken = $tokens[$nextIndex] ?? null;
if (!$newlineRemoved && null !== $nextToken && $nextToken->isWhitespace()) {
$content = Preg::replace('/^\R/', '', $nextToken->getContent());
$tokens->ensureWhitespaceAtIndex($nextIndex, 0, $content);
}
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
private function insertHeader(Tokens $tokens, string $headerAsComment, int $index): void
{
$tokens->insertAt($index, new Token([self::HEADER_COMMENT === $this->configuration['comment_type'] ? \T_COMMENT : \T_DOC_COMMENT, $headerAsComment]));
$this->fixWhiteSpaceAroundHeader($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/Comment/MultilineCommentOpeningClosingFixer.php | src/Fixer/Comment/MultilineCommentOpeningClosingFixer.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\Comment;
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 Filippo Tessarotto <zoeslam@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class MultilineCommentOpeningClosingFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'DocBlocks must start with two asterisks, multiline comments must start with a single asterisk, after the opening slash. Both must end with a single asterisk before the closing slash.',
[
new CodeSample(
<<<'EOT'
<?php
/******
* Multiline comment with arbitrary asterisks count
******/
/**\
* Multiline comment that seems a DocBlock
*/
/**
* DocBlock with arbitrary asterisk count at the end
**/
EOT,
),
],
);
}
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) {
$originalContent = $token->getContent();
if (
!$token->isGivenKind(\T_DOC_COMMENT)
&& !($token->isGivenKind(\T_COMMENT) && str_starts_with($originalContent, '/*'))
) {
continue;
}
$newContent = $originalContent;
// Fix opening
if ($token->isGivenKind(\T_COMMENT)) {
$newContent = Preg::replace('/^\/\*{2,}(?!\/)/', '/*', $newContent);
}
// Fix closing
$newContent = Preg::replace('/(?<!\/)\*{2,}\/$/', '*/', $newContent);
if ($newContent !== $originalContent) {
$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/Comment/NoEmptyCommentFixer.php | src/Fixer/Comment/NoEmptyCommentFixer.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\Comment;
use PhpCsFixer\AbstractFixer;
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 NoEmptyCommentFixer extends AbstractFixer
{
private const TYPE_HASH = 1;
private const TYPE_DOUBLE_SLASH = 2;
private const TYPE_SLASH_ASTERISK = 3;
/**
* {@inheritdoc}
*
* Must run before NoExtraBlankLinesFixer, NoTrailingWhitespaceFixer, NoWhitespaceInBlankLineFixer.
* Must run after PhpdocToCommentFixer.
*/
public function getPriority(): int
{
return 2;
}
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There should not be any empty comments.',
[new CodeSample("<?php\n//\n#\n/* */\n")],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_COMMENT);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = 1, $count = \count($tokens); $index < $count; ++$index) {
if (!$tokens[$index]->isGivenKind(\T_COMMENT)) {
continue;
}
$blockInfo = $this->getCommentBlock($tokens, $index);
$blockStart = $blockInfo['blockStart'];
$index = $blockInfo['blockEnd'];
$isEmpty = $blockInfo['isEmpty'];
if (false === $isEmpty) {
continue;
}
for ($i = $blockStart; $i <= $index; ++$i) {
$tokens->clearTokenAndMergeSurroundingWhitespace($i);
}
}
}
/**
* Return the start index, end index and a flag stating if the comment block is empty.
*
* @param int $index T_COMMENT index
*
* @return array{blockStart: int, blockEnd: int, isEmpty: bool}
*/
private function getCommentBlock(Tokens $tokens, int $index): array
{
$commentType = $this->getCommentType($tokens[$index]->getContent());
$empty = $this->isEmptyComment($tokens[$index]->getContent());
if (self::TYPE_SLASH_ASTERISK === $commentType) {
return [
'blockStart' => $index,
'blockEnd' => $index,
'isEmpty' => $empty,
];
}
$start = $index;
$count = \count($tokens);
++$index;
for (; $index < $count; ++$index) {
if ($tokens[$index]->isComment()) {
if ($commentType !== $this->getCommentType($tokens[$index]->getContent())) {
break;
}
if ($empty) { // don't retest if already known the block not being empty
$empty = $this->isEmptyComment($tokens[$index]->getContent());
}
continue;
}
if (!$tokens[$index]->isWhitespace() || $this->getLineBreakCount($tokens, $index, $index + 1) > 1) {
break;
}
}
return [
'blockStart' => $start,
'blockEnd' => $index - 1,
'isEmpty' => $empty,
];
}
private function getCommentType(string $content): int
{
if (str_starts_with($content, '#')) {
return self::TYPE_HASH;
}
if ('*' === $content[1]) {
return self::TYPE_SLASH_ASTERISK;
}
return self::TYPE_DOUBLE_SLASH;
}
private function getLineBreakCount(Tokens $tokens, int $whiteStart, int $whiteEnd): int
{
$lineCount = 0;
for ($i = $whiteStart; $i < $whiteEnd; ++$i) {
$lineCount += Preg::matchAll('/\R/u', $tokens[$i]->getContent());
}
return $lineCount;
}
private function isEmptyComment(string $content): bool
{
$type = $this->getCommentType($content);
return Preg::match([
self::TYPE_HASH => '|^#\s*$|', // single line comment starting with '#'
self::TYPE_SLASH_ASTERISK => '|^/\*[\s\*]*\*+/$|', // comment starting with '/*' and ending with '*/' (but not a PHPDoc)
self::TYPE_DOUBLE_SLASH => '|^//\s*$|', // single line comment starting with '//'
][$type], $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/Comment/NoTrailingWhitespaceInCommentFixer.php | src/Fixer/Comment/NoTrailingWhitespaceInCommentFixer.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\Comment;
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 Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoTrailingWhitespaceInCommentFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There must be no trailing whitespace at the end of lines in comments and PHPDocs.',
[new CodeSample('<?php
// This is '.'
// a comment. '.'
')],
);
}
/**
* {@inheritdoc}
*
* Must run after PhpdocNoUselessInheritdocFixer.
*/
public function getPriority(): int
{
return 0;
}
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->isGivenKind(\T_DOC_COMMENT)) {
$tokens[$index] = new Token([\T_DOC_COMMENT, Preg::replace('/(*ANY)[\h]+$/m', '', $token->getContent())]);
continue;
}
if ($token->isGivenKind(\T_COMMENT)) {
if (str_starts_with($token->getContent(), '/*')) {
$tokens[$index] = new Token([\T_COMMENT, Preg::replace('/(*ANY)[\h]+$/m', '', $token->getContent())]);
} elseif (isset($tokens[$index + 1]) && $tokens[$index + 1]->isWhitespace()) {
$trimmedContent = ltrim($tokens[$index + 1]->getContent(), " \t");
$tokens->ensureWhitespaceAtIndex($index + 1, 0, $trimmedContent);
}
}
}
}
}
| 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/DoctrineAnnotation/DoctrineAnnotationArrayAssignmentFixer.php | src/Fixer/DoctrineAnnotation/DoctrineAnnotationArrayAssignmentFixer.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\DoctrineAnnotation;
use PhpCsFixer\AbstractDoctrineAnnotationFixer;
use PhpCsFixer\Doctrine\Annotation\DocLexer;
use PhpCsFixer\Doctrine\Annotation\Tokens;
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;
/**
* Forces the configured operator for assignment in arrays in Doctrine Annotations.
*
* @phpstan-type _AutogeneratedInputConfiguration array{
* ignored_tags?: list<string>,
* operator?: ':'|'=',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* ignored_tags: list<string>,
* operator: ':'|'=',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class DoctrineAnnotationArrayAssignmentFixer extends AbstractDoctrineAnnotationFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Doctrine annotations must use configured operator for assignment in arrays.',
[
new CodeSample(
"<?php\n/**\n * @Foo({bar : \"baz\"})\n */\nclass Bar {}\n",
),
new CodeSample(
"<?php\n/**\n * @Foo({bar = \"baz\"})\n */\nclass Bar {}\n",
['operator' => ':'],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before DoctrineAnnotationSpacesFixer.
*/
public function getPriority(): int
{
return 1;
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
$options = parent::createConfigurationDefinition()->getOptions();
$options[] = (new FixerOptionBuilder('operator', 'The operator to use.'))
->setAllowedValues(['=', ':'])
->setDefault('=')
->getOption()
;
return new FixerConfigurationResolver($options);
}
protected function fixAnnotations(Tokens $doctrineAnnotationTokens): void
{
$scopes = [];
foreach ($doctrineAnnotationTokens as $token) {
if ($token->isType(DocLexer::T_OPEN_PARENTHESIS)) {
$scopes[] = 'annotation';
continue;
}
if ($token->isType(DocLexer::T_OPEN_CURLY_BRACES)) {
$scopes[] = 'array';
continue;
}
if ($token->isType([DocLexer::T_CLOSE_PARENTHESIS, DocLexer::T_CLOSE_CURLY_BRACES])) {
array_pop($scopes);
continue;
}
if ('array' === end($scopes) && $token->isType([DocLexer::T_EQUALS, DocLexer::T_COLON])) {
$token->setContent($this->configuration['operator']);
}
}
}
}
| 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/DoctrineAnnotation/DoctrineAnnotationSpacesFixer.php | src/Fixer/DoctrineAnnotation/DoctrineAnnotationSpacesFixer.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\DoctrineAnnotation;
use PhpCsFixer\AbstractDoctrineAnnotationFixer;
use PhpCsFixer\Doctrine\Annotation\DocLexer;
use PhpCsFixer\Doctrine\Annotation\Token;
use PhpCsFixer\Doctrine\Annotation\Tokens;
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;
/**
* Fixes spaces around commas and assignment operators in Doctrine annotations.
*
* @phpstan-type _AutogeneratedInputConfiguration array{
* after_argument_assignments?: bool|null,
* after_array_assignments_colon?: bool|null,
* after_array_assignments_equals?: bool|null,
* around_commas?: bool,
* around_parentheses?: bool,
* before_argument_assignments?: bool|null,
* before_array_assignments_colon?: bool|null,
* before_array_assignments_equals?: bool|null,
* ignored_tags?: list<string>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* after_argument_assignments: bool|null,
* after_array_assignments_colon: bool|null,
* after_array_assignments_equals: bool|null,
* around_commas: bool,
* around_parentheses: bool,
* before_argument_assignments: bool|null,
* before_array_assignments_colon: bool|null,
* before_array_assignments_equals: bool|null,
* ignored_tags: list<string>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class DoctrineAnnotationSpacesFixer extends AbstractDoctrineAnnotationFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Fixes spaces in Doctrine annotations.',
[
new CodeSample(
"<?php\n/**\n * @Foo ( )\n */\nclass Bar {}\n\n/**\n * @Foo(\"bar\" ,\"baz\")\n */\nclass Bar2 {}\n\n/**\n * @Foo(foo = \"foo\", bar = {\"foo\":\"foo\", \"bar\"=\"bar\"})\n */\nclass Bar3 {}\n",
),
new CodeSample(
"<?php\n/**\n * @Foo(foo = \"foo\", bar = {\"foo\":\"foo\", \"bar\"=\"bar\"})\n */\nclass Bar {}\n",
['after_array_assignments_equals' => false, 'before_array_assignments_equals' => false],
),
],
'There must not be any space around parentheses; commas must be preceded by no space and followed by one space; there must be no space around named arguments assignment operator; there must be one space around array assignment operator.',
);
}
/**
* {@inheritdoc}
*
* Must run after DoctrineAnnotationArrayAssignmentFixer.
*/
public function getPriority(): int
{
return 0;
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
...parent::createConfigurationDefinition()->getOptions(),
(new FixerOptionBuilder('around_parentheses', 'Whether to fix spaces around parentheses.'))
->setAllowedTypes(['bool'])
->setDefault(true)
->getOption(),
(new FixerOptionBuilder('around_commas', 'Whether to fix spaces around commas.'))
->setAllowedTypes(['bool'])
->setDefault(true)
->getOption(),
(new FixerOptionBuilder('before_argument_assignments', 'Whether to add, remove or ignore spaces before argument assignment operator.'))
->setAllowedTypes(['null', 'bool'])
->setDefault(false)
->getOption(),
(new FixerOptionBuilder('after_argument_assignments', 'Whether to add, remove or ignore spaces after argument assignment operator.'))
->setAllowedTypes(['null', 'bool'])
->setDefault(false)
->getOption(),
(new FixerOptionBuilder('before_array_assignments_equals', 'Whether to add, remove or ignore spaces before array `=` assignment operator.'))
->setAllowedTypes(['null', 'bool'])
->setDefault(true)
->getOption(),
(new FixerOptionBuilder('after_array_assignments_equals', 'Whether to add, remove or ignore spaces after array assignment `=` operator.'))
->setAllowedTypes(['null', 'bool'])
->setDefault(true)
->getOption(),
(new FixerOptionBuilder('before_array_assignments_colon', 'Whether to add, remove or ignore spaces before array `:` assignment operator.'))
->setAllowedTypes(['null', 'bool'])
->setDefault(true)
->getOption(),
(new FixerOptionBuilder('after_array_assignments_colon', 'Whether to add, remove or ignore spaces after array assignment `:` operator.'))
->setAllowedTypes(['null', 'bool'])
->setDefault(true)
->getOption(),
]);
}
protected function fixAnnotations(Tokens $doctrineAnnotationTokens): void
{
if (true === $this->configuration['around_parentheses']) {
$this->fixSpacesAroundParentheses($doctrineAnnotationTokens);
}
if (true === $this->configuration['around_commas']) {
$this->fixSpacesAroundCommas($doctrineAnnotationTokens);
}
if (
null !== $this->configuration['before_argument_assignments']
|| null !== $this->configuration['after_argument_assignments']
|| null !== $this->configuration['before_array_assignments_equals']
|| null !== $this->configuration['after_array_assignments_equals']
|| null !== $this->configuration['before_array_assignments_colon']
|| null !== $this->configuration['after_array_assignments_colon']
) {
$this->fixAroundAssignments($doctrineAnnotationTokens);
}
}
private function fixSpacesAroundParentheses(Tokens $tokens): void
{
$inAnnotationUntilIndex = null;
foreach ($tokens as $index => $token) {
if (null !== $inAnnotationUntilIndex) {
if ($index === $inAnnotationUntilIndex) {
$inAnnotationUntilIndex = null;
continue;
}
} elseif ($token->isType(DocLexer::T_AT)) {
$endIndex = $tokens->getAnnotationEnd($index);
if (null !== $endIndex) {
$inAnnotationUntilIndex = $endIndex + 1;
}
continue;
}
if (null === $inAnnotationUntilIndex) {
continue;
}
if (!$token->isType([DocLexer::T_OPEN_PARENTHESIS, DocLexer::T_CLOSE_PARENTHESIS])) {
continue;
}
if ($token->isType(DocLexer::T_OPEN_PARENTHESIS)) {
$token = $tokens[$index - 1];
if ($token->isType(DocLexer::T_NONE)) {
$token->clear();
}
$token = $tokens[$index + 1];
} else {
$token = $tokens[$index - 1];
}
if ($token->isType(DocLexer::T_NONE)) {
if (str_contains($token->getContent(), "\n")) {
continue;
}
$token->clear();
}
}
}
private function fixSpacesAroundCommas(Tokens $tokens): void
{
$inAnnotationUntilIndex = null;
foreach ($tokens as $index => $token) {
if (null !== $inAnnotationUntilIndex) {
if ($index === $inAnnotationUntilIndex) {
$inAnnotationUntilIndex = null;
continue;
}
} elseif ($token->isType(DocLexer::T_AT)) {
$endIndex = $tokens->getAnnotationEnd($index);
if (null !== $endIndex) {
$inAnnotationUntilIndex = $endIndex;
}
continue;
}
if (null === $inAnnotationUntilIndex) {
continue;
}
if (!$token->isType(DocLexer::T_COMMA)) {
continue;
}
$token = $tokens[$index - 1];
if ($token->isType(DocLexer::T_NONE)) {
$token->clear();
}
if ($index < \count($tokens) - 1 && !Preg::match('/^\s/', $tokens[$index + 1]->getContent())) {
$tokens->insertAt($index + 1, new Token(DocLexer::T_NONE, ' '));
}
}
}
private function fixAroundAssignments(Tokens $tokens): void
{
$beforeArguments = $this->configuration['before_argument_assignments'];
$afterArguments = $this->configuration['after_argument_assignments'];
$beforeArraysEquals = $this->configuration['before_array_assignments_equals'];
$afterArraysEquals = $this->configuration['after_array_assignments_equals'];
$beforeArraysColon = $this->configuration['before_array_assignments_colon'];
$afterArraysColon = $this->configuration['after_array_assignments_colon'];
$scopes = [];
foreach ($tokens as $index => $token) {
$endScopeType = end($scopes);
if (false !== $endScopeType && $token->isType($endScopeType)) {
array_pop($scopes);
continue;
}
if ($token->isType(DocLexer::T_AT)) {
$scopes[] = DocLexer::T_CLOSE_PARENTHESIS;
continue;
}
if ($token->isType(DocLexer::T_OPEN_CURLY_BRACES)) {
$scopes[] = DocLexer::T_CLOSE_CURLY_BRACES;
continue;
}
if (DocLexer::T_CLOSE_PARENTHESIS === $endScopeType && $token->isType(DocLexer::T_EQUALS)) {
$this->updateSpacesAfter($tokens, $index, $afterArguments);
$this->updateSpacesBefore($tokens, $index, $beforeArguments);
continue;
}
if (DocLexer::T_CLOSE_CURLY_BRACES === $endScopeType) {
if ($token->isType(DocLexer::T_EQUALS)) {
$this->updateSpacesAfter($tokens, $index, $afterArraysEquals);
$this->updateSpacesBefore($tokens, $index, $beforeArraysEquals);
continue;
}
if ($token->isType(DocLexer::T_COLON)) {
$this->updateSpacesAfter($tokens, $index, $afterArraysColon);
$this->updateSpacesBefore($tokens, $index, $beforeArraysColon);
}
}
}
}
private function updateSpacesAfter(Tokens $tokens, int $index, ?bool $insert): void
{
$this->updateSpacesAt($tokens, $index + 1, $index + 1, $insert);
}
private function updateSpacesBefore(Tokens $tokens, int $index, ?bool $insert): void
{
$this->updateSpacesAt($tokens, $index - 1, $index, $insert);
}
private function updateSpacesAt(Tokens $tokens, int $index, int $insertIndex, ?bool $insert): void
{
if (null === $insert) {
return;
}
$token = $tokens[$index];
if ($insert) {
if (!$token->isType(DocLexer::T_NONE)) {
$tokens->insertAt($insertIndex, $token = new Token());
}
$token->setContent(' ');
} elseif ($token->isType(DocLexer::T_NONE)) {
$token->clear();
}
}
}
| 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/DoctrineAnnotation/DoctrineAnnotationIndentationFixer.php | src/Fixer/DoctrineAnnotation/DoctrineAnnotationIndentationFixer.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\DoctrineAnnotation;
use PhpCsFixer\AbstractDoctrineAnnotationFixer;
use PhpCsFixer\Doctrine\Annotation\DocLexer;
use PhpCsFixer\Doctrine\Annotation\Tokens;
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{
* ignored_tags?: list<string>,
* indent_mixed_lines?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* ignored_tags: list<string>,
* indent_mixed_lines: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class DoctrineAnnotationIndentationFixer extends AbstractDoctrineAnnotationFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Doctrine annotations must be indented with four spaces.',
[
new CodeSample("<?php\n/**\n * @Foo(\n * foo=\"foo\"\n * )\n */\nclass Bar {}\n"),
new CodeSample(
"<?php\n/**\n * @Foo({@Bar,\n * @Baz})\n */\nclass Bar {}\n",
['indent_mixed_lines' => true],
),
],
);
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
...parent::createConfigurationDefinition()->getOptions(),
(new FixerOptionBuilder('indent_mixed_lines', 'Whether to indent lines that have content before closing parenthesis.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
protected function fixAnnotations(Tokens $doctrineAnnotationTokens): void
{
$annotationPositions = [];
for ($index = 0, $max = \count($doctrineAnnotationTokens); $index < $max; ++$index) {
if (!$doctrineAnnotationTokens[$index]->isType(DocLexer::T_AT)) {
continue;
}
$annotationEndIndex = $doctrineAnnotationTokens->getAnnotationEnd($index);
if (null === $annotationEndIndex) {
return;
}
$annotationPositions[] = [$index, $annotationEndIndex];
$index = $annotationEndIndex;
}
$indentLevel = 0;
foreach ($doctrineAnnotationTokens as $index => $token) {
if (!$token->isType(DocLexer::T_NONE) || !str_contains($token->getContent(), "\n")) {
continue;
}
if (!$this->indentationCanBeFixed($doctrineAnnotationTokens, $index, $annotationPositions)) {
continue;
}
$braces = $this->getLineBracesCount($doctrineAnnotationTokens, $index);
$delta = $braces[0] - $braces[1];
$mixedBraces = 0 === $delta && $braces[0] > 0;
$extraIndentLevel = 0;
if ($indentLevel > 0 && ($delta < 0 || $mixedBraces)) {
--$indentLevel;
if (true === $this->configuration['indent_mixed_lines'] && $this->isClosingLineWithMeaningfulContent($doctrineAnnotationTokens, $index)) {
$extraIndentLevel = 1;
}
}
$token->setContent(Preg::replace(
'/(\n( +\*)?) *$/',
'$1'.str_repeat(' ', 4 * ($indentLevel + $extraIndentLevel) + 1),
$token->getContent(),
));
if ($delta > 0 || $mixedBraces) {
++$indentLevel;
}
}
}
/**
* @return array{int, int}
*/
private function getLineBracesCount(Tokens $tokens, int $index): array
{
$opening = 0;
$closing = 0;
while (isset($tokens[++$index])) {
$token = $tokens[$index];
if ($token->isType(DocLexer::T_NONE) && str_contains($token->getContent(), "\n")) {
break;
}
if ($token->isType([DocLexer::T_OPEN_PARENTHESIS, DocLexer::T_OPEN_CURLY_BRACES])) {
++$opening;
continue;
}
if (!$token->isType([DocLexer::T_CLOSE_PARENTHESIS, DocLexer::T_CLOSE_CURLY_BRACES])) {
continue;
}
if ($opening > 0) {
--$opening;
} else {
++$closing;
}
}
return [$opening, $closing];
}
private function isClosingLineWithMeaningfulContent(Tokens $tokens, int $index): bool
{
while (isset($tokens[++$index])) {
$token = $tokens[$index];
if ($token->isType(DocLexer::T_NONE)) {
if (str_contains($token->getContent(), "\n")) {
return false;
}
continue;
}
return !$token->isType([DocLexer::T_CLOSE_PARENTHESIS, DocLexer::T_CLOSE_CURLY_BRACES]);
}
return false;
}
/**
* @param list<array{int, int}> $annotationPositions Pairs of begin and end indices of main annotations
*/
private function indentationCanBeFixed(Tokens $tokens, int $newLineTokenIndex, array $annotationPositions): bool
{
foreach ($annotationPositions as $position) {
if ($newLineTokenIndex >= $position[0] && $newLineTokenIndex <= $position[1]) {
return true;
}
}
for ($index = $newLineTokenIndex + 1, $max = \count($tokens); $index < $max; ++$index) {
$token = $tokens[$index];
if (str_contains($token->getContent(), "\n")) {
return false;
}
return $tokens[$index]->isType(DocLexer::T_AT);
}
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/DoctrineAnnotation/DoctrineAnnotationBracesFixer.php | src/Fixer/DoctrineAnnotation/DoctrineAnnotationBracesFixer.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\DoctrineAnnotation;
use PhpCsFixer\AbstractDoctrineAnnotationFixer;
use PhpCsFixer\Doctrine\Annotation\DocLexer;
use PhpCsFixer\Doctrine\Annotation\Token;
use PhpCsFixer\Doctrine\Annotation\Tokens;
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;
/**
* Adds braces to Doctrine annotations when missing.
*
* @phpstan-type _AutogeneratedInputConfiguration array{
* ignored_tags?: list<string>,
* syntax?: 'with_braces'|'without_braces',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* ignored_tags: list<string>,
* syntax: 'with_braces'|'without_braces',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class DoctrineAnnotationBracesFixer extends AbstractDoctrineAnnotationFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Doctrine annotations without arguments must use the configured syntax.',
[
new CodeSample(
"<?php\n/**\n * @Foo()\n */\nclass Bar {}\n",
),
new CodeSample(
"<?php\n/**\n * @Foo\n */\nclass Bar {}\n",
['syntax' => 'with_braces'],
),
],
);
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
...parent::createConfigurationDefinition()->getOptions(),
(new FixerOptionBuilder('syntax', 'Whether to add or remove braces.'))
->setAllowedValues(['with_braces', 'without_braces'])
->setDefault('without_braces')
->getOption(),
]);
}
protected function fixAnnotations(Tokens $doctrineAnnotationTokens): void
{
if ('without_braces' === $this->configuration['syntax']) {
$this->removesBracesFromAnnotations($doctrineAnnotationTokens);
} else {
$this->addBracesToAnnotations($doctrineAnnotationTokens);
}
}
private function addBracesToAnnotations(Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if (!$token->isType(DocLexer::T_AT)) {
continue;
}
$braceIndex = $tokens->getNextMeaningfulToken($index + 1);
if (null !== $braceIndex && $tokens[$braceIndex]->isType(DocLexer::T_OPEN_PARENTHESIS)) {
continue;
}
$tokens->insertAt($index + 2, new Token(DocLexer::T_OPEN_PARENTHESIS, '('));
$tokens->insertAt($index + 3, new Token(DocLexer::T_CLOSE_PARENTHESIS, ')'));
}
}
private function removesBracesFromAnnotations(Tokens $tokens): void
{
for ($index = 0, $max = \count($tokens); $index < $max; ++$index) {
if (!$tokens[$index]->isType(DocLexer::T_AT)) {
continue;
}
$openBraceIndex = $tokens->getNextMeaningfulToken($index + 1);
if (null === $openBraceIndex) {
continue;
}
if (!$tokens[$openBraceIndex]->isType(DocLexer::T_OPEN_PARENTHESIS)) {
continue;
}
$closeBraceIndex = $tokens->getNextMeaningfulToken($openBraceIndex);
if (null === $closeBraceIndex) {
continue;
}
if (!$tokens[$closeBraceIndex]->isType(DocLexer::T_CLOSE_PARENTHESIS)) {
continue;
}
for ($currentIndex = $index + 2; $currentIndex <= $closeBraceIndex; ++$currentIndex) {
$tokens[$currentIndex]->clear();
}
}
}
}
| 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/Naming/NoHomoglyphNamesFixer.php | src/Fixer/Naming/NoHomoglyphNamesFixer.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\Naming;
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 Fred Cox <mcfedr@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 NoHomoglyphNamesFixer extends AbstractFixer
{
/**
* Used the program https://github.com/mcfedr/homoglyph-download
* to generate this list from
* http://homoglyphs.net/?text=abcdefghijklmnopqrstuvwxyz&lang=en&exc7=1&exc8=1&exc13=1&exc14=1.
*
* Symbols replaced include
* - Latin homoglyphs
* - IPA extensions
* - Greek and Coptic
* - Cyrillic
* - Cyrillic Supplement
* - Letterlike Symbols
* - Latin Numbers
* - Fullwidth Latin
*
* This is not the complete list of unicode homographs, but limited
* to those you are more likely to have typed/copied by accident
*
* @var array<string, string>
*/
private const REPLACEMENTS = [
'O' => '0',
'0' => '0',
'I' => '1',
'1' => '1',
'2' => '2',
'3' => '3',
'4' => '4',
'5' => '5',
'6' => '6',
'7' => '7',
'8' => '8',
'9' => '9',
'Α' => 'A',
'А' => 'A',
'A' => 'A',
'ʙ' => 'B',
'Β' => 'B',
'В' => 'B',
'B' => 'B',
'Ϲ' => 'C',
'С' => 'C',
'Ⅽ' => 'C',
'C' => 'C',
'Ⅾ' => 'D',
'D' => 'D',
'Ε' => 'E',
'Е' => 'E',
'E' => 'E',
'Ϝ' => 'F',
'F' => 'F',
'ɢ' => 'G',
'Ԍ' => 'G',
'G' => 'G',
'ʜ' => 'H',
'Η' => 'H',
'Н' => 'H',
'H' => 'H',
'l' => 'I',
'Ι' => 'I',
'І' => 'I',
'Ⅰ' => 'I',
'I' => 'I',
'Ј' => 'J',
'J' => 'J',
'Κ' => 'K',
'К' => 'K',
'K' => 'K',
'K' => 'K',
'ʟ' => 'L',
'Ⅼ' => 'L',
'L' => 'L',
'Μ' => 'M',
'М' => 'M',
'Ⅿ' => 'M',
'M' => 'M',
'ɴ' => 'N',
'Ν' => 'N',
'N' => 'N',
'Ο' => 'O',
'О' => 'O',
'O' => 'O',
'Ρ' => 'P',
'Р' => 'P',
'P' => 'P',
'Q' => 'Q',
'ʀ' => 'R',
'R' => 'R',
'Ѕ' => 'S',
'S' => 'S',
'Τ' => 'T',
'Т' => 'T',
'T' => 'T',
'U' => 'U',
'Ѵ' => 'V',
'Ⅴ' => 'V',
'V' => 'V',
'W' => 'W',
'Χ' => 'X',
'Х' => 'X',
'Ⅹ' => 'X',
'X' => 'X',
'ʏ' => 'Y',
'Υ' => 'Y',
'Ү' => 'Y',
'Y' => 'Y',
'Ζ' => 'Z',
'Z' => 'Z',
'_' => '_',
'ɑ' => 'a',
'а' => 'a',
'a' => 'a',
'Ь' => 'b',
'b' => 'b',
'ϲ' => 'c',
'с' => 'c',
'ⅽ' => 'c',
'c' => 'c',
'ԁ' => 'd',
'ⅾ' => 'd',
'd' => 'd',
'е' => 'e',
'e' => 'e',
'f' => 'f',
'ɡ' => 'g',
'g' => 'g',
'һ' => 'h',
'h' => 'h',
'ɩ' => 'i',
'і' => 'i',
'ⅰ' => 'i',
'i' => 'i',
'ј' => 'j',
'j' => 'j',
'k' => 'k',
'ⅼ' => 'l',
'l' => 'l',
'ⅿ' => 'm',
'm' => 'm',
'n' => 'n',
'ο' => 'o',
'о' => 'o',
'o' => 'o',
'р' => 'p',
'p' => 'p',
'q' => 'q',
'r' => 'r',
'ѕ' => 's',
's' => 's',
't' => 't',
'u' => 'u',
'ν' => 'v',
'ѵ' => 'v',
'ⅴ' => 'v',
'v' => 'v',
'ѡ' => 'w',
'w' => 'w',
'х' => 'x',
'ⅹ' => 'x',
'x' => 'x',
'у' => 'y',
'y' => 'y',
'z' => 'z',
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Replace accidental usage of homoglyphs (non ascii characters) in names.',
[new CodeSample("<?php \$nаmе = 'wrong \"a\" character';\n")],
null,
'Renames classes and cannot rename the files. You might have string references to renamed code (`$$name`).',
);
}
public function isRisky(): bool
{
return true;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([\T_VARIABLE, \T_STRING]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
foreach ($tokens as $index => $token) {
if (!$token->isGivenKind([\T_VARIABLE, \T_STRING])) {
continue;
}
$replaced = Preg::replaceCallback('/[^[:ascii:]]/u', static fn (array $matches): string => self::REPLACEMENTS[$matches[0]] ?? $matches[0], $token->getContent(), -1, $count);
if ($count > 0) {
$tokens->offsetSet($index, new Token([$token->getId(), $replaced]));
}
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Operator/IncrementStyleFixer.php | src/Fixer/Operator/IncrementStyleFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\Fixer\AbstractIncrementOperatorFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* style?: 'post'|'pre',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* style: 'post'|'pre',
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Gregor Harlan <gharlan@web.de>
* @author Kuba Werłos <werlos@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class IncrementStyleFixer extends AbstractIncrementOperatorFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @internal
*/
public const STYLE_PRE = 'pre';
/**
* @internal
*/
public const STYLE_POST = 'post';
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Pre- or post-increment and decrement operators should be used if possible.',
[
new CodeSample("<?php\n\$a++;\n\$b--;\n"),
new CodeSample(
"<?php\n++\$a;\n--\$b;\n",
['style' => self::STYLE_POST],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before NoSpacesInsideParenthesisFixer, SpacesInsideParenthesesFixer.
* Must run after StandardizeIncrementFixer.
*/
public function getPriority(): int
{
return 15;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound([\T_INC, \T_DEC]);
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('style', 'Whether to use pre- or post-increment and decrement operators.'))
->setAllowedValues([self::STYLE_PRE, self::STYLE_POST])
->setDefault(self::STYLE_PRE)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$tokensAnalyzer = new TokensAnalyzer($tokens);
for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind([\T_INC, \T_DEC])) {
continue;
}
if (self::STYLE_PRE === $this->configuration['style'] && $tokensAnalyzer->isUnarySuccessorOperator($index)) {
$nextToken = $tokens[$tokens->getNextMeaningfulToken($index)];
if (!$nextToken->equalsAny([';', ')'])) {
continue;
}
$startIndex = $this->findStart($tokens, $index);
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($startIndex)];
if ($prevToken->equalsAny([';', '{', '}', [\T_OPEN_TAG], ')'])) {
$tokens->clearAt($index);
$tokens->insertAt($startIndex, clone $token);
}
} elseif (self::STYLE_POST === $this->configuration['style'] && $tokensAnalyzer->isUnaryPredecessorOperator($index)) {
$prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)];
if (!$prevToken->equalsAny([';', '{', '}', [\T_OPEN_TAG], ')'])) {
continue;
}
$endIndex = $this->findEnd($tokens, $index);
$nextToken = $tokens[$tokens->getNextMeaningfulToken($endIndex)];
if ($nextToken->equalsAny([';', ')'])) {
$tokens->clearAt($index);
$tokens->insertAt($tokens->getNextNonWhitespace($endIndex), clone $token);
}
}
}
}
private function findEnd(Tokens $tokens, int $index): int
{
$nextIndex = $tokens->getNextMeaningfulToken($index);
$nextToken = $tokens[$nextIndex];
while ($nextToken->equalsAny([
'$',
'(',
'[',
[CT::T_DYNAMIC_PROP_BRACE_OPEN],
[CT::T_DYNAMIC_VAR_BRACE_OPEN],
[CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN],
[\T_NS_SEPARATOR],
[\T_STATIC],
[\T_STRING],
[\T_VARIABLE],
])) {
$blockType = Tokens::detectBlockType($nextToken);
if (null !== $blockType) {
$nextIndex = $tokens->findBlockEnd($blockType['type'], $nextIndex);
}
$index = $nextIndex;
$nextIndex = $tokens->getNextMeaningfulToken($nextIndex);
$nextToken = $tokens[$nextIndex];
}
if ($nextToken->isObjectOperator()) {
return $this->findEnd($tokens, $nextIndex);
}
if ($nextToken->isGivenKind(\T_PAAMAYIM_NEKUDOTAYIM)) {
return $this->findEnd($tokens, $tokens->getNextMeaningfulToken($nextIndex));
}
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/Operator/NewWithParenthesesFixer.php | src/Fixer/Operator/NewWithParenthesesFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Future;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* anonymous_class?: bool,
* named_class?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* anonymous_class: bool,
* named_class: 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 NewWithParenthesesFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private const NEXT_TOKEN_KINDS = [
'?',
';',
',',
'(',
')',
'[',
']',
':',
'<',
'>',
'+',
'-',
'*',
'/',
'%',
'&',
'^',
'|',
[\T_CLASS],
[\T_IS_SMALLER_OR_EQUAL],
[\T_IS_GREATER_OR_EQUAL],
[\T_IS_EQUAL],
[\T_IS_NOT_EQUAL],
[\T_IS_IDENTICAL],
[\T_IS_NOT_IDENTICAL],
[\T_CLOSE_TAG],
[\T_LOGICAL_AND],
[\T_LOGICAL_OR],
[\T_LOGICAL_XOR],
[\T_BOOLEAN_AND],
[\T_BOOLEAN_OR],
[\T_SL],
[\T_SR],
[\T_INSTANCEOF],
[\T_AS],
[\T_DOUBLE_ARROW],
[\T_POW],
[\T_SPACESHIP],
[CT::T_ARRAY_SQUARE_BRACE_OPEN],
[CT::T_ARRAY_SQUARE_BRACE_CLOSE],
[CT::T_BRACE_CLASS_INSTANTIATION_OPEN],
[CT::T_BRACE_CLASS_INSTANTIATION_CLOSE],
[FCT::T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG],
[FCT::T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG],
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'All instances created with `new` keyword must (not) be followed by parentheses.',
[
new CodeSample("<?php\n\n\$x = new X;\n\$y = new class {};\n"),
new CodeSample(
"<?php\n\n\$y = new class() {};\n",
['anonymous_class' => false],
),
new CodeSample(
"<?php\n\n\$x = new X();\n",
['named_class' => false],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before ClassDefinitionFixer, NewExpressionParenthesesFixer.
*/
public function getPriority(): int
{
return 38;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_NEW);
}
/**
* @protected
*
* @TODO 4.0 move visibility from annotation to code when `NewWithBracesFixer` is removed
*/
public function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('named_class', 'Whether named classes should be followed by parentheses.'))
->setAllowedTypes(['bool'])
->setDefault(true)
->getOption(),
(new FixerOptionBuilder('anonymous_class', 'Whether anonymous classes should be followed by parentheses.'))
->setAllowedTypes(['bool'])
->setDefault(Future::getV4OrV3(false, true))
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 3; $index > 0; --$index) {
if (!$tokens[$index]->isGivenKind(\T_NEW)) {
continue;
}
$nextIndex = $tokens->getNextTokenOfKind($index, self::NEXT_TOKEN_KINDS);
// new anonymous class definition
if ($tokens[$nextIndex]->isGivenKind(\T_CLASS)) {
$nextIndex = $tokens->getNextMeaningfulToken($nextIndex);
if (true === $this->configuration['anonymous_class']) {
$this->ensureParenthesesAt($tokens, $nextIndex);
} else {
$this->ensureNoParenthesesAt($tokens, $nextIndex);
}
continue;
}
// entrance into array index syntax - need to look for exit
while ($tokens[$nextIndex]->equals('[') || $tokens[$nextIndex]->isGivenKind(CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN)) {
$nextIndex = $tokens->findBlockEnd(Tokens::detectBlockType($tokens[$nextIndex])['type'], $nextIndex);
$nextIndex = $tokens->getNextMeaningfulToken($nextIndex);
}
if (true === $this->configuration['named_class']) {
$this->ensureParenthesesAt($tokens, $nextIndex);
} else {
$this->ensureNoParenthesesAt($tokens, $nextIndex);
}
}
}
private function ensureParenthesesAt(Tokens $tokens, int $index): void
{
$token = $tokens[$index];
if (!$token->equals('(') && !$token->isObjectOperator()) {
$tokens->insertAt(
$tokens->getPrevMeaningfulToken($index) + 1,
[new Token('('), new Token(')')],
);
}
}
private function ensureNoParenthesesAt(Tokens $tokens, int $index): void
{
if (!$tokens[$index]->equals('(')) {
return;
}
$closingIndex = $tokens->getNextMeaningfulToken($index);
// constructor has arguments - parentheses can not be removed
if (!$tokens[$closingIndex]->equals(')')) {
return;
}
// Check if there's an object operator after the closing parenthesis
// Preserve parentheses in expressions like "new A()->method()" as per RFC
$afterClosingIndex = $tokens->getNextMeaningfulToken($closingIndex);
if ($tokens[$afterClosingIndex]->isObjectOperator()) {
return;
}
$tokens->clearTokenAndMergeSurroundingWhitespace($closingIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($index);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Operator/AssignNullCoalescingToCoalesceEqualFixer.php | src/Fixer/Operator/AssignNullCoalescingToCoalesceEqualFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\Fixer\AbstractShortOperatorFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class AssignNullCoalescingToCoalesceEqualFixer extends AbstractShortOperatorFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Use the null coalescing assignment operator `??=` where possible.',
[
new CodeSample(
"<?php\n\$foo = \$foo ?? 1;\n",
),
],
);
}
/**
* {@inheritdoc}
*
* Must run before BinaryOperatorSpacesFixer, NoWhitespaceInBlankLineFixer.
* Must run after TernaryToNullCoalescingFixer.
*/
public function getPriority(): int
{
return -1;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound(\T_COALESCE);
}
protected function isOperatorTokenCandidate(Tokens $tokens, int $index): bool
{
if (!$tokens[$index]->isGivenKind(\T_COALESCE)) {
return false;
}
// make sure after '??' does not contain '? :'
$nextIndex = $tokens->getNextTokenOfKind($index, ['?', ';', [\T_CLOSE_TAG]]);
return !$tokens[$nextIndex]->equals('?');
}
protected function getReplacementToken(Token $token): Token
{
return new Token([\T_COALESCE_EQUAL, '??=']);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Operator/ObjectOperatorWithoutWhitespaceFixer.php | src/Fixer/Operator/ObjectOperatorWithoutWhitespaceFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Fabien Potencier <fabien@symfony.com>
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class ObjectOperatorWithoutWhitespaceFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There should not be space before or after object operators `->` and `?->`.',
[new CodeSample("<?php \$a -> b;\n")],
);
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isAnyTokenKindsFound(Token::getObjectOperatorKinds());
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
// [Structure] there should not be space before or after "->" or "?->"
foreach ($tokens as $index => $token) {
if (!$token->isObjectOperator()) {
continue;
}
// clear whitespace before ->
if ($tokens[$index - 1]->isWhitespace(" \t") && !$tokens[$index - 2]->isComment()) {
$tokens->clearAt($index - 1);
}
// clear whitespace after ->
if ($tokens[$index + 1]->isWhitespace(" \t") && !$tokens[$index + 2]->isComment()) {
$tokens->clearAt($index + 1);
}
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Operator/NotOperatorWithSuccessorSpaceFixer.php | src/Fixer/Operator/NotOperatorWithSuccessorSpaceFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @author Javier Spagnoletti <phansys@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NotOperatorWithSuccessorSpaceFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Logical NOT operators (`!`) should have one trailing whitespace.',
[
new CodeSample(
<<<'PHP'
<?php
if (!$bar) {
echo "Help!";
}
PHP,
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after ModernizeStrposFixer, UnaryOperatorSpacesFixer.
*/
public function getPriority(): int
{
return -10;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound('!');
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
$token = $tokens[$index];
if ($token->equals('!')) {
$tokens->ensureWhitespaceAtIndex($index + 1, 0, ' ');
}
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Operator/TernaryToElvisOperatorFixer.php | src/Fixer/Operator/TernaryToElvisOperatorFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\RangeAnalyzer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-import-type _PhpTokenPrototypePartial from Token
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class TernaryToElvisOperatorFixer extends AbstractFixer
{
/**
* Lower precedence and other valid preceding tokens.
*
* Ordered by most common types first.
*
* @var non-empty-list<_PhpTokenPrototypePartial>
*/
private const VALID_BEFORE_ENDTYPES = [
'=',
[\T_OPEN_TAG],
[\T_OPEN_TAG_WITH_ECHO],
'(',
',',
';',
'[',
'{',
'}',
[CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN],
[\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], // ^=
];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Use the Elvis operator `?:` where possible.',
[
new CodeSample(
"<?php\n\$foo = \$foo ? \$foo : 1;\n",
),
new CodeSample(
"<?php \$foo = \$bar[a()] ? \$bar[a()] : 1; # \"risky\" sample, \"a()\" only gets called once after fixing\n",
),
],
null,
'Risky when relying on functions called on both sides of the `?` operator.',
);
}
/**
* {@inheritdoc}
*
* Must run before NoTrailingWhitespaceFixer, TernaryOperatorSpacesFixer.
*/
public function getPriority(): int
{
return 2;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound('?');
}
public function isRisky(): bool
{
return true;
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = \count($tokens) - 5; $index > 1; --$index) {
if (!$tokens[$index]->equals('?')) {
continue;
}
$nextIndex = $tokens->getNextMeaningfulToken($index);
if ($tokens[$nextIndex]->equals(':')) {
continue; // Elvis is alive!
}
// get and check what is before the `?` operator
$beforeOperator = $this->getBeforeOperator($tokens, $index);
if (null === $beforeOperator) {
continue; // contains something we cannot fix because of priorities
}
// get what is after the `?` token
$afterOperator = $this->getAfterOperator($tokens, $index);
// if before and after the `?` operator are the same (in meaningful matter), clear after
if (RangeAnalyzer::rangeEqualsRange($tokens, $beforeOperator, $afterOperator)) {
$this->clearMeaningfulFromRange($tokens, $afterOperator);
}
}
}
/**
* @return ?array{start: int, end: int} null if contains ++/-- operator
*/
private function getBeforeOperator(Tokens $tokens, int $index): ?array
{
$blockEdgeDefinitions = Tokens::getBlockEdgeDefinitions();
$index = $tokens->getPrevMeaningfulToken($index);
$before = ['end' => $index];
while (!$tokens[$index]->equalsAny(self::VALID_BEFORE_ENDTYPES)) {
if ($tokens[$index]->isGivenKind([\T_INC, \T_DEC])) {
return null;
}
$detectedBlockType = Tokens::detectBlockType($tokens[$index]);
if (null === $detectedBlockType || $detectedBlockType['isStart']) {
$before['start'] = $index;
$index = $tokens->getPrevMeaningfulToken($index);
continue;
}
/** @phpstan-ignore-next-line offsetAccess.notFound (we just detected block type, we know it's definition exists under given PHP runtime) */
$blockType = $blockEdgeDefinitions[$detectedBlockType['type']];
$openCount = 1;
do {
$index = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$index]->isGivenKind([\T_INC, \T_DEC])) {
return null;
}
if ($tokens[$index]->equals($blockType['start'])) {
++$openCount;
continue;
}
if ($tokens[$index]->equals($blockType['end'])) {
--$openCount;
}
} while (1 >= $openCount);
$before['start'] = $index;
$index = $tokens->getPrevMeaningfulToken($index);
}
if (!isset($before['start'])) {
return null;
}
return $before;
}
/**
* @return array{start: int, end: int}
*/
private function getAfterOperator(Tokens $tokens, int $index): array
{
$index = $tokens->getNextMeaningfulToken($index);
$after = ['start' => $index];
do {
$blockType = Tokens::detectBlockType($tokens[$index]);
if (null !== $blockType) {
$index = $tokens->findBlockEnd($blockType['type'], $index);
}
$after['end'] = $index;
$index = $tokens->getNextMeaningfulToken($index);
} while (!$tokens[$index]->equals(':'));
return $after;
}
/**
* @param array{start: int, end: int} $range
*/
private function clearMeaningfulFromRange(Tokens $tokens, array $range): void
{
// $range['end'] must be meaningful!
for ($i = $range['end']; $i >= $range['start']; $i = $tokens->getPrevMeaningfulToken($i)) {
$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/Operator/ConcatSpaceFixer.php | src/Fixer/Operator/ConcatSpaceFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* spacing?: 'none'|'one',
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* spacing: '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 ConcatSpaceFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Concatenation should be spaced according to configuration.',
[
new CodeSample(
"<?php\n\$foo = 'bar' . 3 . 'baz'.'qux';\n",
),
new CodeSample(
"<?php\n\$foo = 'bar' . 3 . 'baz'.'qux';\n",
['spacing' => 'none'],
),
new CodeSample(
"<?php\n\$foo = 'bar' . 3 . 'baz'.'qux';\n",
['spacing' => 'one'],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after NoUnneededControlParenthesesFixer, SingleLineThrowFixer.
*/
public function getPriority(): int
{
return 0;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound('.');
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
if ($tokens[$index]->equals('.')) {
if ('one' === $this->configuration['spacing']) {
$this->fixConcatenationToSingleSpace($tokens, $index);
} else {
$this->fixConcatenationToNoSpace($tokens, $index);
}
}
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('spacing', 'Spacing to apply around concatenation operator.'))
->setAllowedValues(['one', 'none'])
->setDefault('none')
->getOption(),
]);
}
/**
* @param int $index index of concatenation '.' token
*/
private function fixConcatenationToNoSpace(Tokens $tokens, int $index): void
{
$prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)];
if (!$prevNonWhitespaceToken->isGivenKind([\T_LNUMBER, \T_COMMENT, \T_DOC_COMMENT]) || str_starts_with($prevNonWhitespaceToken->getContent(), '/*')) {
$tokens->removeLeadingWhitespace($index, " \t");
}
if (!$tokens[$tokens->getNextNonWhitespace($index)]->isGivenKind([\T_LNUMBER, \T_COMMENT, \T_DOC_COMMENT])) {
$tokens->removeTrailingWhitespace($index, " \t");
}
}
/**
* @param int $index index of concatenation '.' token
*/
private function fixConcatenationToSingleSpace(Tokens $tokens, int $index): void
{
$this->fixWhiteSpaceAroundConcatToken($tokens, $index, 1);
$this->fixWhiteSpaceAroundConcatToken($tokens, $index, -1);
}
/**
* @param int $index index of concatenation '.' token
* @param int $offset 1 or -1
*/
private function fixWhiteSpaceAroundConcatToken(Tokens $tokens, int $index, int $offset): void
{
if (-1 !== $offset && 1 !== $offset) {
throw new \InvalidArgumentException(\sprintf(
'Expected `-1|1` for "$offset", got "%s"',
$offset,
));
}
$offsetIndex = $index + $offset;
if (!$tokens[$offsetIndex]->isWhitespace()) {
$tokens->insertAt($index + (1 === $offset ? 1 : 0), new Token([\T_WHITESPACE, ' ']));
return;
}
if (str_contains($tokens[$offsetIndex]->getContent(), "\n")) {
return;
}
if ($tokens[$index + $offset * 2]->isComment()) {
return;
}
$tokens[$offsetIndex] = new Token([\T_WHITESPACE, ' ']);
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Operator/NewExpressionParenthesesFixer.php | src/Fixer/Operator/NewExpressionParenthesesFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\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{
* use_parentheses?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* use_parentheses: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Valentin Udaltsov <udaltsov.valentin@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NewExpressionParenthesesFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'All `new` expressions with a further call must (not) be wrapped in parentheses.',
[
new VersionSpecificCodeSample(
"<?php\n\n(new Foo())->bar();\n",
new VersionSpecification(8_04_00),
),
new VersionSpecificCodeSample(
"<?php\n\n(new class {})->bar();\n",
new VersionSpecification(8_04_00),
),
new VersionSpecificCodeSample(
"<?php\n\nnew Foo()->bar();\n",
new VersionSpecification(8_04_00),
['use_parentheses' => true],
),
new VersionSpecificCodeSample(
"<?php\n\nnew class {}->bar();\n",
new VersionSpecification(8_04_00),
['use_parentheses' => true],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after NewWithParenthesesFixer, NoUnneededControlParenthesesFixer.
*/
public function getPriority(): int
{
return 29;
}
public function isCandidate(Tokens $tokens): bool
{
return \PHP_VERSION_ID >= 8_04_00 && $tokens->isTokenKindFound(\T_NEW);
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('use_parentheses', 'Whether `new` expressions with a further call should be wrapped in parentheses or not.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$useParentheses = $this->configuration['use_parentheses'];
for ($index = $tokens->count() - 3; $index > 0; --$index) {
if (!$tokens[$index]->isGivenKind(\T_NEW)) {
continue;
}
$classStartIndex = $tokens->getNextMeaningfulToken($index);
if (null === $classStartIndex) {
return;
}
// anonymous class
if ($tokens[$classStartIndex]->isGivenKind(\T_CLASS)) {
$nextIndex = $tokens->getNextMeaningfulToken($classStartIndex);
if ($tokens[$nextIndex]->equals('(')) {
$nextIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex);
} else {
$nextIndex = $classStartIndex;
}
$bodyStartIndex = $tokens->getNextTokenOfKind($nextIndex, ['{']);
$bodyEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $bodyStartIndex);
if ($useParentheses) {
$this->ensureWrappedInParentheses($tokens, $index, $bodyEndIndex);
} else {
$this->ensureNotWrappedInParentheses($tokens, $index, $bodyEndIndex);
}
continue;
}
// named class
$classEndIndex = $this->findClassEndIndex($tokens, $classStartIndex);
if (null === $classEndIndex) {
continue;
}
$nextIndex = $tokens->getNextMeaningfulToken($classEndIndex);
if (!$tokens[$nextIndex]->equals('(')) {
// If arguments' parentheses are absent then either this new expression is not further called
// and does not need parentheses, or we cannot omit its parentheses due to the grammar rules.
continue;
}
$argsEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex);
if ($useParentheses) {
$this->ensureWrappedInParentheses($tokens, $index, $argsEndIndex);
} else {
$this->ensureNotWrappedInParentheses($tokens, $index, $argsEndIndex);
}
}
}
private function ensureWrappedInParentheses(Tokens $tokens, int $exprStartIndex, int $exprEndIndex): void
{
$prevIndex = $tokens->getPrevMeaningfulToken($exprStartIndex);
$nextIndex = $tokens->getNextMeaningfulToken($exprEndIndex);
if ($tokens[$prevIndex]->isGivenKind(CT::T_BRACE_CLASS_INSTANTIATION_OPEN)
&& $tokens[$nextIndex]->isGivenKind(CT::T_BRACE_CLASS_INSTANTIATION_CLOSE)
) {
return;
}
if (!$tokens[$nextIndex]->isObjectOperator() && !$tokens[$nextIndex]->isGivenKind(\T_PAAMAYIM_NEKUDOTAYIM)) {
return;
}
$tokens->insertAt($exprStartIndex, [new Token([CT::T_BRACE_CLASS_INSTANTIATION_OPEN, '('])]);
$tokens->insertAt($exprEndIndex + 2, [new Token([CT::T_BRACE_CLASS_INSTANTIATION_CLOSE, ')'])]);
}
private function ensureNotWrappedInParentheses(Tokens $tokens, int $exprStartIndex, int $exprEndIndex): void
{
$prevIndex = $tokens->getPrevMeaningfulToken($exprStartIndex);
$nextIndex = $tokens->getNextMeaningfulToken($exprEndIndex);
if (!$tokens[$prevIndex]->isGivenKind(CT::T_BRACE_CLASS_INSTANTIATION_OPEN)
|| !$tokens[$nextIndex]->isGivenKind(CT::T_BRACE_CLASS_INSTANTIATION_CLOSE)
) {
return;
}
$operatorIndex = $tokens->getNextMeaningfulToken($nextIndex);
if (!$tokens[$operatorIndex]->isObjectOperator() && !$tokens[$operatorIndex]->isGivenKind(\T_PAAMAYIM_NEKUDOTAYIM)) {
return;
}
$tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($nextIndex);
}
private function findClassEndIndex(Tokens $tokens, int $index): ?int
{
// (expression) class name
if ($tokens[$index]->equals('(')) {
return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
}
// regular class name or $variable class name
$nextTokens = [
[\T_STRING],
[\T_NS_SEPARATOR],
[CT::T_NAMESPACE_OPERATOR],
[\T_VARIABLE],
'$',
[CT::T_DYNAMIC_VAR_BRACE_OPEN],
'[',
[\T_OBJECT_OPERATOR],
[\T_NULLSAFE_OBJECT_OPERATOR],
[\T_PAAMAYIM_NEKUDOTAYIM],
];
if (!$tokens[$index]->equalsAny($nextTokens)) {
return null;
}
while ($tokens[$index]->equalsAny($nextTokens)) {
$blockType = Tokens::detectBlockType($tokens[$index]);
if (null !== $blockType) {
$index = $tokens->findBlockEnd($blockType['type'], $index);
}
$index = $tokens->getNextMeaningfulToken($index);
}
return $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/Operator/NewWithBracesFixer.php | src/Fixer/Operator/NewWithBracesFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractProxyFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
/**
* @deprecated
*
* @phpstan-type _AutogeneratedInputConfiguration array{
* anonymous_class?: bool,
* named_class?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* anonymous_class: bool,
* named_class: 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 NewWithBracesFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, DeprecatedFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private NewWithParenthesesFixer $newWithParenthesesFixer;
public function __construct()
{
$this->newWithParenthesesFixer = new NewWithParenthesesFixer();
parent::__construct();
}
public function getDefinition(): FixerDefinitionInterface
{
$fixerDefinition = $this->newWithParenthesesFixer->getDefinition();
return new FixerDefinition(
'All instances created with `new` keyword must (not) be followed by braces.',
$fixerDefinition->getCodeSamples(),
$fixerDefinition->getDescription(),
$fixerDefinition->getRiskyDescription(),
);
}
/**
* {@inheritdoc}
*
* Must run before ClassDefinitionFixer.
*/
public function getPriority(): int
{
return $this->newWithParenthesesFixer->getPriority();
}
public function getSuccessorsNames(): array
{
return [
$this->newWithParenthesesFixer->getName(),
];
}
/**
* @param _AutogeneratedInputConfiguration $configuration
*/
protected function configurePreNormalisation(array $configuration): void
{
$this->newWithParenthesesFixer->configure($configuration);
}
protected function createProxyFixers(): array
{
return [
$this->newWithParenthesesFixer,
];
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return $this->newWithParenthesesFixer->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/Operator/BinaryOperatorSpacesFixer.php | src/Fixer/Operator/BinaryOperatorSpacesFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;
use PhpCsFixer\Utils;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
/**
* @phpstan-type _AutogeneratedInputConfiguration array{
* default?: 'align'|'align_by_scope'|'align_single_space'|'align_single_space_by_scope'|'align_single_space_minimal'|'align_single_space_minimal_by_scope'|'at_least_single_space'|'no_space'|'single_space'|null,
* operators?: array<string, ?string>,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* default: 'align'|'align_by_scope'|'align_single_space'|'align_single_space_by_scope'|'align_single_space_minimal'|'align_single_space_minimal_by_scope'|'at_least_single_space'|'no_space'|'single_space'|null,
* operators: array<string, ?string>,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class BinaryOperatorSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
/**
* @internal
*/
public const SINGLE_SPACE = 'single_space';
/**
* @internal
*/
public const AT_LEAST_SINGLE_SPACE = 'at_least_single_space';
/**
* @internal
*/
public const NO_SPACE = 'no_space';
/**
* @internal
*/
public const ALIGN = 'align';
/**
* @internal
*/
public const ALIGN_BY_SCOPE = 'align_by_scope';
/**
* @internal
*/
public const ALIGN_SINGLE_SPACE = 'align_single_space';
/**
* @internal
*/
public const ALIGN_SINGLE_SPACE_BY_SCOPE = 'align_single_space_by_scope';
/**
* @internal
*/
public const ALIGN_SINGLE_SPACE_MINIMAL = 'align_single_space_minimal';
/**
* @internal
*/
public const ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE = 'align_single_space_minimal_by_scope';
/**
* Placeholder used as anchor for right alignment.
*
* @internal
*/
public const ALIGN_PLACEHOLDER = "\x2 ALIGNABLE%d \x3";
/**
* @var non-empty-list<string>
*/
private const SUPPORTED_OPERATORS = [
'=',
'*',
'/',
'%',
'<',
'>',
'|',
'^',
'+',
'-',
'&',
'&=',
'&&',
'||',
'.=',
'/=',
'=>',
'==',
'>=',
'===',
'!=',
'<>',
'!==',
'<=',
'and',
'or',
'xor',
'-=',
'%=',
'*=',
'|=',
'+=',
'<<',
'<<=',
'>>',
'>>=',
'^=',
'**',
'**=',
'<=>',
'??',
'??=',
];
/**
* @var non-empty-list<null|string>
*/
private const ALLOWED_VALUES = [
self::ALIGN,
self::ALIGN_BY_SCOPE,
self::ALIGN_SINGLE_SPACE,
self::ALIGN_SINGLE_SPACE_MINIMAL,
self::ALIGN_SINGLE_SPACE_BY_SCOPE,
self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE,
self::SINGLE_SPACE,
self::NO_SPACE,
self::AT_LEAST_SINGLE_SPACE,
null,
];
/**
* Keep track of the deepest level ever achieved while
* parsing the code. Used later to replace alignment
* placeholders with spaces.
*/
private int $deepestLevel;
/**
* Level counter of the current nest level.
* So one level alignments are not mixed with
* other level ones.
*/
private int $currentLevel;
private TokensAnalyzer $tokensAnalyzer;
/**
* @var array<string, string>
*/
private array $alignOperatorTokens = [];
/**
* @var array<string, string>
*/
private array $operators = [];
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'Binary operators should be surrounded by space as configured.',
[
new CodeSample(
<<<'PHP'
<?php
$a= 1 + $b^ $d !== $e or $f;
PHP,
),
new CodeSample(
<<<'PHP'
<?php
$aa= 1;
$b=2;
$c = $d xor $e;
$f -= 1;
PHP,
['operators' => ['=' => self::ALIGN, 'xor' => null]],
),
new CodeSample(
<<<'PHP'
<?php
$a = $b +=$c;
$d = $ee+=$f;
$g = $b +=$c;
$h = $ee+=$f;
PHP,
['operators' => ['+=' => self::ALIGN_SINGLE_SPACE]],
),
new CodeSample(
<<<'PHP'
<?php
$a = $b===$c;
$d = $f === $g;
$h = $i=== $j;
PHP,
['operators' => ['===' => self::ALIGN_SINGLE_SPACE_MINIMAL]],
),
new CodeSample(
<<<'PHP'
<?php
$foo = \json_encode($bar, JSON_PRESERVE_ZERO_FRACTION | JSON_PRETTY_PRINT);
PHP,
['operators' => ['|' => self::NO_SPACE]],
),
new CodeSample(
<<<'PHP'
<?php
$array = [
"foo" => 1,
"baaaaaaaaaaar" => 11,
];
PHP,
['operators' => ['=>' => self::SINGLE_SPACE]],
),
new CodeSample(
<<<'PHP'
<?php
$array = [
"foo" => 12,
"baaaaaaaaaaar" => 13,
"baz" => 1,
];
PHP,
['operators' => ['=>' => self::ALIGN]],
),
new CodeSample(
<<<'PHP'
<?php
$array = [
"foo" => 12,
"baaaaaaaaaaar" => 13,
"baz" => 1,
];
PHP,
['operators' => ['=>' => self::ALIGN_BY_SCOPE]],
),
new CodeSample(
<<<'PHP'
<?php
$array = [
"foo" => 12,
"baaaaaaaaaaar" => 13,
"baz" => 1,
];
PHP,
['operators' => ['=>' => self::ALIGN_SINGLE_SPACE]],
),
new CodeSample(
<<<'PHP'
<?php
$array = [
"foo" => 12,
"baaaaaaaaaaar" => 13,
"baz" => 1,
];
PHP,
['operators' => ['=>' => self::ALIGN_SINGLE_SPACE_BY_SCOPE]],
),
new CodeSample(
<<<'PHP'
<?php
$array = [
"foo" => 12,
"baaaaaaaaaaar" => 13,
"baz" => 1,
];
PHP,
['operators' => ['=>' => self::ALIGN_SINGLE_SPACE_MINIMAL]],
),
new CodeSample(
<<<'PHP'
<?php
$array = [
"foo" => 12,
"baaaaaaaaaaar" => 13,
"baz" => 1,
];
PHP,
['operators' => ['=>' => self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE]],
),
],
);
}
/**
* {@inheritdoc}
*
* Must run after ArrayIndentationFixer, ArraySyntaxFixer, AssignNullCoalescingToCoalesceEqualFixer, ListSyntaxFixer, LongToShorthandOperatorFixer, ModernizeStrposFixer, NoMultilineWhitespaceAroundDoubleArrowFixer, NoUnsetCastFixer, PowToExponentiationFixer, StandardizeNotEqualsFixer, StrictComparisonFixer.
*/
public function getPriority(): int
{
return -32;
}
public function isCandidate(Tokens $tokens): bool
{
return true;
}
protected function configurePostNormalisation(): void
{
$this->operators = $this->resolveOperatorsFromConfig();
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$this->tokensAnalyzer = new TokensAnalyzer($tokens);
// last and first tokens cannot be an operator
for ($index = $tokens->count() - 2; $index > 0; --$index) {
if (!$this->tokensAnalyzer->isBinaryOperator($index)) {
continue;
}
if ('=' === $tokens[$index]->getContent()) {
$isDeclare = $this->isEqualPartOfDeclareStatement($tokens, $index);
if (false === $isDeclare) {
$this->fixWhiteSpaceAroundOperator($tokens, $index);
} else {
$index = $isDeclare; // skip `declare(foo ==bar)`, see `declare_equal_normalize`
}
} else {
$this->fixWhiteSpaceAroundOperator($tokens, $index);
}
// previous of binary operator is now never an operator / previous of declare statement cannot be an operator
--$index;
}
if (\count($this->alignOperatorTokens) > 0) {
$this->fixAlignment($tokens, $this->alignOperatorTokens);
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('default', 'Default fix strategy.'))
->setDefault(self::SINGLE_SPACE)
->setAllowedValues(self::ALLOWED_VALUES)
->getOption(),
(new FixerOptionBuilder('operators', 'Dictionary of `binary operator` => `fix strategy` values that differ from the default strategy. Supported are: '.Utils::naturalLanguageJoinWithBackticks(self::SUPPORTED_OPERATORS).'.'))
->setAllowedTypes(['array<string, ?string>'])
->setAllowedValues([static function (array $option): bool {
foreach ($option as $operator => $value) {
if (!\in_array($operator, self::SUPPORTED_OPERATORS, true)) {
throw new InvalidOptionsException(
\sprintf(
'Unexpected "operators" key, expected any of %s, got "%s".',
Utils::naturalLanguageJoin(self::SUPPORTED_OPERATORS),
\gettype($operator).'#'.$operator,
),
);
}
if (!\in_array($value, self::ALLOWED_VALUES, true)) {
throw new InvalidOptionsException(
\sprintf(
'Unexpected value for operator "%s", expected any of %s, got "%s".',
$operator,
Utils::naturalLanguageJoin(array_map(
static fn ($value): string => Utils::toString($value),
self::ALLOWED_VALUES,
)),
\is_object($value) ? \get_class($value) : (null === $value ? 'null' : \gettype($value).'#'.$value),
),
);
}
}
return true;
}])
->setDefault([])
->getOption(),
]);
}
private function fixWhiteSpaceAroundOperator(Tokens $tokens, int $index): void
{
$tokenContent = strtolower($tokens[$index]->getContent());
if (!\array_key_exists($tokenContent, $this->operators)) {
return; // not configured to be changed
}
if (self::SINGLE_SPACE === $this->operators[$tokenContent]) {
$this->fixWhiteSpaceAroundOperatorToSingleSpace($tokens, $index);
return;
}
if (self::AT_LEAST_SINGLE_SPACE === $this->operators[$tokenContent]) {
$this->fixWhiteSpaceAroundOperatorToAtLeastSingleSpace($tokens, $index);
return;
}
if (self::NO_SPACE === $this->operators[$tokenContent]) {
$this->fixWhiteSpaceAroundOperatorToNoSpace($tokens, $index);
return;
}
// schedule for alignment
$this->alignOperatorTokens[$tokenContent] = $this->operators[$tokenContent];
if (
self::ALIGN === $this->operators[$tokenContent]
|| self::ALIGN_BY_SCOPE === $this->operators[$tokenContent]
) {
return;
}
// fix white space after operator
if ($tokens[$index + 1]->isWhitespace()) {
if (
self::ALIGN_SINGLE_SPACE_MINIMAL === $this->operators[$tokenContent]
|| self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE === $this->operators[$tokenContent]
) {
$tokens[$index + 1] = new Token([\T_WHITESPACE, ' ']);
}
return;
}
$tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' ']));
}
private function fixWhiteSpaceAroundOperatorToSingleSpace(Tokens $tokens, int $index): void
{
// fix white space after operator
if ($tokens[$index + 1]->isWhitespace()) {
$content = $tokens[$index + 1]->getContent();
if (' ' !== $content && !str_contains($content, "\n") && !$tokens[$tokens->getNextNonWhitespace($index + 1)]->isComment()) {
$tokens[$index + 1] = new Token([\T_WHITESPACE, ' ']);
}
} else {
$tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' ']));
}
// fix white space before operator
if ($tokens[$index - 1]->isWhitespace()) {
$content = $tokens[$index - 1]->getContent();
if (' ' !== $content && !str_contains($content, "\n") && !$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) {
$tokens[$index - 1] = new Token([\T_WHITESPACE, ' ']);
}
} else {
$tokens->insertAt($index, new Token([\T_WHITESPACE, ' ']));
}
}
private function fixWhiteSpaceAroundOperatorToAtLeastSingleSpace(Tokens $tokens, int $index): void
{
// fix white space after operator
if (!$tokens[$index + 1]->isWhitespace()) {
$tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' ']));
}
// fix white space before operator
if (!$tokens[$index - 1]->isWhitespace()) {
$tokens->insertAt($index, new Token([\T_WHITESPACE, ' ']));
}
}
private function fixWhiteSpaceAroundOperatorToNoSpace(Tokens $tokens, int $index): void
{
// fix white space after operator
if ($tokens[$index + 1]->isWhitespace()) {
$content = $tokens[$index + 1]->getContent();
if (!str_contains($content, "\n") && !$tokens[$tokens->getNextNonWhitespace($index + 1)]->isComment()) {
$tokens->clearAt($index + 1);
}
}
// fix white space before operator
if ($tokens[$index - 1]->isWhitespace()) {
$content = $tokens[$index - 1]->getContent();
if (!str_contains($content, "\n") && !$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) {
$tokens->clearAt($index - 1);
}
}
}
/**
* @return false|int index of T_DECLARE where the `=` belongs to or `false`
*/
private function isEqualPartOfDeclareStatement(Tokens $tokens, int $index)
{
$prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevMeaningfulIndex]->isGivenKind(\T_STRING)) {
$prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulIndex);
if ($tokens[$prevMeaningfulIndex]->equals('(')) {
$prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulIndex);
if ($tokens[$prevMeaningfulIndex]->isGivenKind(\T_DECLARE)) {
return $prevMeaningfulIndex;
}
}
}
return false;
}
/**
* @return array<string, string>
*/
private function resolveOperatorsFromConfig(): array
{
$operators = [];
if (null !== $this->configuration['default']) {
foreach (self::SUPPORTED_OPERATORS as $operator) {
$operators[$operator] = $this->configuration['default'];
}
}
foreach ($this->configuration['operators'] as $operator => $value) {
if (null === $value) {
unset($operators[$operator]);
} else {
$operators[$operator] = $value;
}
}
return $operators;
}
// Alignment logic related methods
/**
* @param array<string, string> $toAlign
*/
private function fixAlignment(Tokens $tokens, array $toAlign): void
{
$this->deepestLevel = 0;
$this->currentLevel = 0;
foreach ($toAlign as $tokenContent => $alignStrategy) {
// This fixer works partially on Tokens and partially on string representation of code.
// During the process of fixing internal state of single Token may be affected by injecting ALIGN_PLACEHOLDER to its content.
// The placeholder will be resolved by `replacePlaceholders` method by removing placeholder or changing it into spaces.
// That way of fixing the code causes disturbances in marking Token as changed - if code is perfectly valid then placeholder
// still be injected and removed, which will cause the `changed` flag to be set.
// To handle that unwanted behaviour we work on clone of Tokens collection and then override original collection with fixed collection.
$tokensClone = clone $tokens;
if ('=>' === $tokenContent) {
$this->injectAlignmentPlaceholdersForArrow($tokensClone, 0, \count($tokens));
} else {
$this->injectAlignmentPlaceholdersDefault($tokensClone, 0, \count($tokens), $tokenContent);
}
// for all tokens that should be aligned but do not have anything to align with, fix spacing if needed
if (
self::ALIGN_SINGLE_SPACE === $alignStrategy
|| self::ALIGN_SINGLE_SPACE_MINIMAL === $alignStrategy
|| self::ALIGN_SINGLE_SPACE_BY_SCOPE === $alignStrategy
|| self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE === $alignStrategy
) {
if ('=>' === $tokenContent) {
for ($index = $tokens->count() - 2; $index > 0; --$index) {
if ($tokens[$index]->isGivenKind(\T_DOUBLE_ARROW)) { // always binary operator, never part of declare statement
$this->fixWhiteSpaceBeforeOperator($tokensClone, $index, $alignStrategy);
}
}
} elseif ('=' === $tokenContent) {
for ($index = $tokens->count() - 2; $index > 0; --$index) {
if ('=' === $tokens[$index]->getContent() && false === $this->isEqualPartOfDeclareStatement($tokens, $index) && $this->tokensAnalyzer->isBinaryOperator($index)) {
$this->fixWhiteSpaceBeforeOperator($tokensClone, $index, $alignStrategy);
}
}
} else {
for ($index = $tokens->count() - 2; $index > 0; --$index) {
$content = $tokens[$index]->getContent();
if (strtolower($content) === $tokenContent && $this->tokensAnalyzer->isBinaryOperator($index)) { // never part of declare statement
$this->fixWhiteSpaceBeforeOperator($tokensClone, $index, $alignStrategy);
}
}
}
}
$tokens->setCode($this->replacePlaceholders($tokensClone, $alignStrategy, $tokenContent));
}
}
private function injectAlignmentPlaceholdersDefault(Tokens $tokens, int $startAt, int $endAt, string $tokenContent): void
{
$newLineFoundSinceLastPlaceholder = true;
for ($index = $startAt; $index < $endAt; ++$index) {
$token = $tokens[$index];
$content = $token->getContent();
if (str_contains($content, "\n")) {
$newLineFoundSinceLastPlaceholder = true;
}
if (
strtolower($content) === $tokenContent
&& $this->tokensAnalyzer->isBinaryOperator($index)
&& ('=' !== $content || false === $this->isEqualPartOfDeclareStatement($tokens, $index))
&& $newLineFoundSinceLastPlaceholder
) {
$tokens[$index] = new Token(\sprintf(self::ALIGN_PLACEHOLDER, $this->currentLevel).$content);
$newLineFoundSinceLastPlaceholder = false;
continue;
}
if ($token->isGivenKind(\T_FN)) {
$from = $tokens->getNextMeaningfulToken($index);
$until = $this->tokensAnalyzer->getLastTokenIndexOfArrowFunction($index);
$this->injectAlignmentPlaceholders($tokens, $from + 1, $until - 1, $tokenContent);
$index = $until;
continue;
}
if ($token->isGivenKind([\T_FUNCTION, \T_CLASS])) {
$index = $tokens->getNextTokenOfKind($index, ['{', ';', '(']);
// We don't align `=` on multi-line definition of function parameters with default values
if ($tokens[$index]->equals('(')) {
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
continue;
}
if ($tokens[$index]->equals(';')) {
continue;
}
// Update the token to the `{` one in order to apply the following logic
$token = $tokens[$index];
}
if ($token->equals('{')) {
$until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
$this->injectAlignmentPlaceholders($tokens, $index + 1, $until - 1, $tokenContent);
$index = $until;
continue;
}
if ($token->equals('(')) {
$until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
$this->injectAlignmentPlaceholders($tokens, $index + 1, $until - 1, $tokenContent);
$index = $until;
continue;
}
if ($token->equals('[')) {
$index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index);
continue;
}
if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) {
$until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index);
$this->injectAlignmentPlaceholders($tokens, $index + 1, $until - 1, $tokenContent);
$index = $until;
continue;
}
}
}
private function injectAlignmentPlaceholders(Tokens $tokens, int $from, int $until, string $tokenContent): void
{
// Only inject placeholders for multi-line code
if ($tokens->isPartialCodeMultiline($from, $until)) {
++$this->deepestLevel;
$currentLevel = $this->currentLevel;
$this->currentLevel = $this->deepestLevel;
$this->injectAlignmentPlaceholdersDefault($tokens, $from, $until, $tokenContent);
$this->currentLevel = $currentLevel;
}
}
private function injectAlignmentPlaceholdersForArrow(Tokens $tokens, int $startAt, int $endAt): void
{
$newLineFoundSinceLastPlaceholder = true;
$yieldFoundSinceLastPlaceholder = false;
for ($index = $startAt; $index < $endAt; ++$index) {
$token = $tokens[$index];
$content = $token->getContent();
if (str_contains($content, "\n")) {
$newLineFoundSinceLastPlaceholder = true;
}
if ($token->isGivenKind(\T_YIELD)) {
$yieldFoundSinceLastPlaceholder = true;
}
if ($token->isGivenKind(\T_FN)) {
$yieldFoundSinceLastPlaceholder = false;
$from = $tokens->getNextMeaningfulToken($index);
$until = $this->tokensAnalyzer->getLastTokenIndexOfArrowFunction($index);
$this->injectArrayAlignmentPlaceholders($tokens, $from + 1, $until - 1);
$index = $until;
continue;
}
if ($token->isGivenKind(\T_ARRAY)) { // don't use "$tokens->isArray()" here, short arrays are handled in the next case
$yieldFoundSinceLastPlaceholder = false;
$from = $tokens->getNextMeaningfulToken($index);
$until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $from);
$index = $until;
$this->injectArrayAlignmentPlaceholders($tokens, $from + 1, $until - 1);
continue;
}
if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) {
$yieldFoundSinceLastPlaceholder = false;
$from = $index;
$until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $from);
$index = $until;
$this->injectArrayAlignmentPlaceholders($tokens, $from + 1, $until - 1);
continue;
}
// no need to analyse for `isBinaryOperator` (always true), nor if part of declare statement (not valid PHP)
// there is also no need to analyse the second arrow of a line
if ($token->isGivenKind(\T_DOUBLE_ARROW) && $newLineFoundSinceLastPlaceholder) {
if ($yieldFoundSinceLastPlaceholder) {
++$this->deepestLevel;
++$this->currentLevel;
}
$tokenContent = \sprintf(self::ALIGN_PLACEHOLDER, $this->currentLevel).$token->getContent();
$nextToken = $tokens[$index + 1];
if (!$nextToken->isWhitespace()) {
$tokenContent .= ' ';
} elseif ($nextToken->isWhitespace(" \t")) {
$tokens[$index + 1] = new Token([\T_WHITESPACE, ' ']);
}
$tokens[$index] = new Token([\T_DOUBLE_ARROW, $tokenContent]);
$newLineFoundSinceLastPlaceholder = false;
$yieldFoundSinceLastPlaceholder = false;
continue;
}
if ($token->equals(';')) {
++$this->deepestLevel;
++$this->currentLevel;
continue;
}
if ($token->equals(',')) {
for ($i = $index; $i < $endAt - 1; ++$i) {
if (str_contains($tokens[$i - 1]->getContent(), "\n")) {
$newLineFoundSinceLastPlaceholder = true;
break;
}
if ($tokens[$i + 1]->isGivenKind([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) {
$arrayStartIndex = $tokens[$i + 1]->isGivenKind(\T_ARRAY)
? $tokens->getNextMeaningfulToken($i + 1)
: $i + 1;
$blockType = Tokens::detectBlockType($tokens[$arrayStartIndex]);
$arrayEndIndex = $tokens->findBlockEnd($blockType['type'], $arrayStartIndex);
if ($tokens->isPartialCodeMultiline($arrayStartIndex, $arrayEndIndex)) {
break;
}
}
++$index;
}
}
if ($token->equals('{')) {
$until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
$this->injectArrayAlignmentPlaceholders($tokens, $index + 1, $until - 1);
$index = $until;
continue;
}
if ($token->equals('(')) {
$until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
$this->injectArrayAlignmentPlaceholders($tokens, $index + 1, $until - 1);
$index = $until;
continue;
}
}
}
private function injectArrayAlignmentPlaceholders(Tokens $tokens, int $from, int $until): void
{
// Only inject placeholders for multi-line arrays
if ($tokens->isPartialCodeMultiline($from, $until)) {
++$this->deepestLevel;
$currentLevel = $this->currentLevel;
$this->currentLevel = $this->deepestLevel;
$this->injectAlignmentPlaceholdersForArrow($tokens, $from, $until);
$this->currentLevel = $currentLevel;
}
}
private function fixWhiteSpaceBeforeOperator(Tokens $tokens, int $index, string $alignStrategy): void
{
// fix white space after operator is not needed as BinaryOperatorSpacesFixer took care of this (if strategy is _not_ ALIGN)
if (!$tokens[$index - 1]->isWhitespace()) {
$tokens->insertAt($index, new Token([\T_WHITESPACE, ' ']));
return;
}
if (
self::ALIGN_SINGLE_SPACE_MINIMAL !== $alignStrategy && self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE !== $alignStrategy
|| $tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()
) {
return;
}
$content = $tokens[$index - 1]->getContent();
if (' ' !== $content && !str_contains($content, "\n")) {
$tokens[$index - 1] = new Token([\T_WHITESPACE, ' ']);
}
}
/**
* Look for group of placeholders and provide vertical alignment.
*/
private function replacePlaceholders(Tokens $tokens, string $alignStrategy, string $tokenContent): string
{
$tmpCode = $tokens->generateCode();
for ($j = 0; $j <= $this->deepestLevel; ++$j) {
$placeholder = \sprintf(self::ALIGN_PLACEHOLDER, $j);
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | true |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Operator/NoUselessNullsafeOperatorFixer.php | src/Fixer/Operator/NoUselessNullsafeOperatorFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoUselessNullsafeOperatorFixer extends AbstractFixer
{
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There should not be useless Null-safe operator `?->` used.',
[
new VersionSpecificCodeSample(
<<<'PHP'
<?php
class Foo extends Bar
{
public function test() {
echo $this?->parentMethod();
}
}
PHP,
new VersionSpecification(8_00_00),
),
],
);
}
public function isCandidate(Tokens $tokens): bool
{
return \PHP_VERSION_ID >= 8_00_00 && $tokens->isAllTokenKindsFound([\T_VARIABLE, \T_NULLSAFE_OBJECT_OPERATOR]);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; $index >= 0; --$index) {
if (!$tokens[$index]->isGivenKind(\T_NULLSAFE_OBJECT_OPERATOR)) {
continue;
}
$nullsafeObjectOperatorIndex = $index;
$index = $tokens->getPrevMeaningfulToken($index);
if (!$tokens[$index]->isGivenKind(\T_VARIABLE)) {
continue;
}
if ('$this' !== strtolower($tokens[$index]->getContent())) {
continue;
}
$tokens[$nullsafeObjectOperatorIndex] = new Token([\T_OBJECT_OPERATOR, '->']);
}
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
PHP-CS-Fixer/PHP-CS-Fixer | https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/Operator/NoUselessConcatOperatorFixer.php | src/Fixer/Operator/NoUselessConcatOperatorFixer.php | <?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Fixer\Operator;
use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
/**
* @phpstan-type _ConcatOperandType array{
* start: int,
* end: int,
* type: self::STR_*,
* }
* @phpstan-type _AutogeneratedInputConfiguration array{
* juggle_simple_strings?: bool,
* }
* @phpstan-type _AutogeneratedComputedConfiguration array{
* juggle_simple_strings: bool,
* }
*
* @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
*
* @no-named-arguments Parameter names are not covered by the backward compatibility promise.
*/
final class NoUselessConcatOperatorFixer extends AbstractFixer implements ConfigurableFixerInterface
{
/** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
use ConfigurableFixerTrait;
private const STR_DOUBLE_QUOTE = 0;
private const STR_DOUBLE_QUOTE_VAR = 1;
private const STR_SINGLE_QUOTE = 2;
public function getDefinition(): FixerDefinitionInterface
{
return new FixerDefinition(
'There should not be useless concat operations.',
[
new CodeSample("<?php\n\$a = 'a'.'b';\n"),
new CodeSample("<?php\n\$a = 'a'.\"b\";\n", ['juggle_simple_strings' => true]),
],
);
}
/**
* {@inheritdoc}
*
* Must run before DateTimeCreateFromFormatCallFixer, EregToPregFixer, PhpUnitDedicateAssertInternalTypeFixer, RegularCallableCallFixer, SetTypeToCastFixer.
* Must run after ExplicitStringVariableFixer, NoBinaryStringFixer, SingleQuoteFixer.
*/
public function getPriority(): int
{
return 5;
}
public function isCandidate(Tokens $tokens): bool
{
return $tokens->isTokenKindFound('.') && $tokens->isAnyTokenKindsFound([\T_CONSTANT_ENCAPSED_STRING, '"']);
}
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
for ($index = $tokens->count() - 1; $index > 0; --$index) {
if (!$tokens[$index]->equals('.')) {
continue;
}
$nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($index);
if ($this->containsLinebreak($tokens, $index, $nextMeaningfulTokenIndex)) {
continue;
}
$secondOperand = $this->getConcatOperandType($tokens, $nextMeaningfulTokenIndex, 1);
if (null === $secondOperand) {
continue;
}
$prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($index);
if ($this->containsLinebreak($tokens, $prevMeaningfulTokenIndex, $index)) {
continue;
}
$firstOperand = $this->getConcatOperandType($tokens, $prevMeaningfulTokenIndex, -1);
if (null === $firstOperand) {
continue;
}
$this->fixConcatOperation($tokens, $firstOperand, $index, $secondOperand);
}
}
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('juggle_simple_strings', 'Allow for simple string quote juggling if it results in more concat-operations merges.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
]);
}
/**
* @param _ConcatOperandType $firstOperand
* @param _ConcatOperandType $secondOperand
*/
private function fixConcatOperation(Tokens $tokens, array $firstOperand, int $concatIndex, array $secondOperand): void
{
// if both operands are of the same type then these operands can always be merged
if (
(self::STR_DOUBLE_QUOTE === $firstOperand['type'] && self::STR_DOUBLE_QUOTE === $secondOperand['type'])
|| (self::STR_SINGLE_QUOTE === $firstOperand['type'] && self::STR_SINGLE_QUOTE === $secondOperand['type'])
) {
$this->mergeConstantEscapedStringOperands($tokens, $firstOperand, $concatIndex, $secondOperand);
return;
}
if (self::STR_DOUBLE_QUOTE_VAR === $firstOperand['type'] && self::STR_DOUBLE_QUOTE_VAR === $secondOperand['type']) {
if ($this->operandsCanNotBeMerged($tokens, $firstOperand, $secondOperand)) {
return;
}
$this->mergeConstantEscapedStringVarOperands($tokens, $firstOperand, $concatIndex, $secondOperand);
return;
}
// if any is double and the other is not, check for simple other, than merge with "
$operands = [
[$firstOperand, $secondOperand],
[$secondOperand, $firstOperand],
];
foreach ($operands as $operandPair) {
[$operand1, $operand2] = $operandPair;
if (self::STR_DOUBLE_QUOTE_VAR === $operand1['type'] && self::STR_DOUBLE_QUOTE === $operand2['type']) {
if ($this->operandsCanNotBeMerged($tokens, $operand1, $operand2)) {
return;
}
$this->mergeConstantEscapedStringVarOperands($tokens, $firstOperand, $concatIndex, $secondOperand);
return;
}
if (false === $this->configuration['juggle_simple_strings']) {
continue;
}
if (self::STR_DOUBLE_QUOTE === $operand1['type'] && self::STR_SINGLE_QUOTE === $operand2['type']) {
$operantContent = $tokens[$operand2['start']]->getContent();
if ($this->isSimpleQuotedStringContent($operantContent)) {
$this->mergeConstantEscapedStringOperands($tokens, $firstOperand, $concatIndex, $secondOperand);
}
return;
}
if (self::STR_DOUBLE_QUOTE_VAR === $operand1['type'] && self::STR_SINGLE_QUOTE === $operand2['type']) {
$operantContent = $tokens[$operand2['start']]->getContent();
if ($this->isSimpleQuotedStringContent($operantContent)) {
if ($this->operandsCanNotBeMerged($tokens, $operand1, $operand2)) {
return;
}
$this->mergeConstantEscapedStringVarOperands($tokens, $firstOperand, $concatIndex, $secondOperand);
}
return;
}
}
}
/**
* @param -1|1 $direction
*
* @return null|_ConcatOperandType
*/
private function getConcatOperandType(Tokens $tokens, int $index, int $direction): ?array
{
if ($tokens[$index]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) {
$firstChar = $tokens[$index]->getContent();
if ('b' === $firstChar[0] || 'B' === $firstChar[0]) {
return null; // we don't care about these, priorities are set to do deal with these cases
}
return [
'start' => $index,
'end' => $index,
'type' => '"' === $firstChar[0] ? self::STR_DOUBLE_QUOTE : self::STR_SINGLE_QUOTE,
];
}
if ($tokens[$index]->equals('"')) {
$end = $tokens->getTokenOfKindSibling($index, $direction, ['"']);
return [
'start' => 1 === $direction ? $index : $end,
'end' => 1 === $direction ? $end : $index,
'type' => self::STR_DOUBLE_QUOTE_VAR,
];
}
return null;
}
/**
* @param _ConcatOperandType $firstOperand
* @param _ConcatOperandType $secondOperand
*/
private function mergeConstantEscapedStringOperands(
Tokens $tokens,
array $firstOperand,
int $concatOperatorIndex,
array $secondOperand
): void {
$quote = self::STR_DOUBLE_QUOTE === $firstOperand['type'] || self::STR_DOUBLE_QUOTE === $secondOperand['type'] ? '"' : "'";
$firstOperandTokenContent = $tokens[$firstOperand['start']]->getContent();
$secondOperandTokenContent = $tokens[$secondOperand['start']]->getContent();
$tokens[$firstOperand['start']] = new Token(
[
\T_CONSTANT_ENCAPSED_STRING,
$quote.substr($firstOperandTokenContent, 1, -1).substr($secondOperandTokenContent, 1, -1).$quote,
],
);
$this->clearConcatAndAround($tokens, $concatOperatorIndex);
$tokens->clearTokenAndMergeSurroundingWhitespace($secondOperand['start']);
}
/**
* @param _ConcatOperandType $firstOperand
* @param _ConcatOperandType $secondOperand
*/
private function mergeConstantEscapedStringVarOperands(
Tokens $tokens,
array $firstOperand,
int $concatOperatorIndex,
array $secondOperand
): void {
// build up the new content
$newContent = '';
foreach ([$firstOperand, $secondOperand] as $operant) {
$operandContent = '';
for ($i = $operant['start']; $i <= $operant['end'];) {
$operandContent .= $tokens[$i]->getContent();
$i = $tokens->getNextMeaningfulToken($i);
}
$newContent .= substr($operandContent, 1, -1);
}
// remove tokens making up the concat statement
for ($i = $secondOperand['end']; $i >= $secondOperand['start'];) {
$tokens->clearTokenAndMergeSurroundingWhitespace($i);
$i = $tokens->getPrevMeaningfulToken($i);
}
$this->clearConcatAndAround($tokens, $concatOperatorIndex);
for ($i = $firstOperand['end']; $i > $firstOperand['start'];) {
$tokens->clearTokenAndMergeSurroundingWhitespace($i);
$i = $tokens->getPrevMeaningfulToken($i);
}
// insert new tokens based on the new content
$newTokens = Tokens::fromCode('<?php "'.$newContent.'";');
$newTokensCount = \count($newTokens);
$insertTokens = [];
for ($i = 1; $i < $newTokensCount - 1; ++$i) {
$insertTokens[] = $newTokens[$i];
}
$tokens->overrideRange($firstOperand['start'], $firstOperand['start'], $insertTokens);
}
private function clearConcatAndAround(Tokens $tokens, int $concatOperatorIndex): void
{
if ($tokens[$concatOperatorIndex + 1]->isWhitespace()) {
$tokens->clearTokenAndMergeSurroundingWhitespace($concatOperatorIndex + 1);
}
$tokens->clearTokenAndMergeSurroundingWhitespace($concatOperatorIndex);
if ($tokens[$concatOperatorIndex - 1]->isWhitespace()) {
$tokens->clearTokenAndMergeSurroundingWhitespace($concatOperatorIndex - 1);
}
}
private function isSimpleQuotedStringContent(string $candidate): bool
{
return !Preg::match('#[\$"\'\\\]#', substr($candidate, 1, -1));
}
private function containsLinebreak(Tokens $tokens, int $startIndex, int $endIndex): bool
{
for ($i = $endIndex; $i > $startIndex; --$i) {
if (Preg::match('/\R/', $tokens[$i]->getContent())) {
return true;
}
}
return false;
}
/**
* @param _ConcatOperandType $firstOperand
* @param _ConcatOperandType $secondOperand
*/
private function operandsCanNotBeMerged(Tokens $tokens, array $firstOperand, array $secondOperand): bool
{
// If the first operand does not end with a variable, no variables would be broken by concatenation.
if (self::STR_DOUBLE_QUOTE_VAR !== $firstOperand['type']) {
return false;
}
if (!$tokens[$firstOperand['end'] - 1]->isGivenKind(\T_VARIABLE)) {
return false;
}
$allowedPatternsForSecondOperand = [
'/^ .*/', // e.g. " foo", ' bar', " $baz"
'/^-(?!\>)/', // e.g. "-foo", '-bar', "-$baz"
];
// If the first operand ends with a variable, the second operand should match one of the allowed patterns.
// Otherwise, the concatenation can break a variable in the first operand.
foreach ($allowedPatternsForSecondOperand as $allowedPattern) {
$secondOperandInnerContent = substr($tokens->generatePartialCode($secondOperand['start'], $secondOperand['end']), 1, -1);
if (Preg::match($allowedPattern, $secondOperandInnerContent)) {
return false;
}
}
return true;
}
}
| php | MIT | 63b024eaaf8a48445494964bd21a6c38c788f40f | 2026-01-04T15:02:54.911792Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.