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/PregException.php
src/PregException.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer; /** * Exception that is thrown when PCRE function encounters an error. * * @author Kuba Werłos <werlos@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PregException extends \RuntimeException {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/AbstractPhpdocToTypeDeclarationFixer.php
src/AbstractPhpdocToTypeDeclarationFixer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer; use PhpCsFixer\DocBlock\Annotation; use PhpCsFixer\DocBlock\DocBlock; use PhpCsFixer\DocBlock\TypeExpression; use PhpCsFixer\Fixer\ConfigurableFixerInterface; use PhpCsFixer\Fixer\ConfigurableFixerTrait; use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer; use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @internal * * @phpstan-type _CommonTypeInfo array{commonType: string, isNullable: bool} * @phpstan-type _AutogeneratedInputConfiguration array{ * scalar_types?: bool, * types_map?: array<string, string>, * union_types?: bool, * } * @phpstan-type _AutogeneratedComputedConfiguration array{ * scalar_types: bool, * types_map: array<string, string>, * union_types: bool, * } * * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ abstract class AbstractPhpdocToTypeDeclarationFixer extends AbstractFixer implements ConfigurableFixerInterface { /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */ use ConfigurableFixerTrait; private const REGEX_CLASS = '(?:\\\?+'.TypeExpression::REGEX_IDENTIFIER .'(\\\\'.TypeExpression::REGEX_IDENTIFIER.')*+)'; /** * @var array<string, int> */ private array $versionSpecificTypes = [ 'void' => 7_01_00, 'iterable' => 7_01_00, 'object' => 7_02_00, 'mixed' => 8_00_00, 'never' => 8_01_00, ]; /** * @var array<string, bool> */ private array $scalarTypes = [ 'bool' => true, 'float' => true, 'int' => true, 'string' => true, ]; /** * @var array<string, bool> */ private static array $syntaxValidationCache = []; public function isRisky(): bool { return true; } abstract protected function isSkippedType(string $type): bool; protected function createConfigurationDefinition(): FixerConfigurationResolverInterface { return new FixerConfigurationResolver([ (new FixerOptionBuilder('scalar_types', 'Fix also scalar types; may have unexpected behaviour due to PHP bad type coercion system.')) ->setAllowedTypes(['bool']) ->setDefault(true) ->getOption(), (new FixerOptionBuilder('union_types', 'Fix also union types; turned on by default on PHP >= 8.0.0.')) ->setAllowedTypes(['bool']) ->setDefault(\PHP_VERSION_ID >= 8_00_00) ->getOption(), (new FixerOptionBuilder('types_map', 'Map of custom types, e.g. template types from PHPStan.')) ->setAllowedTypes(['array<string, string>']) ->setDefault([]) ->getOption(), ]); } /** * @param int $index The index of the function token */ protected function findFunctionDocComment(Tokens $tokens, int $index): ?int { do { $index = $tokens->getPrevNonWhitespace($index); } while ($tokens[$index]->isGivenKind([ \T_COMMENT, \T_ABSTRACT, \T_FINAL, \T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC, ])); if ($tokens[$index]->isGivenKind(\T_DOC_COMMENT)) { return $index; } return null; } /** * @return list<Annotation> */ protected function getAnnotationsFromDocComment(string $name, Tokens $tokens, int $docCommentIndex): array { $namespacesAnalyzer = new NamespacesAnalyzer(); $namespace = $namespacesAnalyzer->getNamespaceAt($tokens, $docCommentIndex); $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer(); $namespaceUses = $namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace); $doc = new DocBlock( $tokens[$docCommentIndex]->getContent(), $namespace, $namespaceUses, ); return $doc->getAnnotationsOfType($name); } /** * @return list<Token> */ protected function createTypeDeclarationTokens(string $type, bool $isNullable): array { $newTokens = []; if (true === $isNullable && 'mixed' !== $type) { $newTokens[] = new Token([CT::T_NULLABLE_TYPE, '?']); } $newTokens = array_merge( $newTokens, $this->createTokensFromRawType($type)->toArray(), ); // 'scalar's, 'void', 'iterable' and 'object' must be unqualified foreach ($newTokens as $i => $token) { if ($token->isGivenKind(\T_STRING)) { $typeUnqualified = $token->getContent(); if ( (isset($this->scalarTypes[$typeUnqualified]) || isset($this->versionSpecificTypes[$typeUnqualified])) && isset($newTokens[$i - 1]) && '\\' === $newTokens[$i - 1]->getContent() ) { unset($newTokens[$i - 1]); } } } return array_values($newTokens); } /** * Each fixer inheriting from this class must define a way of creating token collection representing type * gathered from phpDoc, e.g. `Foo|Bar` should be transformed into 3 tokens (`Foo`, `|` and `Bar`). * This can't be standardised, because some types may be allowed in one place, and invalid in others. * * @param string $type Type determined (and simplified) from phpDoc */ abstract protected function createTokensFromRawType(string $type): Tokens; /** * @return ?_CommonTypeInfo */ protected function getCommonTypeInfo(TypeExpression $typesExpression, bool $isReturnType): ?array { $commonType = $typesExpression->getCommonType(); $isNullable = $typesExpression->allowsNull(); if (null === $commonType) { return null; } if ($isNullable && 'void' === $commonType) { return null; } if ('static' === $commonType && (!$isReturnType || \PHP_VERSION_ID < 8_00_00)) { $commonType = 'self'; } if ($this->isSkippedType($commonType)) { return null; } if (\array_key_exists($commonType, $this->configuration['types_map'])) { $commonType = $this->configuration['types_map'][$commonType]; } if (isset($this->versionSpecificTypes[$commonType]) && \PHP_VERSION_ID < $this->versionSpecificTypes[$commonType]) { return null; } if (isset($this->scalarTypes[$commonType])) { if (false === $this->configuration['scalar_types']) { return null; } } elseif (!Preg::match('/^'.self::REGEX_CLASS.'$/', $commonType)) { return null; } return ['commonType' => $commonType, 'isNullable' => $isNullable]; } protected function getUnionTypes(TypeExpression $typesExpression, bool $isReturnType): ?string { if (\PHP_VERSION_ID < 8_00_00) { return null; } if (!$typesExpression->isUnionType()) { return null; } if (false === $this->configuration['union_types']) { return null; } $types = $typesExpression->getTypes(); $isNullable = $typesExpression->allowsNull(); $unionTypes = []; $containsOtherThanIterableType = false; $containsOtherThanEmptyType = false; foreach ($types as $type) { if ('null' === $type) { continue; } if ($this->isSkippedType($type)) { return null; } if (isset($this->versionSpecificTypes[$type]) && \PHP_VERSION_ID < $this->versionSpecificTypes[$type]) { return null; } $typeExpression = new TypeExpression($type, null, []); $commonTypeInfo = $this->getCommonTypeInfo($typeExpression, $isReturnType); if (null === $commonTypeInfo) { return null; } $commonType = $commonTypeInfo['commonType']; if (!$containsOtherThanIterableType && !\in_array($commonType, ['array', \Traversable::class, 'iterable'], true)) { $containsOtherThanIterableType = true; } if ($isReturnType && !$containsOtherThanEmptyType && !\in_array($commonType, ['null', 'void', 'never'], true)) { $containsOtherThanEmptyType = true; } if (!$isNullable && $commonTypeInfo['isNullable']) { $isNullable = true; } $unionTypes[] = $commonType; } if (!$containsOtherThanIterableType) { return null; } if ($isReturnType && !$containsOtherThanEmptyType) { return null; } if ($isNullable) { $unionTypes[] = 'null'; } return implode($typesExpression->getTypesGlue(), array_unique($unionTypes)); } final protected function isValidSyntax(string $code): bool { if (!isset(self::$syntaxValidationCache[$code])) { try { Tokens::fromCode($code); self::$syntaxValidationCache[$code] = true; } catch (\ParseError $e) { self::$syntaxValidationCache[$code] = false; } } return self::$syntaxValidationCache[$code]; } /** * @return list<string> */ final protected static function getTypesToExclude(string $content): array { $typesToExclude = []; $docBlock = new DocBlock($content); foreach ($docBlock->getAnnotationsOfType(['phpstan-type', 'psalm-type']) as $annotation) { $typesToExclude[] = $annotation->getTypeExpression()->toString(); } foreach ($docBlock->getAnnotationsOfType(['phpstan-import-type', 'psalm-import-type']) as $annotation) { $content = trim($annotation->getContent()); if (Preg::match('/\bas\s+('.TypeExpression::REGEX_IDENTIFIER.')$/', $content, $matches)) { $typesToExclude[] = $matches[1]; continue; } $typesToExclude[] = $annotation->getTypeExpression()->toString(); } return $typesToExclude; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/AbstractFunctionReferenceFixer.php
src/AbstractFunctionReferenceFixer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer; use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; use PhpCsFixer\Tokenizer\Tokens; /** * @internal * * @author Vladimir Reznichenko <kalessil@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ abstract class AbstractFunctionReferenceFixer extends AbstractFixer { private ?FunctionsAnalyzer $functionsAnalyzer = null; public function isCandidate(Tokens $tokens): bool { return $tokens->isTokenKindFound(\T_STRING); } public function isRisky(): bool { return true; } /** * Looks up Tokens sequence for suitable candidates and delivers boundaries information, * which can be supplied by other methods in this abstract class. * * @return ?array{int, int, int} returns $functionName, $openParenthesis, $closeParenthesis packed into array */ protected function find(string $functionNameToSearch, Tokens $tokens, int $start = 0, ?int $end = null): ?array { if (null === $this->functionsAnalyzer) { $this->functionsAnalyzer = new FunctionsAnalyzer(); } // make interface consistent with findSequence $end ??= $tokens->count(); // find raw sequence which we can analyse for context $candidateSequence = [[\T_STRING, $functionNameToSearch], '(']; $matches = $tokens->findSequence($candidateSequence, $start, $end, false); if (null === $matches) { return null; // not found, simply return without further attempts } // translate results for humans [$functionName, $openParenthesis] = array_keys($matches); if (!$this->functionsAnalyzer->isGlobalFunctionCall($tokens, $functionName)) { return $this->find($functionNameToSearch, $tokens, $openParenthesis, $end); } return [$functionName, $openParenthesis, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis)]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Doctrine/Annotation/Token.php
src/Doctrine/Annotation/Token.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Doctrine\Annotation; /** * A Doctrine annotation token. * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class Token { private int $type; private string $content; private int $position; /** * @param int $type The type * @param string $content The content */ public function __construct(int $type = DocLexer::T_NONE, string $content = '', int $position = 0) { $this->type = $type; $this->content = $content; $this->position = $position; } public function getType(): int { return $this->type; } public function setType(int $type): void { $this->type = $type; } public function getContent(): string { return $this->content; } public function setContent(string $content): void { $this->content = $content; } public function getPosition(): int { return $this->position; } /** * Returns whether the token type is one of the given types. * * @param int|list<int> $types */ public function isType($types): bool { if (!\is_array($types)) { $types = [$types]; } return \in_array($this->getType(), $types, true); } /** * Overrides the content with an empty string. */ public function clear(): void { $this->setContent(''); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Doctrine/Annotation/Tokens.php
src/Doctrine/Annotation/Tokens.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Doctrine\Annotation; use PhpCsFixer\Preg; use PhpCsFixer\Tokenizer\Token as PhpToken; /** * A list of Doctrine annotation tokens. * * @internal * * @extends \SplFixedArray<Token> * * `SplFixedArray` uses `T|null` in return types because value can be null if an offset is unset or if the size does not match the number of elements. * But our class takes care of it and always ensures correct size and indexes, so that these methods never return `null` instead of `Token`. * * @method Token offsetGet($offset) * @method \Traversable<int, Token> getIterator() * @method array<int, Token> toArray() * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class Tokens extends \SplFixedArray { /** * @param list<string> $ignoredTags * * @throws \InvalidArgumentException */ public static function createFromDocComment(PhpToken $input, array $ignoredTags = []): self { if (!$input->isGivenKind(\T_DOC_COMMENT)) { throw new \InvalidArgumentException('Input must be a T_DOC_COMMENT token.'); } $tokens = []; $content = $input->getContent(); $ignoredTextPosition = 0; $currentPosition = 0; $token = null; while (false !== $nextAtPosition = strpos($content, '@', $currentPosition)) { if (0 !== $nextAtPosition && !Preg::match('/\s/', $content[$nextAtPosition - 1])) { $currentPosition = $nextAtPosition + 1; continue; } $lexer = new DocLexer(); $lexer->setInput(substr($content, $nextAtPosition)); $scannedTokens = []; $index = 0; $nbScannedTokensToUse = 0; $nbScopes = 0; while (null !== $token = $lexer->peek()) { if (0 === $index && !$token->isType(DocLexer::T_AT)) { break; } if (1 === $index) { if (!$token->isType(DocLexer::T_IDENTIFIER) || \in_array($token->getContent(), $ignoredTags, true)) { break; } $nbScannedTokensToUse = 2; } if ($index >= 2 && 0 === $nbScopes && !$token->isType([DocLexer::T_NONE, DocLexer::T_OPEN_PARENTHESIS])) { break; } $scannedTokens[] = $token; if ($token->isType(DocLexer::T_OPEN_PARENTHESIS)) { ++$nbScopes; } elseif ($token->isType(DocLexer::T_CLOSE_PARENTHESIS)) { if (0 === --$nbScopes) { $nbScannedTokensToUse = \count($scannedTokens); break; } } ++$index; } if (0 !== $nbScopes) { break; } if (0 !== $nbScannedTokensToUse) { $ignoredTextLength = $nextAtPosition - $ignoredTextPosition; if (0 !== $ignoredTextLength) { $tokens[] = new Token(DocLexer::T_NONE, substr($content, $ignoredTextPosition, $ignoredTextLength)); } $lastTokenEndIndex = 0; foreach (\array_slice($scannedTokens, 0, $nbScannedTokensToUse) as $scannedToken) { $token = $scannedToken->isType(DocLexer::T_STRING) ? new Token( $scannedToken->getType(), '"'.str_replace('"', '""', $scannedToken->getContent()).'"', $scannedToken->getPosition(), ) : $scannedToken; $missingTextLength = $token->getPosition() - $lastTokenEndIndex; if ($missingTextLength > 0) { $tokens[] = new Token(DocLexer::T_NONE, substr( $content, $nextAtPosition + $lastTokenEndIndex, $missingTextLength, )); } $tokens[] = new Token($token->getType(), $token->getContent()); $lastTokenEndIndex = $token->getPosition() + \strlen($token->getContent()); } $currentPosition = $ignoredTextPosition = $nextAtPosition + $token->getPosition() + \strlen($token->getContent()); } else { $currentPosition = $nextAtPosition + 1; } } if ($ignoredTextPosition < \strlen($content)) { $tokens[] = new Token(DocLexer::T_NONE, substr($content, $ignoredTextPosition)); } return self::fromArray($tokens); } /** * Create token collection from array. * * @param array<int, Token> $array the array to import * @param ?bool $saveIndices save the numeric indices used in the original array, default is yes */ public static function fromArray($array, $saveIndices = null): self { $tokens = new self(\count($array)); if (null === $saveIndices || $saveIndices) { foreach ($array as $key => $val) { $tokens[$key] = $val; } } else { $index = 0; foreach ($array as $val) { $tokens[$index++] = $val; } } return $tokens; } /** * Returns the index of the closest next token that is neither a comment nor a whitespace token. */ public function getNextMeaningfulToken(int $index): ?int { return $this->getMeaningfulTokenSibling($index, 1); } /** * Returns the index of the last token that is part of the annotation at the given index. */ public function getAnnotationEnd(int $index): ?int { $currentIndex = null; if (isset($this[$index + 2])) { if ($this[$index + 2]->isType(DocLexer::T_OPEN_PARENTHESIS)) { $currentIndex = $index + 2; } elseif ( isset($this[$index + 3]) && $this[$index + 2]->isType(DocLexer::T_NONE) && $this[$index + 3]->isType(DocLexer::T_OPEN_PARENTHESIS) && Preg::match('/^(\R\s*\*\s*)*\s*$/', $this[$index + 2]->getContent()) ) { $currentIndex = $index + 3; } } if (null !== $currentIndex) { $level = 0; for ($max = \count($this); $currentIndex < $max; ++$currentIndex) { if ($this[$currentIndex]->isType(DocLexer::T_OPEN_PARENTHESIS)) { ++$level; } elseif ($this[$currentIndex]->isType(DocLexer::T_CLOSE_PARENTHESIS)) { --$level; } if (0 === $level) { return $currentIndex; } } return null; } return $index + 1; } /** * Returns the code from the tokens. */ public function getCode(): string { $code = ''; foreach ($this as $token) { $code .= $token->getContent(); } return $code; } /** * Inserts a token at the given index. */ public function insertAt(int $index, Token $token): void { $this->setSize($this->getSize() + 1); for ($i = $this->getSize() - 1; $i > $index; --$i) { $this[$i] = $this[$i - 1] ?? new Token(); } $this[$index] = $token; } public function offsetSet($index, $token): void { if (!$token instanceof Token) { throw new \InvalidArgumentException(\sprintf('Token must be an instance of %s, "%s" given.', Token::class, get_debug_type($token))); } parent::offsetSet($index, $token); } /** * @param mixed $index * * @throws \OutOfBoundsException */ public function offsetUnset($index): void { if (!isset($this[$index])) { throw new \OutOfBoundsException(\sprintf('Index "%s" is invalid or does not exist.', $index)); } $max = \count($this) - 1; while ($index < $max) { $this[$index] = $this[$index + 1]; ++$index; } parent::offsetUnset($index); $this->setSize($max); } private function getMeaningfulTokenSibling(int $index, int $direction): ?int { while (true) { $index += $direction; if (!$this->offsetExists($index)) { break; } if (!$this[$index]->isType(DocLexer::T_NONE)) { return $index; } } return null; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Doctrine/Annotation/DocLexer.php
src/Doctrine/Annotation/DocLexer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Doctrine\Annotation; use PhpCsFixer\Preg; /** * Copyright (c) 2006-2013 Doctrine Project. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DocLexer { public const T_NONE = 1; public const T_INTEGER = 2; public const T_STRING = 3; public const T_FLOAT = 4; // All tokens that are also identifiers should be >= 100 public const T_IDENTIFIER = 100; public const T_AT = 101; public const T_CLOSE_CURLY_BRACES = 102; public const T_CLOSE_PARENTHESIS = 103; public const T_COMMA = 104; public const T_EQUALS = 105; public const T_NAMESPACE_SEPARATOR = 107; public const T_OPEN_CURLY_BRACES = 108; public const T_OPEN_PARENTHESIS = 109; public const T_COLON = 112; public const T_MINUS = 113; private const CATCHABLE_PATTERNS = [ '[a-z_\\\][a-z0-9_\:\\\]*[a-z_][a-z0-9_]*', '(?:[+-]?[0-9]+(?:[\.][0-9]+)*)(?:[eE][+-]?[0-9]+)?', '"(?:""|[^"])*+"', ]; private const NON_CATCHABLE_PATTERNS = ['\s+', '\*+', '(.)']; /** @var array<string, self::T_*> */ private array $noCase = [ '@' => self::T_AT, ',' => self::T_COMMA, '(' => self::T_OPEN_PARENTHESIS, ')' => self::T_CLOSE_PARENTHESIS, '{' => self::T_OPEN_CURLY_BRACES, '}' => self::T_CLOSE_CURLY_BRACES, '=' => self::T_EQUALS, ':' => self::T_COLON, '-' => self::T_MINUS, '\\' => self::T_NAMESPACE_SEPARATOR, ]; /** @var list<Token> */ private array $tokens = []; private int $position = 0; private int $peek = 0; private ?string $regex = null; public function setInput(string $input): void { $this->tokens = []; $this->reset(); $this->scan($input); } public function reset(): void { $this->peek = 0; $this->position = 0; } public function peek(): ?Token { if (isset($this->tokens[$this->position + $this->peek])) { return $this->tokens[$this->position + $this->peek++]; } return null; } /** * @return self::T_* */ private function getType(string &$value): int { $type = self::T_NONE; if ('"' === $value[0]) { $value = str_replace('""', '"', substr($value, 1, \strlen($value) - 2)); return self::T_STRING; } if (isset($this->noCase[$value])) { return $this->noCase[$value]; } if ('_' === $value[0] || '\\' === $value[0] || !Preg::match('/[^A-Za-z]/', $value[0])) { return self::T_IDENTIFIER; } if (is_numeric($value)) { return str_contains($value, '.') || str_contains(strtolower($value), 'e') ? self::T_FLOAT : self::T_INTEGER; } return $type; } private function scan(string $input): void { $this->regex ??= \sprintf( '/(%s)|%s/%s', implode(')|(', self::CATCHABLE_PATTERNS), implode('|', self::NON_CATCHABLE_PATTERNS), 'iu', ); $flags = \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_OFFSET_CAPTURE; $matches = Preg::split($this->regex, $input, -1, $flags); foreach ($matches as $match) { // Must remain before 'value' assignment since it can change content $firstMatch = $match[0]; $type = $this->getType($firstMatch); $this->tokens[] = new Token($type, $firstMatch, (int) $match[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/Linter/TokenizerLinter.php
src/Linter/TokenizerLinter.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Linter; use PhpCsFixer\FileReader; use PhpCsFixer\Hasher; use PhpCsFixer\Tokenizer\Tokens; /** * Handle PHP code linting. * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @readonly * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class TokenizerLinter implements LinterInterface { public function isAsync(): bool { return false; } public function lintFile(string $path): LintingResultInterface { return $this->lintSource(FileReader::createSingleton()->read($path)); } public function lintSource(string $source): LintingResultInterface { try { // To lint, we will parse the source into Tokens. // During that process, it might throw a ParseError or CompileError. // If it won't, cache of tokenized version of source will be kept, which is great for Runner. // Yet, first we need to clear already existing cache to not hit it and lint the code indeed. $codeHash = Hasher::calculate($source); Tokens::clearCache($codeHash); Tokens::fromCode($source); return new TokenizerLintingResult(); } catch (\CompileError|\ParseError $e) { return new TokenizerLintingResult($e); } } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Linter/ProcessLinterProcessBuilder.php
src/Linter/ProcessLinterProcessBuilder.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Linter; use Symfony\Component\Process\Process; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @readonly * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ProcessLinterProcessBuilder { private string $executable; /** * @param string $executable PHP executable */ public function __construct(string $executable) { $this->executable = $executable; } public function build(string $path): Process { return new Process([ $this->executable, '-l', $path, ]); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Linter/Linter.php
src/Linter/Linter.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Linter; /** * Handle PHP code linting process. * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @readonly * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class Linter implements LinterInterface { private LinterInterface $subLinter; public function __construct() { $this->subLinter = new TokenizerLinter(); } public function isAsync(): bool { return $this->subLinter->isAsync(); } public function lintFile(string $path): LintingResultInterface { return $this->subLinter->lintFile($path); } public function lintSource(string $source): LintingResultInterface { return $this->subLinter->lintSource($source); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Linter/UnavailableLinterException.php
src/Linter/UnavailableLinterException.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Linter; /** * Exception that is thrown when the chosen linter is not available on the environment. * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @final * * @TODO 4.0 make class "final" * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ class UnavailableLinterException extends \RuntimeException {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Linter/ProcessLinter.php
src/Linter/ProcessLinter.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Linter; use PhpCsFixer\FileReader; use PhpCsFixer\FileRemoval; use Symfony\Component\Filesystem\Exception\IOException; use Symfony\Component\Process\PhpExecutableFinder; use Symfony\Component\Process\Process; /** * Handle PHP code linting using separated process of `php -l _file_`. * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ProcessLinter implements LinterInterface { private FileRemoval $fileRemoval; private ProcessLinterProcessBuilder $processBuilder; /** * Temporary file for code linting. */ private ?string $temporaryFile = null; /** * @param null|string $executable PHP executable, null for autodetection */ public function __construct(?string $executable = null) { if (null === $executable) { $executableFinder = new PhpExecutableFinder(); $executable = $executableFinder->find(false); if (false === $executable) { throw new UnavailableLinterException('Cannot find PHP executable.'); } if ('phpdbg' === \PHP_SAPI) { if (!str_contains($executable, 'phpdbg')) { throw new UnavailableLinterException('Automatically found PHP executable is non-standard phpdbg. Could not find proper PHP executable.'); } // automatically found executable is `phpdbg`, let us try to fallback to regular `php` $executable = str_replace('phpdbg', 'php', $executable); if (!is_executable($executable)) { throw new UnavailableLinterException('Automatically found PHP executable is phpdbg. Could not find proper PHP executable.'); } } } $this->processBuilder = new ProcessLinterProcessBuilder($executable); $this->fileRemoval = new FileRemoval(); } public function __destruct() { if (null !== $this->temporaryFile) { $this->fileRemoval->delete($this->temporaryFile); } } /** * This class is not intended to be serialized, * and cannot be deserialized (see __wakeup method). */ public function __sleep(): array { throw new \BadMethodCallException('Cannot serialize '.self::class); } /** * Disable the deserialization of the class to prevent attacker executing * code by leveraging the __destruct method. * * @see https://owasp.org/www-community/vulnerabilities/PHP_Object_Injection */ public function __wakeup(): void { throw new \BadMethodCallException('Cannot unserialize '.self::class); } public function isAsync(): bool { return true; } public function lintFile(string $path): LintingResultInterface { return new ProcessLintingResult($this->createProcessForFile($path), $path); } public function lintSource(string $source): LintingResultInterface { return new ProcessLintingResult($this->createProcessForSource($source), $this->temporaryFile); } /** * @param string $path path to file */ private function createProcessForFile(string $path): Process { // in case php://stdin if (!is_file($path)) { return $this->createProcessForSource(FileReader::createSingleton()->read($path)); } $process = $this->processBuilder->build($path); $process->setTimeout(10); $process->start(); return $process; } /** * Create process that lint PHP code. * * @param string $source code */ private function createProcessForSource(string $source): Process { if (null === $this->temporaryFile) { $this->temporaryFile = tempnam(sys_get_temp_dir(), 'cs_fixer_tmp_'); $this->fileRemoval->observe($this->temporaryFile); } if (false === @file_put_contents($this->temporaryFile, $source)) { throw new IOException(\sprintf('Failed to write file "%s".', $this->temporaryFile), 0, null, $this->temporaryFile); } return $this->createProcessForFile($this->temporaryFile); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Linter/CachingLinter.php
src/Linter/CachingLinter.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Linter; use PhpCsFixer\Hasher; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class CachingLinter implements LinterInterface { private LinterInterface $sublinter; /** * @var array<string, LintingResultInterface> */ private array $cache = []; public function __construct(LinterInterface $linter) { $this->sublinter = $linter; } public function isAsync(): bool { return $this->sublinter->isAsync(); } public function lintFile(string $path): LintingResultInterface { $checksum = Hasher::calculate(file_get_contents($path)); return $this->cache[$checksum] ??= $this->sublinter->lintFile($path); } public function lintSource(string $source): LintingResultInterface { $checksum = Hasher::calculate($source); return $this->cache[$checksum] ??= $this->sublinter->lintSource($source); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Linter/ProcessLintingResult.php
src/Linter/ProcessLintingResult.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Linter; use Symfony\Component\Process\Process; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ProcessLintingResult implements LintingResultInterface { private Process $process; private ?string $path; private ?bool $isSuccessful = null; public function __construct(Process $process, ?string $path = null) { $this->process = $process; $this->path = $path; } public function check(): void { if (!$this->isSuccessful()) { // on some systems stderr is used, but on others, it's not throw new LintingException($this->getProcessErrorMessage(), $this->process->getExitCode()); } } private function getProcessErrorMessage(): string { $errorOutput = $this->process->getErrorOutput(); $output = strtok(ltrim('' !== $errorOutput ? $errorOutput : $this->process->getOutput()), "\n"); if (false === $output) { return 'Fatal error: Unable to lint file.'; } if (null !== $this->path) { $needle = \sprintf('in %s ', $this->path); $pos = strrpos($output, $needle); if (false !== $pos) { $output = \sprintf('%s%s', substr($output, 0, $pos), substr($output, $pos + \strlen($needle))); } } $prefix = substr($output, 0, 18); if ('PHP Parse error: ' === $prefix) { return \sprintf('Parse error: %s.', substr($output, 18)); } if ('PHP Fatal error: ' === $prefix) { return \sprintf('Fatal error: %s.', substr($output, 18)); } return \sprintf('%s.', $output); } private function isSuccessful(): bool { if (null === $this->isSuccessful) { $this->process->wait(); $this->isSuccessful = $this->process->isSuccessful(); } return $this->isSuccessful; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Linter/LinterInterface.php
src/Linter/LinterInterface.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Linter; /** * Interface for PHP code linting process manager. * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ interface LinterInterface { public function isAsync(): bool; /** * Lint PHP file. */ public function lintFile(string $path): LintingResultInterface; /** * Lint PHP code. */ public function lintSource(string $source): LintingResultInterface; }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Linter/LintingException.php
src/Linter/LintingException.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Linter; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @final * * @TODO 4.0 make class "final" * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ class LintingException extends \RuntimeException {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Linter/TokenizerLintingResult.php
src/Linter/TokenizerLintingResult.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Linter; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @readonly * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class TokenizerLintingResult implements LintingResultInterface { private ?\Error $error; public function __construct(?\Error $error = null) { $this->error = $error; } public function check(): void { if (null !== $this->error) { throw new LintingException( \sprintf('%s: %s on line %d.', $this->getMessagePrefix(), $this->error->getMessage(), $this->error->getLine()), $this->error->getCode(), $this->error, ); } } private function getMessagePrefix(): string { return $this->error instanceof \ParseError ? 'Parse error' : 'Fatal error'; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Linter/LintingResultInterface.php
src/Linter/LintingResultInterface.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Linter; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ interface LintingResultInterface { /** * Check if linting process was successful and raise LintingException if not. */ public function check(): void; }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Documentation/DocumentationTag.php
src/Documentation/DocumentationTag.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Documentation; /** * @readonly * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DocumentationTag { /** * @var DocumentationTagType::* * * @readonly */ public string $type; /** * @readonly */ public string $title; /** * @readonly */ public ?string $description; /** * @param DocumentationTagType::* $type */ public function __construct( string $type, string $title, ?string $description = null ) { $this->type = $type; $this->title = $title; $this->description = $description; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Documentation/RstUtils.php
src/Documentation/RstUtils.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Documentation; use PhpCsFixer\Preg; /** * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class RstUtils { private function __construct() { // cannot create instance of util. class } public static function toRst(string $string, int $indent = 0): string { $string = wordwrap(self::ensureProperInlineCode($string), 80 - $indent); return 0 === $indent ? $string : self::indent($string, $indent); } public static function ensureProperInlineCode(string $string): string { return Preg::replace('/(?<!`)(`[^`]+`)(?!`)/', '`$1`', $string); } public static function indent(string $string, int $indent): string { return Preg::replace('/(\n)(?!\n|$)/', '$1'.str_repeat(' ', $indent), $string); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Documentation/FixerDocumentGenerator.php
src/Documentation/FixerDocumentGenerator.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Documentation; use PhpCsFixer\Console\Command\HelpCommand; use PhpCsFixer\Differ\FullDiffer; use PhpCsFixer\Fixer\ConfigurableFixerInterface; use PhpCsFixer\Fixer\FixerInterface; use PhpCsFixer\FixerConfiguration\AliasedFixerOption; use PhpCsFixer\FixerConfiguration\AllowedValueSubset; use PhpCsFixer\FixerConfiguration\DeprecatedFixerOptionInterface; use PhpCsFixer\FixerDefinition\CodeSampleInterface; use PhpCsFixer\FixerDefinition\FileSpecificCodeSampleInterface; use PhpCsFixer\FixerDefinition\VersionSpecificCodeSampleInterface; use PhpCsFixer\Preg; use PhpCsFixer\RuleSet\AutomaticRuleSetDefinitionInterface; use PhpCsFixer\RuleSet\DeprecatedRuleSetDefinitionInterface; use PhpCsFixer\RuleSet\RuleSet; use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; use PhpCsFixer\RuleSet\RuleSets; use PhpCsFixer\StdinFileInfo; use PhpCsFixer\Tokenizer\Tokens; use PhpCsFixer\Utils; /** * @readonly * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class FixerDocumentGenerator { private DocumentationLocator $locator; private FullDiffer $differ; /** @var array<string, RuleSetDefinitionInterface> */ private array $ruleSetDefinitions; public function __construct(DocumentationLocator $locator) { $this->locator = $locator; $this->differ = new FullDiffer(); $this->ruleSetDefinitions = RuleSets::getSetDefinitions(); } public function generateFixerDocumentation(FixerInterface $fixer): string { $name = $fixer->getName(); $title = "Rule ``{$name}``"; $titleLine = str_repeat('=', \strlen($title)); $doc = "{$titleLine}\n{$title}\n{$titleLine}"; $definition = $fixer->getDefinition(); $doc .= "\n\n".RstUtils::toRst($definition->getSummary()); $description = $definition->getDescription(); if (null !== $description) { $description = RstUtils::toRst($description); $doc .= <<<RST Description ----------- {$description} RST; } $header = static function (string $message, string $underline = '-'): string { $line = str_repeat($underline, \strlen($message)); return "{$message}\n{$line}\n"; }; $tags = DocumentationTagGenerator::analyseRule($fixer); $warnings = array_map( static function (DocumentationTag $tag): string { $titleLine = str_repeat('~', \strlen($tag->title)); return \sprintf( "\n%s\n%s\n\n%s", $tag->title, $titleLine, null === $tag->description ? '' : RstUtils::toRst($tag->description, 0), ); }, $tags, ); if ([] !== $warnings) { $warningsHeader = 1 === \count($warnings) ? 'Warning' : 'Warnings'; $doc .= "\n\n".$header($warningsHeader).implode("\n", $warnings); } if ($fixer instanceof ConfigurableFixerInterface) { $doc .= <<<'RST' Configuration ------------- RST; $configurationDefinition = $fixer->getConfigurationDefinition(); foreach ($configurationDefinition->getOptions() as $option) { $optionInfo = "``{$option->getName()}``"; $optionInfo .= "\n".str_repeat('~', \strlen($optionInfo)); if ($option instanceof DeprecatedFixerOptionInterface) { $deprecationMessage = RstUtils::toRst($option->getDeprecationMessage()); $optionInfo .= "\n\n.. warning:: This option is deprecated and will be removed in the next major version. {$deprecationMessage}"; } $optionInfo .= "\n\n".RstUtils::toRst($option->getDescription()); if ($option instanceof AliasedFixerOption) { $optionInfo .= "\n\n.. note:: The previous name of this option was ``{$option->getAlias()}`` but it is now deprecated and will be removed in the next major version."; } $allowed = HelpCommand::getDisplayableAllowedValues($option); if (null === $allowed) { $allowedKind = 'Allowed types'; $allowedTypes = $option->getAllowedTypes(); if (null !== $allowedTypes) { $allowed = array_map( static fn (string $value): string => '``'.Utils::convertArrayTypeToList($value).'``', $allowedTypes, ); } } else { $allowedKind = 'Allowed values'; $allowed = array_map(static fn ($value): string => $value instanceof AllowedValueSubset ? 'a subset of ``'.Utils::toString($value->getAllowedValues()).'``' : '``'.Utils::toString($value).'``', $allowed); } if (null !== $allowed) { $allowed = Utils::naturalLanguageJoin($allowed, ''); $optionInfo .= "\n\n{$allowedKind}: {$allowed}"; } if ($option->hasDefault()) { $default = Utils::toString($option->getDefault()); $optionInfo .= "\n\nDefault value: ``{$default}``"; } else { $optionInfo .= "\n\nThis option is required."; } $doc .= "\n\n{$optionInfo}"; } } $samples = $definition->getCodeSamples(); if (0 !== \count($samples)) { $doc .= <<<'RST' Examples -------- RST; foreach ($samples as $index => $sample) { $title = \sprintf('Example #%d', $index + 1); $titleLine = str_repeat('~', \strlen($title)); $doc .= "\n\n{$title}\n{$titleLine}"; if ($fixer instanceof ConfigurableFixerInterface) { if (null === $sample->getConfiguration()) { $doc .= "\n\n*Default* configuration."; } else { $doc .= \sprintf( "\n\nWith configuration: ``%s``.", Utils::toString($sample->getConfiguration()), ); } } $doc .= "\n".$this->generateSampleDiff($fixer, $sample, $index + 1, $name); } } $ruleSetConfigs = self::getSetsOfRule($name); if ([] !== $ruleSetConfigs) { $plural = 1 !== \count($ruleSetConfigs) ? 's' : ''; $doc .= <<<RST Rule sets --------- The rule is part of the following rule set{$plural}:\n\n RST; foreach ($ruleSetConfigs as $set => $config) { $ruleSetPath = $this->locator->getRuleSetsDocumentationFilePath($set); $ruleSetPath = substr($ruleSetPath, strrpos($ruleSetPath, '/')); \assert(isset($this->ruleSetDefinitions[$set])); $ruleSetDefinition = $this->ruleSetDefinitions[$set]; if ($ruleSetDefinition instanceof AutomaticRuleSetDefinitionInterface) { continue; } $deprecatedDesc = ($ruleSetDefinition instanceof DeprecatedRuleSetDefinitionInterface) ? ' *(deprecated)*' : ''; $configInfo = (null !== $config) ? " with config:\n\n ``".Utils::toString($config)."``\n" : ''; $doc .= <<<RST - `{$set} <./../../ruleSets{$ruleSetPath}>`_{$deprecatedDesc}{$configInfo}\n RST; } $doc = trim($doc); } $reflectionObject = new \ReflectionObject($fixer); $className = str_replace('\\', '\\\\', $reflectionObject->getName()); $fileName = $reflectionObject->getFileName(); $fileName = str_replace('\\', '/', $fileName); $fileName = substr($fileName, (int) strrpos($fileName, '/src/Fixer/') + 1); $fileName = "`{$className} <./../../../{$fileName}>`_"; $testFileName = Preg::replace('~.*\K/src/(?=Fixer/)~', '/tests/', $fileName); $testFileName = Preg::replace('~PhpCsFixer\\\\\\\\\K(?=Fixer\\\\\\\)~', 'Tests\\\\\\\\', $testFileName); $testFileName = Preg::replace('~(?= <|\.php>)~', 'Test', $testFileName); $doc .= <<<RST References ---------- - Fixer class: {$fileName} - Test class: {$testFileName} The test class defines officially supported behaviour. Each test case is a part of our backward compatibility promise. RST; $doc = str_replace("\t", '<TAB>', $doc); return "{$doc}\n"; } /** * @internal * * @return array<string, null|array<string, mixed>> */ public static function getSetsOfRule(string $ruleName): array { static $ruleSetCache = null; if (null === $ruleSetCache) { $definitionNames = array_keys( array_filter( RuleSets::getSetDefinitions(), static fn (RuleSetDefinitionInterface $definition): bool => !$definition instanceof AutomaticRuleSetDefinitionInterface, ), ); $ruleSetCache = array_combine( $definitionNames, array_map( static fn (string $name): RuleSet => new RuleSet([$name => true]), $definitionNames, ), ); } $ruleSetConfigs = []; foreach ($ruleSetCache as $set => $ruleSet) { if ($ruleSet->hasRule($ruleName)) { $ruleSetConfigs[$set] = $ruleSet->getRuleConfiguration($ruleName); } } return $ruleSetConfigs; } /** * @param list<FixerInterface> $fixers */ public function generateFixersDocumentationIndex(array $fixers): string { $overrideGroups = [ 'PhpUnit' => 'PHPUnit', 'PhpTag' => 'PHP Tag', 'Phpdoc' => 'PHPDoc', ]; usort($fixers, static fn (FixerInterface $a, FixerInterface $b): int => \get_class($a) <=> \get_class($b)); $documentation = <<<'RST' ======================= List of Available Rules ======================= RST; $currentGroup = null; foreach ($fixers as $fixer) { $namespace = Preg::replace('/^.*\\\(.+)\\\.+Fixer$/', '$1', \get_class($fixer)); $group = $overrideGroups[$namespace] ?? Preg::replace('/(?<=[[:lower:]])(?=[[:upper:]])/', ' ', $namespace); if ($group !== $currentGroup) { $underline = str_repeat('-', \strlen($group)); $documentation .= "\n\n{$group}\n{$underline}\n"; $currentGroup = $group; } $path = './'.$this->locator->getFixerDocumentationFileRelativePath($fixer); $tags = array_map( static fn (DocumentationTag $tag): string => $tag->type, DocumentationTagGenerator::analyseRule($fixer), ); $attributes = 0 === \count($tags) ? '' : ' *('.implode(', ', $tags).')*'; $summary = str_replace('`', '``', $fixer->getDefinition()->getSummary()); $documentation .= <<<RST - `{$fixer->getName()} <{$path}>`_{$attributes} {$summary} RST; } return "{$documentation}\n"; } private function generateSampleDiff(FixerInterface $fixer, CodeSampleInterface $sample, int $sampleNumber, string $ruleName): string { if ($sample instanceof VersionSpecificCodeSampleInterface && !$sample->isSuitableFor(\PHP_VERSION_ID)) { $existingFile = @file_get_contents($this->locator->getFixerDocumentationFilePath($fixer)); if (false !== $existingFile) { Preg::match("/\\RExample #{$sampleNumber}\\R.+?(?<diff>\\R\\.\\. code-block:: diff\\R\\R.*?)\\R(?:\\R\\S|$)/s", $existingFile, $matches); if (isset($matches['diff'])) { return $matches['diff']; } } $error = <<<RST .. error:: Cannot generate diff for code sample #{$sampleNumber} of rule {$ruleName}: the sample is not suitable for current version of PHP (%s). RST; return \sprintf($error, \PHP_VERSION); } $old = $sample->getCode(); $tokens = Tokens::fromCode($old); $file = $sample instanceof FileSpecificCodeSampleInterface ? $sample->getSplFileInfo() : new StdinFileInfo(); if ($fixer instanceof ConfigurableFixerInterface) { $fixer->configure($sample->getConfiguration() ?? []); } $fixer->fix($file, $tokens); $diff = $this->differ->diff($old, $tokens->generateCode()); $diff = Preg::replace('/@@[ \+\-\d,]+@@\n/', '', $diff); $diff = Preg::replace('/\r/', '^M', $diff); $diff = Preg::replace('/^ $/m', '', $diff); $diff = Preg::replace('/\n$/', '', $diff); $diff = RstUtils::indent($diff, 3); return <<<RST .. code-block:: diff {$diff} RST; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Documentation/DocumentationLocator.php
src/Documentation/DocumentationLocator.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Documentation; use PhpCsFixer\Fixer\FixerInterface; use PhpCsFixer\Preg; use PhpCsFixer\Utils; /** * @readonly * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DocumentationLocator { private string $path; public function __construct() { $this->path = \dirname(__DIR__, 2).'/doc'; } public function getFixersDocumentationDirectoryPath(): string { return $this->path.'/rules'; } public function getFixersDocumentationIndexFilePath(): string { return $this->getFixersDocumentationDirectoryPath().'/index.rst'; } public function getFixerDocumentationFilePath(FixerInterface $fixer): string { return $this->getFixersDocumentationDirectoryPath().'/'.Preg::replaceCallback( '/^.*\\\(.+)\\\(.+)Fixer$/', static fn (array $matches): string => Utils::camelCaseToUnderscore($matches[1]).'/'.Utils::camelCaseToUnderscore($matches[2]), \get_class($fixer), ).'.rst'; } public function getFixerDocumentationFileRelativePath(FixerInterface $fixer): string { return Preg::replace( '#^'.preg_quote($this->getFixersDocumentationDirectoryPath(), '#').'/#', '', $this->getFixerDocumentationFilePath($fixer), ); } public function getRuleSetsDocumentationDirectoryPath(): string { return $this->path.'/ruleSets'; } public function getRuleSetsDocumentationIndexFilePath(): string { return $this->getRuleSetsDocumentationDirectoryPath().'/index.rst'; } public function getRuleSetsDocumentationFilePath(string $name): string { return $this->getRuleSetsDocumentationDirectoryPath().'/'.str_replace(':risky', 'Risky', ucfirst(substr($name, 1))).'.rst'; } public function getUsageFilePath(): string { return $this->path.'/usage.rst'; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Documentation/DocumentationTagType.php
src/Documentation/DocumentationTagType.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Documentation; /** * @readonly * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DocumentationTagType { public const EXPERIMENTAL = 'experimental'; public const INTERNAL = 'internal'; public const DEPRECATED = 'deprecated'; public const RISKY = 'risky'; public const CONFIGURABLE = 'configurable'; public const AUTOMATIC = 'automatic'; private function __construct() {} }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Documentation/RuleSetDocumentationGenerator.php
src/Documentation/RuleSetDocumentationGenerator.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Documentation; use PhpCsFixer\Fixer\FixerInterface; use PhpCsFixer\Preg; use PhpCsFixer\RuleSet\AutomaticRuleSetDefinitionInterface; use PhpCsFixer\RuleSet\DeprecatedRuleSetDefinitionInterface; use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; use PhpCsFixer\Utils; /** * @readonly * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class RuleSetDocumentationGenerator { private DocumentationLocator $locator; public function __construct(DocumentationLocator $locator) { $this->locator = $locator; } /** * @param list<FixerInterface> $fixers */ public function generateRuleSetsDocumentation(RuleSetDefinitionInterface $definition, array $fixers): string { $fixerNames = []; foreach ($fixers as $fixer) { $fixerNames[$fixer->getName()] = $fixer; } $title = "Rule set ``{$definition->getName()}``"; $titleLine = str_repeat('=', \strlen($title)); $doc = "{$titleLine}\n{$title}\n{$titleLine}\n\n".$definition->getDescription(); $header = static function (string $message, string $underline = '-'): string { $line = str_repeat($underline, \strlen($message)); return "{$message}\n{$line}\n"; }; $tags = DocumentationTagGenerator::analyseRuleSet($definition); $warnings = array_map( static function (DocumentationTag $tag): string { $titleLine = str_repeat('~', \strlen($tag->title)); return \sprintf( "\n%s\n%s\n\n%s", $tag->title, $titleLine, null === $tag->description ? '' : RstUtils::toRst($tag->description, 0), ); }, $tags, ); if ([] !== $warnings) { $warningsHeader = 1 === \count($warnings) ? 'Warning' : 'Warnings'; $doc .= "\n\n".$header($warningsHeader).implode("\n", $warnings); } $rules = $definition instanceof AutomaticRuleSetDefinitionInterface ? $definition->getRulesCandidates() : $definition->getRules(); if ([] === $rules) { $doc .= "\n\nThis is an empty set."; } else { $enabledRules = array_filter($rules, static fn ($config) => false !== $config); $disabledRules = array_filter($rules, static fn ($config) => false === $config); $listRules = function (array $rules) use (&$doc, $fixerNames): void { foreach ($rules as $rule => $config) { if (str_starts_with($rule, '@')) { $ruleSetPath = $this->locator->getRuleSetsDocumentationFilePath($rule); $ruleSetPath = substr($ruleSetPath, strrpos($ruleSetPath, '/')); $doc .= "\n- `{$rule} <.{$ruleSetPath}>`_"; } else { $path = Preg::replace( '#^'.preg_quote($this->locator->getFixersDocumentationDirectoryPath(), '#').'/#', './../rules/', $this->locator->getFixerDocumentationFilePath($fixerNames[$rule]), ); $doc .= "\n- `{$rule} <{$path}>`_"; } if (!\is_bool($config)) { $doc .= " with config:\n\n ``".Utils::toString($config)."``\n"; } } }; $rulesCandidatesDescriptionHeader = $definition instanceof AutomaticRuleSetDefinitionInterface ? ' candidates' : ''; if ([] !== $enabledRules) { $doc .= "\n\n".$header("Rules{$rulesCandidatesDescriptionHeader}"); $listRules($enabledRules); } if ([] !== $disabledRules) { $doc .= "\n\n".$header("Disabled rules{$rulesCandidatesDescriptionHeader}"); $listRules($disabledRules); } } return $doc."\n"; } /** * @param array<string, RuleSetDefinitionInterface> $setDefinitions */ public function generateRuleSetsDocumentationIndex(array $setDefinitions): string { $documentation = <<<'RST' =========================== List of Available Rule sets =========================== RST; foreach ($setDefinitions as $path => $definition) { $path = substr($path, strrpos($path, '/')); $attributes = []; if ($definition instanceof DeprecatedRuleSetDefinitionInterface) { $attributes[] = 'deprecated'; } $attributes = 0 === \count($attributes) ? '' : ' *('.implode(', ', $attributes).')*'; $documentation .= "\n- `{$definition->getName()} <.{$path}>`_{$attributes}"; } return $documentation."\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/Documentation/DocumentationTagGenerator.php
src/Documentation/DocumentationTagGenerator.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Documentation; use PhpCsFixer\Console\Application; use PhpCsFixer\Fixer\ConfigurableFixerInterface; use PhpCsFixer\Fixer\DeprecatedFixerInterface; use PhpCsFixer\Fixer\ExperimentalFixerInterface; use PhpCsFixer\Fixer\FixerInterface; use PhpCsFixer\Fixer\InternalFixerInterface; use PhpCsFixer\FixerConfiguration\FixerOptionInterface; use PhpCsFixer\RuleSet\AutomaticRuleSetDefinitionInterface; use PhpCsFixer\RuleSet\DeprecatedRuleSetDefinitionInterface; use PhpCsFixer\RuleSet\InternalRuleSetDefinitionInterface; use PhpCsFixer\RuleSet\RuleSetDefinitionInterface; use PhpCsFixer\Utils; /** * @readonly * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DocumentationTagGenerator { /** * @return list<DocumentationTag> */ public static function analyseRuleSet(RuleSetDefinitionInterface $ruleSetDefinition): array { $tags = []; // not possible for set to be DocumentationTagType::EXPERIMENTAL if ($ruleSetDefinition instanceof InternalRuleSetDefinitionInterface) { $tags[] = new DocumentationTag( DocumentationTagType::INTERNAL, 'This rule set is INTERNAL', 'Set is expected to be used only on PHP CS Fixer project itself.', ); } if ($ruleSetDefinition instanceof DeprecatedRuleSetDefinitionInterface) { $alternatives = $ruleSetDefinition->getSuccessorsNames(); $tags[] = new DocumentationTag( DocumentationTagType::DEPRECATED, \sprintf('This rule set is DEPRECATED and will be removed in the next major version %d.0', Application::getMajorVersion() + 1), 0 !== \count($alternatives) ? \sprintf( 'You should use %s instead.', Utils::naturalLanguageJoinWithBackticks($alternatives), ) : 'No replacement available.', ); } if ($ruleSetDefinition->isRisky()) { $tags[] = new DocumentationTag( DocumentationTagType::RISKY, 'This rule set is RISKY', 'This set contains rules that are risky. Using it may lead to changes in your code\'s logic and behaviour. Use it with caution and review changes before incorporating them into your code base.', ); } // not possible for set to be DocumentationTagType::CONFIGURABLE if ($ruleSetDefinition instanceof AutomaticRuleSetDefinitionInterface) { $tags[] = new DocumentationTag( DocumentationTagType::AUTOMATIC, 'This rule set is AUTOMATIC', '⚡ '.strip_tags(AutomaticRuleSetDefinitionInterface::WARNING_MESSAGE_DECORATED), ); } return $tags; } /** * @return list<DocumentationTag> */ public static function analyseRule(FixerInterface $fixer): array { $tags = []; if ($fixer instanceof ExperimentalFixerInterface) { $tags[] = new DocumentationTag( DocumentationTagType::EXPERIMENTAL, 'This rule is EXPERIMENTAL', 'Rule is not covered with backward compatibility promise and may produce unstable or unexpected results, use it at your own risk. Rule\'s behaviour may be changed at any point, including rule\'s name; its options\' names, availability and allowed values; its default configuration. Rule may be even removed without prior notice. Feel free to provide feedback and help with determining final state of the rule.', ); } if ($fixer instanceof InternalFixerInterface) { $tags[] = new DocumentationTag( DocumentationTagType::INTERNAL, 'This rule is INTERNAL', 'Rule is expected to be used only on PHP CS Fixer project itself.', ); } if ($fixer instanceof DeprecatedFixerInterface) { $alternatives = $fixer->getSuccessorsNames(); $tags[] = new DocumentationTag( DocumentationTagType::DEPRECATED, \sprintf('This rule is DEPRECATED and will be removed in the next major version %d.0', Application::getMajorVersion() + 1), 0 !== \count($alternatives) ? \sprintf( 'You should use %s instead.', Utils::naturalLanguageJoinWithBackticks($alternatives), ) : 'No replacement available.', ); } if ($fixer->isRisky()) { $riskyDescription = $fixer->getDefinition()->getRiskyDescription(); $tags[] = new DocumentationTag( DocumentationTagType::RISKY, 'This rule is RISKY', // @TODO - FRS enable me // 'Using it may lead to changes in your code\'s logic and behaviour. Use it with caution and review changes before incorporating them into your code base.' // \n\n '' .(null !== $riskyDescription ? "{$riskyDescription}" : ''), ); } if ($fixer instanceof ConfigurableFixerInterface) { $options = array_map( static fn (FixerOptionInterface $option): string => '`'.$option->getName().'`', $fixer->getConfigurationDefinition()->getOptions(), ); $tags[] = new DocumentationTag( DocumentationTagType::CONFIGURABLE, 'This rule is CONFIGURABLE', \sprintf( 'You can configure this rule using the following option%s: %s.', 1 === \count($options) ? '' : 's', implode(', ', $options), ), ); } // not possible for set to be DocumentationTagType::AUTOMATIC return $tags; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/ConfigurationException/UnresolvableAutoRuleSetConfigurationException.php
src/ConfigurationException/UnresolvableAutoRuleSetConfigurationException.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\ConfigurationException; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class UnresolvableAutoRuleSetConfigurationException extends InvalidConfigurationException {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/ConfigurationException/InvalidFixerConfigurationException.php
src/ConfigurationException/InvalidFixerConfigurationException.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\ConfigurationException; use PhpCsFixer\Console\Command\FixCommandExitStatusCalculator; /** * Exception thrown by Fixers on misconfiguration. * * @internal * * @final Only internal extending this class is supported * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ class InvalidFixerConfigurationException extends InvalidConfigurationException { private string $fixerName; public function __construct(string $fixerName, string $message, ?\Throwable $previous = null) { parent::__construct( \sprintf('[%s] %s', $fixerName, $message), FixCommandExitStatusCalculator::EXIT_STATUS_FLAG_HAS_INVALID_FIXER_CONFIG, $previous, ); $this->fixerName = $fixerName; } public function getFixerName(): string { return $this->fixerName; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/ConfigurationException/RequiredFixerConfigurationException.php
src/ConfigurationException/RequiredFixerConfigurationException.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\ConfigurationException; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class RequiredFixerConfigurationException extends InvalidFixerConfigurationException {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/ConfigurationException/InvalidForEnvFixerConfigurationException.php
src/ConfigurationException/InvalidForEnvFixerConfigurationException.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\ConfigurationException; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class InvalidForEnvFixerConfigurationException extends InvalidFixerConfigurationException {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/ConfigurationException/InvalidConfigurationException.php
src/ConfigurationException/InvalidConfigurationException.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\ConfigurationException; use PhpCsFixer\Console\Command\FixCommandExitStatusCalculator; /** * Exceptions of this type are thrown on misconfiguration of the Fixer. * * @internal * * @final Only internal extending this class is supported * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ class InvalidConfigurationException extends \InvalidArgumentException { public function __construct(string $message, ?int $code = null, ?\Throwable $previous = null) { parent::__construct( $message, $code ?? FixCommandExitStatusCalculator::EXIT_STATUS_FLAG_HAS_INVALID_CONFIG, $previous, ); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Token.php
src/Tokenizer/Token.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer; use PhpCsFixer\Future; /** * Representation of single token. * As a token prototype you should understand a single element generated by token_get_all. * Also, this class exposes PHPStan types. (hint: string in those types shall ideally not be empty - yet we are not there yet). * * @phpstan-type _PhpTokenKind int|string * @phpstan-type _PhpTokenArray array{0: int, 1: string} * @phpstan-type _PhpTokenArrayPartial array{0: int, 1?: string} * @phpstan-type _PhpTokenPrototype _PhpTokenArray|string * @phpstan-type _PhpTokenPrototypePartial _PhpTokenArrayPartial|string * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @readonly * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class Token { /** * Content of token prototype. */ private string $content; /** * ID of token prototype, if available. */ private ?int $id; /** * If token prototype is an array. */ private bool $isArray; /** * @param _PhpTokenPrototype $token token prototype */ public function __construct($token) { if (\is_array($token)) { if (!\is_int($token[0])) { throw new \InvalidArgumentException(\sprintf( 'Id must be an int, got "%s".', get_debug_type($token[0]), )); } if (!\is_string($token[1])) { throw new \InvalidArgumentException(\sprintf( 'Content must be a string, got "%s".', get_debug_type($token[1]), )); } if ('' === $token[1]) { throw new \InvalidArgumentException('Cannot set empty content for id-based Token.'); } $this->isArray = true; $this->id = $token[0]; $this->content = $token[1]; } elseif (\is_string($token)) { $this->isArray = false; $this->id = null; $this->content = $token; } else { throw new \InvalidArgumentException(\sprintf('Cannot recognize input value as valid Token prototype, got "%s".', get_debug_type($token))); } } /** * @return non-empty-list<int> */ public static function getCastTokenKinds(): array { return [\T_ARRAY_CAST, \T_BOOL_CAST, \T_DOUBLE_CAST, \T_INT_CAST, \T_OBJECT_CAST, \T_STRING_CAST, \T_UNSET_CAST, FCT::T_VOID_CAST]; } /** * Get classy tokens kinds: T_ENUM, T_CLASS, T_INTERFACE and T_TRAIT. * * @return non-empty-list<int> */ public static function getClassyTokenKinds(): array { return [\T_CLASS, \T_TRAIT, \T_INTERFACE, FCT::T_ENUM]; } /** * Get object operator tokens kinds: T_OBJECT_OPERATOR and (if available) T_NULLSAFE_OBJECT_OPERATOR. * * @return non-empty-list<int> */ public static function getObjectOperatorKinds(): array { return [\T_OBJECT_OPERATOR, FCT::T_NULLSAFE_OBJECT_OPERATOR]; } /** * Check if token is equals to given one. * * If tokens are arrays, then only keys defined in parameter token are checked. * * @param _PhpTokenPrototypePartial|Token $other token or it's prototype * @param bool $caseSensitive perform a case sensitive comparison */ public function equals($other, bool $caseSensitive = true): bool { if ('&' === $other) { return '&' === $this->content && (null === $this->id || $this->isGivenKind([FCT::T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, FCT::T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG])); } if (null === $this->id && '&' === $this->content) { return $other instanceof self && '&' === $other->content && (null === $other->id || $other->isGivenKind([FCT::T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, FCT::T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG])); } if ($other instanceof self) { // Inlined getPrototype() on this very hot path. // We access the private properties of $other directly to save function call overhead. // This is only possible because $other is of the same class as `self`. if (!$other->isArray) { $otherPrototype = $other->content; } else { $otherPrototype = [ $other->id, $other->content, ]; } } else { $otherPrototype = $other; } if ($this->isArray !== \is_array($otherPrototype)) { return false; } if (!$this->isArray) { return $this->content === $otherPrototype; } if ($this->id !== $otherPrototype[0]) { return false; } if (isset($otherPrototype[1])) { if ($caseSensitive) { if ($this->content !== $otherPrototype[1]) { return false; } } elseif (0 !== strcasecmp($this->content, $otherPrototype[1])) { return false; } } // detect unknown keys unset($otherPrototype[0], $otherPrototype[1]); return [] === $otherPrototype; } /** * Check if token is equals to one of given. * * @param list<_PhpTokenPrototypePartial|Token> $others array of tokens or token prototypes * @param bool $caseSensitive perform a case sensitive comparison */ public function equalsAny(array $others, bool $caseSensitive = true): bool { foreach ($others as $other) { if ($this->equals($other, $caseSensitive)) { return true; } } return false; } /** * A helper method used to find out whether a certain input token has to be case-sensitively matched. * * @param array<int, bool>|bool $caseSensitive global case sensitiveness or an array of booleans, whose keys should match * the ones used in $sequence. If any is missing, the default case-sensitive * comparison is used * @param int $key the key of the token that has to be looked up * * @deprecated */ public static function isKeyCaseSensitive($caseSensitive, int $key): bool { Future::triggerDeprecation(new \InvalidArgumentException(\sprintf( 'Method "%s" is deprecated and will be removed in the next major version.', __METHOD__, ))); if (\is_array($caseSensitive)) { return $caseSensitive[$key] ?? true; } return $caseSensitive; } /** * @return array{int, non-empty-string}|string */ public function getPrototype() { if (!$this->isArray) { return $this->content; } \assert('' !== $this->content); return [ $this->id, $this->content, ]; } /** * Get token's content. * * It shall be used only for getting the content of token, not for checking it against excepted value. */ public function getContent(): string { return $this->content; } /** * Get token's id. * * It shall be used only for getting the internal id of token, not for checking it against excepted value. */ public function getId(): ?int { return $this->id; } /** * Get token's name. * * It shall be used only for getting the name of token, not for checking it against excepted value. * * @return null|non-empty-string token name */ public function getName(): ?string { if (null === $this->id) { return null; } return self::getNameForId($this->id); } /** * Get token's name. * * It shall be used only for getting the name of token, not for checking it against excepted value. * * @return null|non-empty-string token name */ public static function getNameForId(int $id): ?string { if (CT::has($id)) { return CT::getName($id); } $name = token_name($id); return 'UNKNOWN' === $name ? null : $name; } /** * Generate array containing all keywords that exists in PHP version in use. * * @return non-empty-list<int> */ public static function getKeywords(): array { static $keywords = null; if (null === $keywords) { $keywords = self::getTokenKindsForNames(['T_ABSTRACT', 'T_ARRAY', 'T_AS', 'T_BREAK', 'T_CALLABLE', 'T_CASE', 'T_CATCH', 'T_CLASS', 'T_CLONE', 'T_CONST', 'T_CONTINUE', 'T_DECLARE', 'T_DEFAULT', 'T_DO', 'T_ECHO', 'T_ELSE', 'T_ELSEIF', 'T_EMPTY', 'T_ENDDECLARE', 'T_ENDFOR', 'T_ENDFOREACH', 'T_ENDIF', 'T_ENDSWITCH', 'T_ENDWHILE', 'T_EVAL', 'T_EXIT', 'T_EXTENDS', 'T_FINAL', 'T_FINALLY', 'T_FN', 'T_FOR', 'T_FOREACH', 'T_FUNCTION', 'T_GLOBAL', 'T_GOTO', 'T_HALT_COMPILER', 'T_IF', 'T_IMPLEMENTS', 'T_INCLUDE', 'T_INCLUDE_ONCE', 'T_INSTANCEOF', 'T_INSTEADOF', 'T_INTERFACE', 'T_ISSET', 'T_LIST', 'T_LOGICAL_AND', 'T_LOGICAL_OR', 'T_LOGICAL_XOR', 'T_NAMESPACE', 'T_NEW', 'T_PRINT', 'T_PRIVATE', 'T_PROTECTED', 'T_PUBLIC', 'T_REQUIRE', 'T_REQUIRE_ONCE', 'T_RETURN', 'T_STATIC', 'T_SWITCH', 'T_THROW', 'T_TRAIT', 'T_TRY', 'T_UNSET', 'T_USE', 'T_VAR', 'T_WHILE', 'T_YIELD', 'T_YIELD_FROM', ]) + [ CT::T_ARRAY_TYPEHINT => CT::T_ARRAY_TYPEHINT, CT::T_CLASS_CONSTANT => CT::T_CLASS_CONSTANT, CT::T_CONST_IMPORT => CT::T_CONST_IMPORT, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC => CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_FUNCTION_IMPORT => CT::T_FUNCTION_IMPORT, CT::T_NAMESPACE_OPERATOR => CT::T_NAMESPACE_OPERATOR, CT::T_USE_LAMBDA => CT::T_USE_LAMBDA, CT::T_USE_TRAIT => CT::T_USE_TRAIT, FCT::T_ENUM => FCT::T_ENUM, FCT::T_MATCH => FCT::T_MATCH, FCT::T_PRIVATE_SET => FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET => FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET => FCT::T_PUBLIC_SET, FCT::T_READONLY => FCT::T_READONLY, ]; } return $keywords; } /** * Generate array containing all predefined constants that exists in PHP version in use. * * @return non-empty-array<int, int> * * @see https://php.net/manual/en/language.constants.predefined.php */ public static function getMagicConstants(): array { static $magicConstants = null; if (null === $magicConstants) { $magicConstants = self::getTokenKindsForNames(['T_CLASS_C', 'T_DIR', 'T_FILE', 'T_FUNC_C', 'T_LINE', 'T_METHOD_C', 'T_NS_C', 'T_TRAIT_C']); } return $magicConstants; } /** * Check if token prototype is an array. * * @return bool is array * * @phpstan-assert-if-true !=null $this->getId() * @phpstan-assert-if-true !='' $this->getContent() */ public function isArray(): bool { return $this->isArray; } /** * Check if token is one of type cast tokens. * * @phpstan-assert-if-true !='' $this->getContent() */ public function isCast(): bool { return $this->isGivenKind(self::getCastTokenKinds()); } /** * Check if token is one of classy tokens: T_CLASS, T_INTERFACE, T_TRAIT or T_ENUM. * * @phpstan-assert-if-true !='' $this->getContent() */ public function isClassy(): bool { return $this->isGivenKind(self::getClassyTokenKinds()); } /** * Check if token is one of comment tokens: T_COMMENT or T_DOC_COMMENT. * * @phpstan-assert-if-true !='' $this->getContent() */ public function isComment(): bool { return $this->isGivenKind([\T_COMMENT, \T_DOC_COMMENT]); } /** * Check if token is one of object operator tokens: T_OBJECT_OPERATOR or T_NULLSAFE_OBJECT_OPERATOR. * * @phpstan-assert-if-true !='' $this->getContent() */ public function isObjectOperator(): bool { return $this->isGivenKind(self::getObjectOperatorKinds()); } /** * Check if token is one of given kind. * * @param int|list<int> $possibleKind kind or array of kinds * * @phpstan-assert-if-true !=null $this->getId() * @phpstan-assert-if-true !='' $this->getContent() */ public function isGivenKind($possibleKind): bool { return $this->isArray && (\is_array($possibleKind) ? \in_array($this->id, $possibleKind, true) : $this->id === $possibleKind); } /** * Check if token is a keyword. * * @phpstan-assert-if-true !='' $this->getContent() */ public function isKeyword(): bool { $keywords = self::getKeywords(); return $this->isArray && isset($keywords[$this->id]); } /** * Check if token is a native PHP constant: true, false or null. * * @phpstan-assert-if-true !='' $this->getContent() */ public function isNativeConstant(): bool { return $this->isArray && \in_array(strtolower($this->content), ['true', 'false', 'null'], true); } /** * Returns if the token is of a Magic constants type. * * @phpstan-assert-if-true !='' $this->getContent() * * @see https://php.net/manual/en/language.constants.predefined.php */ public function isMagicConstant(): bool { $magicConstants = self::getMagicConstants(); return $this->isArray && isset($magicConstants[$this->id]); } /** * Check if token is whitespace. * * @param null|string $whitespaces whitespace characters, default is " \t\n\r\0\x0B" */ public function isWhitespace(?string $whitespaces = " \t\n\r\0\x0B"): bool { if (null === $whitespaces) { $whitespaces = " \t\n\r\0\x0B"; } if ($this->isArray && !$this->isGivenKind(\T_WHITESPACE)) { return false; } return '' === trim($this->content, $whitespaces); } /** * @return array{ * id: null|int, * name: null|non-empty-string, * content: string, * isArray: bool, * changed: bool, * } */ public function toArray(): array { return [ 'id' => $this->id, 'name' => $this->getName(), 'content' => $this->content, 'isArray' => $this->isArray, 'changed' => false, // @TODO v4: remove index ]; } /** * @return non-empty-string */ public function toJson(): string { try { return json_encode($this->toArray(), \JSON_THROW_ON_ERROR | \JSON_PRETTY_PRINT | \JSON_NUMERIC_CHECK); } catch (\JsonException $e) { return json_encode( [ 'errorDescription' => 'Cannot encode Tokens to JSON.', 'rawErrorMessage' => $e->getMessage(), ], \JSON_THROW_ON_ERROR | \JSON_PRETTY_PRINT | \JSON_NUMERIC_CHECK, ); } } /** * @param non-empty-list<string> $tokenNames * * @return non-empty-array<int, int> */ private static function getTokenKindsForNames(array $tokenNames): array { $keywords = []; foreach ($tokenNames as $keywordName) { $keyword = \constant($keywordName); $keywords[$keyword] = $keyword; } return $keywords; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/TokensAnalyzer.php
src/Tokenizer/TokensAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer; use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer; use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer; /** * Analyzer of Tokens collection. * * Its role is to provide the ability to analyse collection. * * @internal * * @phpstan-type _ClassyElementType 'case'|'const'|'method'|'property'|'promoted_property'|'trait_import' * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * @author Gregor Harlan <gharlan@web.de> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class TokensAnalyzer { /** * Tokens collection instance. */ private Tokens $tokens; /** * @readonly */ private GotoLabelAnalyzer $gotoLabelAnalyzer; public function __construct(Tokens $tokens) { $this->tokens = $tokens; $this->gotoLabelAnalyzer = new GotoLabelAnalyzer(); } /** * Get indices of methods and properties in classy code (classes, interfaces and traits). * * @return array<int, array{classIndex: int, token: Token, type: _ClassyElementType}> */ public function getClassyElements(): array { $elements = []; for ($index = 1, $count = \count($this->tokens) - 2; $index < $count; ++$index) { if ($this->tokens[$index]->isClassy()) { [$index, $newElements] = $this->findClassyElements($index, $index); $elements += $newElements; } } ksort($elements); return $elements; } /** * Get indices of modifiers of a classy code (classes, interfaces and traits). * * @return array{ * final: null|int, * abstract: null|int, * readonly: null|int * } */ public function getClassyModifiers(int $index): array { if (!$this->tokens[$index]->isClassy()) { throw new \InvalidArgumentException(\sprintf('Not an "classy" at given index %d.', $index)); } $modifiers = ['final' => null, 'abstract' => null, 'readonly' => null]; while (true) { $index = $this->tokens->getPrevMeaningfulToken($index); if ($this->tokens[$index]->isGivenKind(\T_FINAL)) { $modifiers['final'] = $index; } elseif ($this->tokens[$index]->isGivenKind(\T_ABSTRACT)) { $modifiers['abstract'] = $index; } elseif ($this->tokens[$index]->isGivenKind(FCT::T_READONLY)) { $modifiers['readonly'] = $index; } else { // no need to skip attributes as it is not possible on PHP8.2 break; } } return $modifiers; } /** * Get indices of namespace uses. * * @param bool $perNamespace Return namespace uses per namespace * * @return ($perNamespace is true ? array<int, non-empty-list<int>> : list<int>) */ public function getImportUseIndexes(bool $perNamespace = false): array { $tokens = $this->tokens; $uses = []; $namespaceIndex = 0; for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) { $token = $tokens[$index]; if ($token->isGivenKind(\T_NAMESPACE)) { $nextTokenIndex = $tokens->getNextTokenOfKind($index, [';', '{']); $nextToken = $tokens[$nextTokenIndex]; if ($nextToken->equals('{')) { $index = $nextTokenIndex; } if ($perNamespace) { ++$namespaceIndex; } continue; } if ($token->isGivenKind(\T_USE)) { $uses[$namespaceIndex][] = $index; } } if (!$perNamespace && isset($uses[$namespaceIndex])) { return $uses[$namespaceIndex]; } return $uses; } /** * Check if there is an array at given index. */ public function isArray(int $index): bool { return $this->tokens[$index]->isGivenKind([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]); } /** * Check if the array at index is multiline. * * This only checks the root-level of the array. */ public function isArrayMultiLine(int $index): bool { if (!$this->isArray($index)) { throw new \InvalidArgumentException(\sprintf('Not an array at given index %d.', $index)); } $tokens = $this->tokens; // Skip only when it's an array, for short arrays we need the brace for correct // level counting if ($tokens[$index]->isGivenKind(\T_ARRAY)) { $index = $tokens->getNextMeaningfulToken($index); } return $this->isBlockMultiline($tokens, $index); } public function isBlockMultiline(Tokens $tokens, int $index): bool { $blockType = Tokens::detectBlockType($tokens[$index]); if (null === $blockType || !$blockType['isStart']) { throw new \InvalidArgumentException(\sprintf('Not an block start at given index %d.', $index)); } $endIndex = $tokens->findBlockEnd($blockType['type'], $index); for (++$index; $index < $endIndex; ++$index) { $token = $tokens[$index]; $blockType = Tokens::detectBlockType($token); if (null !== $blockType && $blockType['isStart']) { $index = $tokens->findBlockEnd($blockType['type'], $index); continue; } if ( $token->isWhitespace() && !$tokens[$index - 1]->isGivenKind(\T_END_HEREDOC) && str_contains($token->getContent(), "\n") ) { return true; } } return false; } /** * @param int $index Index of the T_FUNCTION token * * @return array{visibility: null|T_PRIVATE|T_PROTECTED|T_PUBLIC, static: bool, abstract: bool, final: bool} */ public function getMethodAttributes(int $index): array { if (!$this->tokens[$index]->isGivenKind(\T_FUNCTION)) { throw new \LogicException(\sprintf('No T_FUNCTION at given index %d, got "%s".', $index, $this->tokens[$index]->getName())); } $attributes = [ 'visibility' => null, 'static' => false, 'abstract' => false, 'final' => false, ]; for ($i = $index; $i >= 0; --$i) { $i = $this->tokens->getPrevMeaningfulToken($i); $token = $this->tokens[$i]; if ($token->isGivenKind(\T_STATIC)) { $attributes['static'] = true; continue; } if ($token->isGivenKind(\T_FINAL)) { $attributes['final'] = true; continue; } if ($token->isGivenKind(\T_ABSTRACT)) { $attributes['abstract'] = true; continue; } // visibility if ($token->isGivenKind(\T_PRIVATE)) { $attributes['visibility'] = \T_PRIVATE; continue; } if ($token->isGivenKind(\T_PROTECTED)) { $attributes['visibility'] = \T_PROTECTED; continue; } if ($token->isGivenKind(\T_PUBLIC)) { $attributes['visibility'] = \T_PUBLIC; continue; } // found a meaningful token that is not part of // the function signature; stop looking break; } return $attributes; } /** * Check if there is an anonymous class under given index. */ public function isAnonymousClass(int $index): bool { if (!$this->tokens[$index]->isClassy()) { throw new \LogicException(\sprintf('No classy token at given index %d.', $index)); } if (!$this->tokens[$index]->isGivenKind(\T_CLASS)) { return false; } $index = $this->tokens->getPrevMeaningfulToken($index); if ($this->tokens[$index]->isGivenKind(FCT::T_READONLY)) { $index = $this->tokens->getPrevMeaningfulToken($index); } while ($this->tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { $index = $this->tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); $index = $this->tokens->getPrevMeaningfulToken($index); } return $this->tokens[$index]->isGivenKind(\T_NEW); } /** * Check if the function under given index is a lambda. */ public function isLambda(int $index): bool { if (!$this->tokens[$index]->isGivenKind([\T_FUNCTION, \T_FN])) { throw new \LogicException(\sprintf('No T_FUNCTION or T_FN at given index %d, got "%s".', $index, $this->tokens[$index]->getName())); } $startParenthesisIndex = $this->tokens->getNextMeaningfulToken($index); $startParenthesisToken = $this->tokens[$startParenthesisIndex]; // skip & for `function & () {}` syntax if ($startParenthesisToken->isGivenKind(CT::T_RETURN_REF)) { $startParenthesisIndex = $this->tokens->getNextMeaningfulToken($startParenthesisIndex); $startParenthesisToken = $this->tokens[$startParenthesisIndex]; } return $startParenthesisToken->equals('('); } public function getLastTokenIndexOfArrowFunction(int $index): int { if (!$this->tokens[$index]->isGivenKind(\T_FN)) { throw new \InvalidArgumentException(\sprintf('Not an "arrow function" at given index %d.', $index)); } $stopTokens = [')', ']', ',', ';', [\T_CLOSE_TAG]]; $index = $this->tokens->getNextTokenOfKind($index, [[\T_DOUBLE_ARROW]]); while (true) { $index = $this->tokens->getNextMeaningfulToken($index); if ($this->tokens[$index]->equalsAny($stopTokens)) { break; } $blockType = Tokens::detectBlockType($this->tokens[$index]); if (null === $blockType) { continue; } if ($blockType['isStart']) { $index = $this->tokens->findBlockEnd($blockType['type'], $index); continue; } break; } return $this->tokens->getPrevMeaningfulToken($index); } /** * Check if the T_STRING under given index is a constant invocation. */ public function isConstantInvocation(int $index): bool { if (!$this->tokens[$index]->isGivenKind(\T_STRING)) { throw new \LogicException(\sprintf('No T_STRING at given index %d, got "%s".', $index, $this->tokens[$index]->getName())); } $nextIndex = $this->tokens->getNextMeaningfulToken($index); if ( $this->tokens[$nextIndex]->equalsAny(['(', '{']) || $this->tokens[$nextIndex]->isGivenKind([\T_DOUBLE_COLON, \T_ELLIPSIS, \T_NS_SEPARATOR, CT::T_RETURN_REF, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, \T_VARIABLE]) ) { return false; } // handle foreach( FOO as $_ ) {} if ($this->tokens[$nextIndex]->isGivenKind(\T_AS)) { $prevIndex = $this->tokens->getPrevMeaningfulToken($index); if (!$this->tokens[$prevIndex]->equals('(')) { return false; } } $prevIndex = $this->tokens->getPrevMeaningfulToken($index); if ($this->tokens[$prevIndex]->isGivenKind(Token::getClassyTokenKinds())) { return false; } if ($this->tokens[$prevIndex]->isGivenKind([\T_AS, \T_CONST, \T_DOUBLE_COLON, \T_FUNCTION, \T_GOTO, CT::T_GROUP_IMPORT_BRACE_OPEN, CT::T_TYPE_COLON, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION]) || $this->tokens[$prevIndex]->isObjectOperator()) { return false; } if ( $this->tokens[$prevIndex]->isGivenKind(\T_CASE) && $this->tokens->isAllTokenKindsFound([FCT::T_ENUM]) ) { $enumSwitchIndex = $this->tokens->getPrevTokenOfKind($index, [[\T_SWITCH], [\T_ENUM]]); if (!$this->tokens[$enumSwitchIndex]->isGivenKind(\T_SWITCH)) { return false; } } while ($this->tokens[$prevIndex]->isGivenKind([CT::T_NAMESPACE_OPERATOR, \T_NS_SEPARATOR, \T_STRING, CT::T_ARRAY_TYPEHINT])) { $prevIndex = $this->tokens->getPrevMeaningfulToken($prevIndex); } if ($this->tokens[$prevIndex]->isGivenKind([CT::T_CONST_IMPORT, \T_EXTENDS, CT::T_FUNCTION_IMPORT, \T_IMPLEMENTS, \T_INSTANCEOF, \T_INSTEADOF, \T_NAMESPACE, \T_NEW, CT::T_NULLABLE_TYPE, CT::T_TYPE_COLON, \T_USE, CT::T_USE_TRAIT, CT::T_TYPE_INTERSECTION, CT::T_TYPE_ALTERNATION, \T_CONST, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE])) { return false; } // `FOO & $bar` could be: // - function reference parameter: function baz(Foo & $bar) {} // - bit operator: $x = FOO & $bar; if ($this->tokens[$nextIndex]->equals('&') && $this->tokens[$this->tokens->getNextMeaningfulToken($nextIndex)]->isGivenKind(\T_VARIABLE)) { $checkIndex = $this->tokens->getPrevTokenOfKind($prevIndex, [';', '{', '}', [\T_FUNCTION], [\T_OPEN_TAG], [\T_OPEN_TAG_WITH_ECHO]]); if ($this->tokens[$checkIndex]->isGivenKind(\T_FUNCTION)) { return false; } } // check for `extends`/`implements`/`use` list if ($this->tokens[$prevIndex]->equals(',')) { $checkIndex = $prevIndex; while ($this->tokens[$checkIndex]->equalsAny([',', [\T_AS], [CT::T_NAMESPACE_OPERATOR], [\T_NS_SEPARATOR], [\T_STRING]])) { $checkIndex = $this->tokens->getPrevMeaningfulToken($checkIndex); } if ($this->tokens[$checkIndex]->isGivenKind([\T_EXTENDS, CT::T_GROUP_IMPORT_BRACE_OPEN, \T_IMPLEMENTS, \T_USE, CT::T_USE_TRAIT])) { return false; } } // check for array in double quoted string: `"..$foo[bar].."` if ($this->tokens[$prevIndex]->equals('[') && $this->tokens[$nextIndex]->equals(']')) { $checkToken = $this->tokens[$this->tokens->getNextMeaningfulToken($nextIndex)]; if ($checkToken->equals('"') || $checkToken->isGivenKind([\T_CURLY_OPEN, \T_DOLLAR_OPEN_CURLY_BRACES, \T_ENCAPSED_AND_WHITESPACE, \T_VARIABLE])) { return false; } } // check for attribute: `#[Foo]` if (AttributeAnalyzer::isAttribute($this->tokens, $index)) { return false; } // check for goto label if ($this->tokens[$nextIndex]->equals(':')) { if ($this->gotoLabelAnalyzer->belongsToGoToLabel($this->tokens, $nextIndex)) { return false; } } // check for non-capturing catches while ($this->tokens[$prevIndex]->isGivenKind([CT::T_NAMESPACE_OPERATOR, \T_NS_SEPARATOR, \T_STRING, CT::T_TYPE_ALTERNATION])) { $prevIndex = $this->tokens->getPrevMeaningfulToken($prevIndex); } if ($this->tokens[$prevIndex]->equals('(')) { $prevPrevIndex = $this->tokens->getPrevMeaningfulToken($prevIndex); if ($this->tokens[$prevPrevIndex]->isGivenKind(\T_CATCH)) { return false; } } return true; } /** * Checks if there is a unary successor operator under given index. */ public function isUnarySuccessorOperator(int $index): bool { $tokens = $this->tokens; $token = $tokens[$index]; if (!$token->isGivenKind([\T_INC, \T_DEC])) { return false; } $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; return $prevToken->equalsAny([ ']', [\T_STRING], [\T_VARIABLE], [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], [CT::T_DYNAMIC_PROP_BRACE_CLOSE], [CT::T_DYNAMIC_VAR_BRACE_CLOSE], ]); } /** * Checks if there is a unary predecessor operator under given index. */ public function isUnaryPredecessorOperator(int $index): bool { $tokens = $this->tokens; $token = $tokens[$index]; // potential unary successor operator if ($token->isGivenKind([\T_INC, \T_DEC])) { return !$this->isUnarySuccessorOperator($index); } // always unary predecessor operator if ($token->equalsAny(['!', '~', '@', [\T_ELLIPSIS]])) { return true; } // potential binary operator if (!$token->equalsAny(['+', '-', '&', [CT::T_RETURN_REF]])) { return false; } $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; if (!$prevToken->equalsAny([ ']', '}', ')', '"', '`', [CT::T_ARRAY_SQUARE_BRACE_CLOSE], [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], [CT::T_DYNAMIC_PROP_BRACE_CLOSE], [CT::T_DYNAMIC_VAR_BRACE_CLOSE], [\T_CLASS_C], [\T_CONSTANT_ENCAPSED_STRING], [\T_DEC], [\T_DIR], [\T_DNUMBER], [\T_FILE], [\T_FUNC_C], [\T_INC], [\T_LINE], [\T_LNUMBER], [\T_METHOD_C], [\T_NS_C], [\T_STRING], [\T_TRAIT_C], [\T_VARIABLE], ])) { return true; } if (!$token->equals('&') || !$prevToken->isGivenKind(\T_STRING)) { return false; } $prevToken = $tokens[$tokens->getPrevTokenOfKind($index, [ ';', '{', '}', [\T_DOUBLE_ARROW], [\T_FN], [\T_FUNCTION], [\T_OPEN_TAG], [\T_OPEN_TAG_WITH_ECHO], ])]; return $prevToken->isGivenKind([\T_FN, \T_FUNCTION]); } /** * Checks if there is a binary operator under given index. */ public function isBinaryOperator(int $index): bool { $tokens = $this->tokens; $token = $tokens[$index]; if ($token->isGivenKind([\T_INLINE_HTML, \T_ENCAPSED_AND_WHITESPACE, CT::T_TYPE_INTERSECTION])) { return false; } // potential unary predecessor operator if (\in_array($token->getContent(), ['+', '-', '&'], true)) { return !$this->isUnaryPredecessorOperator($index); } if ($token->isArray()) { return \in_array($token->getId(), [ \T_AND_EQUAL, // &= \T_BOOLEAN_AND, // && \T_BOOLEAN_OR, // || \T_CONCAT_EQUAL, // .= \T_DIV_EQUAL, // /= \T_DOUBLE_ARROW, // => \T_IS_EQUAL, // == \T_IS_GREATER_OR_EQUAL, // >= \T_IS_IDENTICAL, // === \T_IS_NOT_EQUAL, // !=, <> \T_IS_NOT_IDENTICAL, // !== \T_IS_SMALLER_OR_EQUAL, // <= \T_LOGICAL_AND, // and \T_LOGICAL_OR, // or \T_LOGICAL_XOR, // xor \T_MINUS_EQUAL, // -= \T_MOD_EQUAL, // %= \T_MUL_EQUAL, // *= \T_OR_EQUAL, // |= \T_PLUS_EQUAL, // += \T_POW, // ** \T_POW_EQUAL, // **= \T_SL, // << \T_SL_EQUAL, // <<= \T_SR, // >> \T_SR_EQUAL, // >>= \T_XOR_EQUAL, // ^= \T_SPACESHIP, // <=> \T_COALESCE, // ?? \T_COALESCE_EQUAL, // ??= ], true); } if (\in_array($token->getContent(), ['=', '*', '/', '%', '<', '>', '|', '^', '.'], true)) { return true; } return false; } /** * Check if `T_WHILE` token at given index is `do { ... } while ();` syntax * and not `while () { ...}`. */ public function isWhilePartOfDoWhile(int $index): bool { $tokens = $this->tokens; $token = $tokens[$index]; if (!$token->isGivenKind(\T_WHILE)) { throw new \LogicException(\sprintf('No T_WHILE at given index %d, got "%s".', $index, $token->getName())); } $endIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$endIndex]->equals('}')) { return false; } $startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $endIndex); $beforeStartIndex = $tokens->getPrevMeaningfulToken($startIndex); return $tokens[$beforeStartIndex]->isGivenKind(\T_DO); } /** * @throws \LogicException when provided index does not point to token containing T_CASE */ public function isEnumCase(int $caseIndex): bool { $tokens = $this->tokens; $token = $tokens[$caseIndex]; if (!$token->isGivenKind(\T_CASE)) { throw new \LogicException(\sprintf( 'No T_CASE given at index %d, got %s instead.', $caseIndex, $token->getName() ?? $token->getContent(), )); } if (!$tokens->isTokenKindFound(FCT::T_ENUM)) { return false; } $prevIndex = $tokens->getPrevTokenOfKind($caseIndex, [[\T_ENUM], [\T_SWITCH]]); return null !== $prevIndex && $tokens[$prevIndex]->isGivenKind(\T_ENUM); } public function isSuperGlobal(int $index): bool { $token = $this->tokens[$index]; if (!$token->isGivenKind(\T_VARIABLE)) { return false; } return \in_array(strtoupper($token->getContent()), [ '$_COOKIE', '$_ENV', '$_FILES', '$_GET', '$_POST', '$_REQUEST', '$_SERVER', '$_SESSION', '$GLOBALS', ], true); } /** * Find classy elements. * * Searches in tokens from the classy (start) index till the end (index) of the classy. * Returns an array; first value is the index until the method has analysed (int), second the found classy elements (array). * * @param int $classIndex classy index * * @return array{int, array<int, array{classIndex: int, token: Token, type: _ClassyElementType}>} */ private function findClassyElements(int $classIndex, int $index): array { $elements = []; $curlyBracesLevel = 0; $bracesLevel = 0; ++$index; // skip the classy index itself for ($count = \count($this->tokens); $index < $count; ++$index) { $token = $this->tokens[$index]; if ($token->isGivenKind(\T_ENCAPSED_AND_WHITESPACE)) { continue; } if ($token->isGivenKind(\T_CLASS)) { // anonymous class in class // check for nested anonymous classes inside the new call of an anonymous class, // for example `new class(function (){new class(function (){new class(function (){}){};}){};}){};` etc. // if class(XYZ) {} skip till `(` as XYZ might contain functions etc. $nestedClassIndex = $index; $index = $this->tokens->getNextMeaningfulToken($index); if ($this->tokens[$index]->equals('(')) { ++$index; // move after `(` for ($nestedBracesLevel = 1; $index < $count; ++$index) { $token = $this->tokens[$index]; if ($token->equals('(')) { ++$nestedBracesLevel; continue; } if ($token->equals(')')) { --$nestedBracesLevel; if (0 === $nestedBracesLevel) { [$index, $newElements] = $this->findClassyElements($nestedClassIndex, $index); $elements += $newElements; break; } continue; } if ($token->isGivenKind(\T_CLASS)) { // anonymous class in class [$index, $newElements] = $this->findClassyElements($index, $index); $elements += $newElements; } } } else { [$index, $newElements] = $this->findClassyElements($nestedClassIndex, $nestedClassIndex); $elements += $newElements; } continue; } if ($token->equals('(')) { ++$bracesLevel; continue; } if ($token->equals(')')) { --$bracesLevel; continue; } if ($token->equals('{')) { ++$curlyBracesLevel; continue; } if ($token->equals('}')) { --$curlyBracesLevel; if (0 === $curlyBracesLevel) { break; } continue; } if (1 !== $curlyBracesLevel || !$token->isArray()) { continue; } if (0 === $bracesLevel && $token->isGivenKind(\T_VARIABLE)) { $elements[$index] = [ 'classIndex' => $classIndex, 'token' => $token, 'type' => 'property', ]; continue; } if ($token->isGivenKind(CT::T_PROPERTY_HOOK_BRACE_OPEN)) { $index = $this->tokens->getNextTokenOfKind($index, [[CT::T_PROPERTY_HOOK_BRACE_CLOSE]]); continue; } if ($token->isGivenKind(\T_FUNCTION)) { $elements[$index] = [ 'classIndex' => $classIndex, 'token' => $token, 'type' => 'method', ]; $functionNameIndex = $this->tokens->getNextMeaningfulToken($index); if ('__construct' === $this->tokens[$functionNameIndex]->getContent()) { $openParenthesis = $this->tokens->getNextMeaningfulToken($functionNameIndex); $closeParenthesis = $this->tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis); foreach ($this->tokens->findGivenKind([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, FCT::T_READONLY, \T_FINAL], $openParenthesis, $closeParenthesis) as $kindElements) { foreach (array_keys($kindElements) as $promotedPropertyModifierIndex) { /** @var int $promotedPropertyVariableIndex */ $promotedPropertyVariableIndex = $this->tokens->getNextTokenOfKind($promotedPropertyModifierIndex, [[\T_VARIABLE]]); $elements[$promotedPropertyVariableIndex] = [ 'classIndex' => $classIndex, 'token' => $this->tokens[$promotedPropertyVariableIndex], 'type' => 'promoted_property', ]; } } } } elseif ($token->isGivenKind(\T_CONST)) { $elements[$index] = [ 'classIndex' => $classIndex, 'token' => $token, 'type' => 'const', ]; } elseif ($token->isGivenKind(CT::T_USE_TRAIT)) { $elements[$index] = [ 'classIndex' => $classIndex, 'token' => $token, 'type' => 'trait_import', ]; } elseif ($token->isGivenKind(\T_CASE)) { $elements[$index] = [ 'classIndex' => $classIndex, 'token' => $token, 'type' => 'case', ]; } } return [$index, $elements]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Transformers.php
src/Tokenizer/Transformers.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer; use Symfony\Component\Finder\Finder; /** * Collection of Transformer classes. * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class Transformers { /** * The registered transformers. * * @var list<TransformerInterface> */ private array $items = []; /** * Register built in Transformers. */ private function __construct() { $this->registerBuiltInTransformers(); usort($this->items, static fn (TransformerInterface $a, TransformerInterface $b): int => $b->getPriority() <=> $a->getPriority()); } public static function createSingleton(): self { static $instance = null; if (!$instance) { $instance = new self(); } return $instance; } /** * Transform given Tokens collection through all Transformer classes. * * @param Tokens $tokens Tokens collection */ public function transform(Tokens $tokens): void { foreach ($this->items as $transformer) { foreach ($tokens as $index => $token) { $transformer->process($tokens, $token, $index); } } } /** * @param TransformerInterface $transformer Transformer */ private function registerTransformer(TransformerInterface $transformer): void { if (\PHP_VERSION_ID >= $transformer->getRequiredPhpVersionId()) { $this->items[] = $transformer; } } private function registerBuiltInTransformers(): void { static $registered = false; if ($registered) { return; } $registered = true; foreach ($this->findBuiltInTransformers() as $transformer) { $this->registerTransformer($transformer); } } /** * @return \Generator<TransformerInterface> */ private function findBuiltInTransformers(): iterable { foreach (Finder::create()->files()->in(__DIR__.'/Transformer') as $file) { $relativeNamespace = $file->getRelativePath(); $class = __NAMESPACE__.'\Transformer\\'.('' !== $relativeNamespace ? $relativeNamespace.'\\' : '').$file->getBasename('.php'); $instance = new $class(); \assert($instance instanceof TransformerInterface); yield $instance; } } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/FCT.php
src/Tokenizer/FCT.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer; /** * Forward Compatibility Tokens. * * Class containing tokens that are not present in the lowest supported PHP version, * so the code can always use the class constant, instead of checking if the constant is defined * * @TODO PHP 8.0+, when mentioned PHP version is required, remove the related consts * @TODO PHP 8.1+, when mentioned PHP version is required, remove the related consts * @TODO PHP 8.4+, when mentioned PHP version is required, remove the related consts * @TODO PHP 8.5+, when mentioned PHP version is required, remove the related consts * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class FCT { // PHP 8.0+ public const T_ATTRIBUTE = \PHP_VERSION_ID >= 8_00_00 ? \T_ATTRIBUTE : -801; public const T_MATCH = \PHP_VERSION_ID >= 8_00_00 ? \T_MATCH : -802; public const T_NULLSAFE_OBJECT_OPERATOR = \PHP_VERSION_ID >= 8_00_00 ? \T_NULLSAFE_OBJECT_OPERATOR : -803; public const T_NAME_FULLY_QUALIFIED = \PHP_VERSION_ID >= 8_00_00 ? \T_NAME_FULLY_QUALIFIED : -804; public const T_NAME_QUALIFIED = \PHP_VERSION_ID >= 8_00_00 ? \T_NAME_QUALIFIED : -805; public const T_NAME_RELATIVE = \PHP_VERSION_ID >= 8_00_00 ? \T_NAME_RELATIVE : -806; // PHP 8.1+ public const T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG = \PHP_VERSION_ID >= 8_01_00 ? \T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG : -811; public const T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG = \PHP_VERSION_ID >= 8_01_00 ? \T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG : -812; public const T_ENUM = \PHP_VERSION_ID >= 8_01_00 ? \T_ENUM : -813; public const T_READONLY = \PHP_VERSION_ID >= 8_01_00 ? \T_READONLY : -814; // PHP 8.4+ public const T_PRIVATE_SET = \PHP_VERSION_ID >= 8_04_00 ? \T_PRIVATE_SET : -841; public const T_PROTECTED_SET = \PHP_VERSION_ID >= 8_04_00 ? \T_PROTECTED_SET : -842; public const T_PUBLIC_SET = \PHP_VERSION_ID >= 8_04_00 ? \T_PUBLIC_SET : -843; public const T_PROPERTY_C = \PHP_VERSION_ID >= 8_04_00 ? \T_PROPERTY_C : -844; // PHP 8.5+ public const T_PIPE = \PHP_VERSION_ID >= 8_05_00 ? \T_PIPE : -851; public const T_VOID_CAST = \PHP_VERSION_ID >= 8_05_00 ? \T_VOID_CAST : -852; }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/AbstractTransformer.php
src/Tokenizer/AbstractTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer; use PhpCsFixer\Utils; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ abstract class AbstractTransformer implements TransformerInterface { public function getName(): string { $nameParts = explode('\\', static::class); $name = substr(end($nameParts), 0, -\strlen('Transformer')); return Utils::camelCaseToUnderscore($name); } public function getPriority(): int { return 0; } abstract public function getCustomTokens(): 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/Tokenizer/CT.php
src/Tokenizer/CT.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class CT { public const T_ARRAY_INDEX_CURLY_BRACE_CLOSE = 10_001; public const T_ARRAY_INDEX_CURLY_BRACE_OPEN = 10_002; public const T_ARRAY_SQUARE_BRACE_CLOSE = 10_003; public const T_ARRAY_SQUARE_BRACE_OPEN = 10_004; public const T_ARRAY_TYPEHINT = 10_005; public const T_BRACE_CLASS_INSTANTIATION_CLOSE = 10_006; public const T_BRACE_CLASS_INSTANTIATION_OPEN = 10_007; public const T_CLASS_CONSTANT = 10_008; public const T_CONST_IMPORT = 10_009; public const T_CURLY_CLOSE = 10_010; public const T_DESTRUCTURING_SQUARE_BRACE_CLOSE = 10_011; public const T_DESTRUCTURING_SQUARE_BRACE_OPEN = 10_012; public const T_DOLLAR_CLOSE_CURLY_BRACES = 10_013; public const T_DYNAMIC_PROP_BRACE_CLOSE = 10_014; public const T_DYNAMIC_PROP_BRACE_OPEN = 10_015; public const T_DYNAMIC_VAR_BRACE_CLOSE = 10_016; public const T_DYNAMIC_VAR_BRACE_OPEN = 10_017; public const T_FUNCTION_IMPORT = 10_018; public const T_GROUP_IMPORT_BRACE_CLOSE = 10_019; public const T_GROUP_IMPORT_BRACE_OPEN = 10_020; public const T_NAMESPACE_OPERATOR = 10_021; public const T_NULLABLE_TYPE = 10_022; public const T_RETURN_REF = 10_023; public const T_TYPE_ALTERNATION = 10_024; public const T_TYPE_COLON = 10_025; public const T_USE_LAMBDA = 10_026; public const T_USE_TRAIT = 10_027; public const T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC = 10_028; public const T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED = 10_029; public const T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE = 10_030; public const T_ATTRIBUTE_CLOSE = 10_031; public const T_NAMED_ARGUMENT_NAME = 10_032; public const T_NAMED_ARGUMENT_COLON = 10_033; public const T_FIRST_CLASS_CALLABLE = 10_034; public const T_TYPE_INTERSECTION = 10_035; public const T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN = 10_036; public const T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE = 10_037; public const T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_OPEN = 10_038; public const T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_CLOSE = 10_039; public const T_PROPERTY_HOOK_BRACE_OPEN = 10_040; public const T_PROPERTY_HOOK_BRACE_CLOSE = 10_041; private function __construct() {} /** * Get name for custom token. * * @param int $value custom token value * * @return non-empty-string */ public static function getName(int $value): string { if (!self::has($value)) { throw new \InvalidArgumentException(\sprintf('No custom token was found for "%s".', $value)); } $tokens = self::getMapById(); \assert(isset($tokens[$value])); return 'CT::'.$tokens[$value]; } /** * Check if given custom token exists. * * @param int $value custom token value */ public static function has(int $value): bool { $tokens = self::getMapById(); return isset($tokens[$value]); } /** * @return array<self::T_*, non-empty-string> */ private static function getMapById(): array { static $constants; if (null === $constants) { $reflection = new \ReflectionClass(self::class); $constants = array_flip($reflection->getConstants()); } return $constants; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Tokens.php
src/Tokenizer/Tokens.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer; use PhpCsFixer\Console\Application; use PhpCsFixer\Future; use PhpCsFixer\Hasher; use PhpCsFixer\Preg; use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer; /** * Collection of code tokens. * * Its role is to provide the ability to manage collection and navigate through it. * * As a token prototype you should understand a single element generated by token_get_all. * * @extends \SplFixedArray<Token> * * `SplFixedArray` uses `T|null` in return types because value can be null if an offset is unset or if the size does not match the number of elements. * But our class takes care of it and always ensures correct size and indexes, so that these methods never return `null` instead of `Token`. * * @method Token offsetGet($offset) * @method \Traversable<int, Token> getIterator() * @method array<int, Token> toArray() * * @phpstan-import-type _PhpTokenKind from Token * @phpstan-import-type _PhpTokenArray from Token * @phpstan-import-type _PhpTokenArrayPartial from Token * @phpstan-import-type _PhpTokenPrototype from Token * @phpstan-import-type _PhpTokenPrototypePartial from Token * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @final * * @TODO 4.0: mark as final * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ class Tokens extends \SplFixedArray { public const BLOCK_TYPE_PARENTHESIS_BRACE = 1; public const BLOCK_TYPE_CURLY_BRACE = 2; public const BLOCK_TYPE_INDEX_SQUARE_BRACE = 3; public const BLOCK_TYPE_ARRAY_SQUARE_BRACE = 4; public const BLOCK_TYPE_DYNAMIC_PROP_BRACE = 5; public const BLOCK_TYPE_DYNAMIC_VAR_BRACE = 6; public const BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE = 7; public const BLOCK_TYPE_GROUP_IMPORT_BRACE = 8; public const BLOCK_TYPE_DESTRUCTURING_SQUARE_BRACE = 9; public const BLOCK_TYPE_BRACE_CLASS_INSTANTIATION = 10; public const BLOCK_TYPE_ATTRIBUTE = 11; public const BLOCK_TYPE_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS = 12; public const BLOCK_TYPE_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE = 13; public const BLOCK_TYPE_COMPLEX_STRING_VARIABLE = 14; public const BLOCK_TYPE_PROPERTY_HOOK = 15; /** * Static class cache. * * @var array<non-empty-string, self> */ private static array $cache = []; /** * Cache of block starts. Any change in collection will invalidate it. * * @var array<int, int> */ private array $blockStartCache = []; /** * Cache of block ends. Any change in collection will invalidate it. * * @var array<int, int> */ private array $blockEndCache = []; /** * An hash of the code string. * * @var ?non-empty-string */ private ?string $codeHash = null; /** * An hash of the collection items. * * @var ?non-empty-string */ private ?string $collectionHash = null; /** * Flag is collection was changed. * * It doesn't know about change of collection's items. To check it run `isChanged` method. */ private bool $changed = false; /** * Set of found token kinds. * * When the token kind is present in this set it means that given token kind * was ever seen inside the collection (but may not be part of it any longer). * The key is token kind and the value is the number of occurrences. * * @var array<_PhpTokenKind, int<0, max>> */ private array $foundTokenKinds = []; /** * @var null|list<NamespaceAnalysis> */ private ?array $namespaceDeclarations = null; /** * Clone tokens collection. */ public function __clone() { foreach ($this as $key => $val) { $this[$key] = clone $val; } } /** * Clear cache - one position or all of them. * * @param null|non-empty-string $key position to clear, when null clear all */ public static function clearCache(?string $key = null): void { if (null === $key) { self::$cache = []; return; } unset(self::$cache[$key]); } /** * Detect type of block. * * @return null|array{type: self::BLOCK_TYPE_*, isStart: bool} */ public static function detectBlockType(Token $token): ?array { static $blockEdgeKinds = null; if (null === $blockEdgeKinds) { $blockEdgeKinds = []; foreach (self::getBlockEdgeDefinitions() as $type => $definition) { $blockEdgeKinds[ \is_string($definition['start']) ? $definition['start'] : $definition['start'][0] ] = ['type' => $type, 'isStart' => true]; $blockEdgeKinds[ \is_string($definition['end']) ? $definition['end'] : $definition['end'][0] ] = ['type' => $type, 'isStart' => false]; } } // inlined extractTokenKind() call on the hot path $tokenKind = $token->isArray() ? $token->getId() : $token->getContent(); return $blockEdgeKinds[$tokenKind] ?? null; } /** * Create token collection from array. * * @param array<int, Token> $array the array to import * @param ?bool $saveIndices save the numeric indices used in the original array, default is yes */ public static function fromArray($array, $saveIndices = null): self { $tokens = new self(\count($array)); if (false !== $saveIndices && !array_is_list($array)) { Future::triggerDeprecation(new \InvalidArgumentException(\sprintf( 'Parameter "array" should be a list. This will be enforced in version %d.0.', Application::getMajorVersion() + 1, ))); foreach ($array as $key => $val) { $tokens[$key] = $val; } } else { $index = 0; foreach ($array as $val) { $tokens[$index++] = $val; } } $tokens->clearChanged(); $tokens->generateCode(); // ensure code hash is calculated, so it's registered in cache return $tokens; } /** * Create token collection directly from code. * * @param string $code PHP code */ public static function fromCode(string $code): self { $codeHash = self::calculateHash($code); if (self::hasCache($codeHash)) { $tokens = self::getCache($codeHash); if ($codeHash === $tokens->codeHash) { $tokens->clearEmptyTokens(); $tokens->clearChanged(); return $tokens; } } $tokens = new self(); $tokens->setCode($code); $tokens->clearChanged(); return $tokens; } /** * @return array<self::BLOCK_TYPE_*, array{start: _PhpTokenPrototype, end: _PhpTokenPrototype}> */ public static function getBlockEdgeDefinitions(): array { return [ self::BLOCK_TYPE_CURLY_BRACE => [ 'start' => '{', 'end' => '}', ], self::BLOCK_TYPE_PARENTHESIS_BRACE => [ 'start' => '(', 'end' => ')', ], self::BLOCK_TYPE_INDEX_SQUARE_BRACE => [ 'start' => '[', 'end' => ']', ], self::BLOCK_TYPE_ARRAY_SQUARE_BRACE => [ 'start' => [CT::T_ARRAY_SQUARE_BRACE_OPEN, '['], 'end' => [CT::T_ARRAY_SQUARE_BRACE_CLOSE, ']'], ], self::BLOCK_TYPE_DYNAMIC_PROP_BRACE => [ 'start' => [CT::T_DYNAMIC_PROP_BRACE_OPEN, '{'], 'end' => [CT::T_DYNAMIC_PROP_BRACE_CLOSE, '}'], ], self::BLOCK_TYPE_DYNAMIC_VAR_BRACE => [ 'start' => [CT::T_DYNAMIC_VAR_BRACE_OPEN, '{'], 'end' => [CT::T_DYNAMIC_VAR_BRACE_CLOSE, '}'], ], self::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE => [ 'start' => [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, '{'], 'end' => [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE, '}'], ], self::BLOCK_TYPE_GROUP_IMPORT_BRACE => [ 'start' => [CT::T_GROUP_IMPORT_BRACE_OPEN, '{'], 'end' => [CT::T_GROUP_IMPORT_BRACE_CLOSE, '}'], ], self::BLOCK_TYPE_DESTRUCTURING_SQUARE_BRACE => [ 'start' => [CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, '['], 'end' => [CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, ']'], ], self::BLOCK_TYPE_BRACE_CLASS_INSTANTIATION => [ 'start' => [CT::T_BRACE_CLASS_INSTANTIATION_OPEN, '('], 'end' => [CT::T_BRACE_CLASS_INSTANTIATION_CLOSE, ')'], ], self::BLOCK_TYPE_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS => [ 'start' => [CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, '('], 'end' => [CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, ')'], ], self::BLOCK_TYPE_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE => [ 'start' => [CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_OPEN, '{'], 'end' => [CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_CLOSE, '}'], ], self::BLOCK_TYPE_COMPLEX_STRING_VARIABLE => [ 'start' => [\T_DOLLAR_OPEN_CURLY_BRACES, '${'], 'end' => [CT::T_DOLLAR_CLOSE_CURLY_BRACES, '}'], ], self::BLOCK_TYPE_PROPERTY_HOOK => [ 'start' => [CT::T_PROPERTY_HOOK_BRACE_OPEN, '{'], 'end' => [CT::T_PROPERTY_HOOK_BRACE_CLOSE, '}'], ], self::BLOCK_TYPE_ATTRIBUTE => [ 'start' => [FCT::T_ATTRIBUTE, '#['], 'end' => [CT::T_ATTRIBUTE_CLOSE, ']'], ], ]; } /** * Set new size of collection. * * @param int $size */ #[\ReturnTypeWillChange] public function setSize($size): bool { throw new \RuntimeException('Changing tokens collection size explicitly is not allowed.'); } /** * Unset collection item. * * @param int $index */ public function offsetUnset($index): void { if (\count($this) - 1 !== $index) { Future::triggerDeprecation(new \InvalidArgumentException(\sprintf( 'Tokens should be a list - only the last index can be unset. This will be enforced in version %d.0.', Application::getMajorVersion() + 1, ))); } if (isset($this[$index])) { if (isset($this->blockStartCache[$index])) { unset($this->blockEndCache[$this->blockStartCache[$index]], $this->blockStartCache[$index]); } if (isset($this->blockEndCache[$index])) { unset($this->blockStartCache[$this->blockEndCache[$index]], $this->blockEndCache[$index]); } $this->unregisterFoundToken($this[$index]); $this->changed = true; $this->collectionHash = null; self::clearCache($this->codeHash); $this->codeHash = null; $this->namespaceDeclarations = null; } parent::offsetUnset($index); } /** * Set collection item. * * Warning! `$newval` must not be typehinted to be compatible with `ArrayAccess::offsetSet` method. * * @param int $index * @param Token $newval */ public function offsetSet($index, $newval): void { if (0 > $index || \count($this) <= $index) { Future::triggerDeprecation(new \InvalidArgumentException(\sprintf( 'Tokens should be a list - index must be within the existing range. This will be enforced in version %d.0.', Application::getMajorVersion() + 1, ))); } if (!$newval instanceof Token) { Future::triggerDeprecation(new \InvalidArgumentException(\sprintf( 'Tokens should be a list of Token instances - newval must be a Token. This will be enforced in version %d.0.', Application::getMajorVersion() + 1, ))); } if (isset($this[$index])) { if (isset($this->blockStartCache[$index])) { unset($this->blockEndCache[$this->blockStartCache[$index]], $this->blockStartCache[$index]); } if (isset($this->blockEndCache[$index])) { unset($this->blockStartCache[$this->blockEndCache[$index]], $this->blockEndCache[$index]); } } if (!isset($this[$index]) || !$this[$index]->equals($newval)) { if (isset($this[$index])) { $this->unregisterFoundToken($this[$index]); } $this->changed = true; $this->collectionHash = null; self::clearCache($this->codeHash); $this->codeHash = null; $this->namespaceDeclarations = null; $this->registerFoundToken($newval); } parent::offsetSet($index, $newval); } /** * Clear internal flag if collection was changed and flag for all collection's items. */ public function clearChanged(): void { $this->changed = false; } /** * Clear empty tokens. * * Empty tokens can occur e.g. after calling clear on item of collection. */ public function clearEmptyTokens(): void { // no empty token found, therefore there is no need to override collection if (!$this->isTokenKindFound('')) { return; } $limit = \count($this); for ($index = 0; $index < $limit; ++$index) { if ($this->isEmptyAt($index)) { break; } } for ($count = $index; $index < $limit; ++$index) { if (!$this->isEmptyAt($index)) { // use directly for speed, skip the register of token kinds found etc. $buffer = $this[$count]; parent::offsetSet($count, $this[$index]); parent::offsetSet($index, $buffer); if (isset($this->blockStartCache[$index])) { $otherEndIndex = $this->blockStartCache[$index]; unset($this->blockStartCache[$index]); $this->blockStartCache[$count] = $otherEndIndex; $this->blockEndCache[$otherEndIndex] = $count; } if (isset($this->blockEndCache[$index])) { $otherEndIndex = $this->blockEndCache[$index]; unset($this->blockEndCache[$index]); $this->blockStartCache[$otherEndIndex] = $count; $this->blockEndCache[$count] = $otherEndIndex; } ++$count; } } // we are moving the tokens, we need to clear the index-based Cache $this->namespaceDeclarations = null; $this->foundTokenKinds[''] = 0; $this->collectionHash = null; $this->updateSizeByTrimmingTrailingEmptyTokens(); } /** * Ensure that on given index is a whitespace with given kind. * * If there is a whitespace then it's content will be modified. * If not - the new Token will be added. * * @param int $index index * @param int $indexOffset index offset for Token insertion * @param string $whitespace whitespace to set * * @return bool if new Token was added */ public function ensureWhitespaceAtIndex(int $index, int $indexOffset, string $whitespace): bool { $removeLastCommentLine = static function (self $tokens, int $index, int $indexOffset, string $whitespace): string { $token = $tokens[$index]; if (1 === $indexOffset && $token->isGivenKind(\T_OPEN_TAG)) { if (str_starts_with($whitespace, "\r\n")) { $tokens[$index] = new Token([\T_OPEN_TAG, rtrim($token->getContent())."\r\n"]); return \strlen($whitespace) > 2 // @TODO: can be removed on PHP 8; https://php.net/manual/en/function.substr.php ? substr($whitespace, 2) : ''; } $tokens[$index] = new Token([\T_OPEN_TAG, rtrim($token->getContent()).$whitespace[0]]); return \strlen($whitespace) > 1 // @TODO: can be removed on PHP 8; https://php.net/manual/en/function.substr.php ? substr($whitespace, 1) : ''; } return $whitespace; }; if ($this[$index]->isWhitespace()) { $whitespace = $removeLastCommentLine($this, $index - 1, $indexOffset, $whitespace); if ('' === $whitespace) { $this->clearAt($index); } else { $this[$index] = new Token([\T_WHITESPACE, $whitespace]); } return false; } $whitespace = $removeLastCommentLine($this, $index, $indexOffset, $whitespace); if ('' === $whitespace) { return false; } $this->insertAt( $index + $indexOffset, [new Token([\T_WHITESPACE, $whitespace])], ); return true; } /** * @param self::BLOCK_TYPE_* $type type of block * @param int $searchIndex index of opening brace * * @return int<0, max> index of closing brace */ public function findBlockEnd(int $type, int $searchIndex): int { return $this->findOppositeBlockEdge($type, $searchIndex, true); } /** * @param self::BLOCK_TYPE_* $type type of block * @param int $searchIndex index of closing brace * * @return int<0, max> index of opening brace */ public function findBlockStart(int $type, int $searchIndex): int { return $this->findOppositeBlockEdge($type, $searchIndex, false); } /** * @param int|non-empty-list<int> $possibleKind kind or array of kinds * @param int $start optional offset * @param null|int $end optional limit * * @return ($possibleKind is int ? array<int<0, max>, Token> : array<int, array<int<0, max>, Token>>) */ public function findGivenKind($possibleKind, int $start = 0, ?int $end = null): array { if (null === $end) { $end = \count($this); } $elements = []; $possibleKinds = (array) $possibleKind; foreach ($possibleKinds as $kind) { $elements[$kind] = []; } $possibleKinds = array_values(array_filter($possibleKinds, fn ($kind): bool => $this->isTokenKindFound($kind))); if (\count($possibleKinds) > 0) { for ($i = $start; $i < $end; ++$i) { $token = $this[$i]; if ($token->isGivenKind($possibleKinds)) { $elements[$token->getId()][$i] = $token; } } } return \is_array($possibleKind) ? $elements : $elements[$possibleKind]; } public function generateCode(): string { $code = $this->generatePartialCode(0, \count($this) - 1); if (null === $this->codeHash) { $this->changeCodeHash(self::calculateHash($code)); // ensure code hash is calculated, so it's registered in cache } return $code; } /** * Generate code from tokens between given indices. * * @param int $start start index * @param int $end end index */ public function generatePartialCode(int $start, int $end): string { $code = ''; for ($i = $start; $i <= $end; ++$i) { $code .= $this[$i]->getContent(); } return $code; } /** * Get hash of code. */ public function getCodeHash(): string { if (null === $this->codeHash) { $code = $this->generatePartialCode(0, \count($this) - 1); $this->changeCodeHash(self::calculateHash($code)); // ensure code hash is calculated, so it's registered in cache } return $this->codeHash; } /** * @return non-empty-string * * @internal */ public function getCollectionHash(): string { if (null === $this->collectionHash) { $this->collectionHash = self::calculateHash( $this->getCodeHash() .'#' .\count($this) .'#' .implode( '', array_map(static fn (?Token $token): ?int => null !== $token ? $token->getId() : null, $this->toArray()), ), ); } return $this->collectionHash; } /** * Get index for closest next token which is non whitespace. * * This method is shorthand for getNonWhitespaceSibling method. * * @param int $index token index * @param null|string $whitespaces whitespaces characters for Token::isWhitespace */ public function getNextNonWhitespace(int $index, ?string $whitespaces = null): ?int { return $this->getNonWhitespaceSibling($index, 1, $whitespaces); } /** * Get index for closest next token of given kind. * * This method is shorthand for getTokenOfKindSibling method. * * @param int $index token index * @param list<_PhpTokenPrototypePartial|Token> $tokens possible tokens * @param bool $caseSensitive perform a case sensitive comparison */ public function getNextTokenOfKind(int $index, array $tokens = [], bool $caseSensitive = true): ?int { return $this->getTokenOfKindSibling($index, 1, $tokens, $caseSensitive); } /** * Get index for closest sibling token which is non whitespace. * * @param int $index token index * @param -1|1 $direction * @param null|string $whitespaces whitespaces characters for Token::isWhitespace */ public function getNonWhitespaceSibling(int $index, int $direction, ?string $whitespaces = null): ?int { while (true) { $index += $direction; if (!$this->offsetExists($index)) { return null; } if (!$this[$index]->isWhitespace($whitespaces)) { return $index; } } } /** * Get index for closest previous token which is non whitespace. * * This method is shorthand for getNonWhitespaceSibling method. * * @param int $index token index * @param null|string $whitespaces whitespaces characters for Token::isWhitespace */ public function getPrevNonWhitespace(int $index, ?string $whitespaces = null): ?int { return $this->getNonWhitespaceSibling($index, -1, $whitespaces); } /** * Get index for closest previous token of given kind. * This method is shorthand for getTokenOfKindSibling method. * * @param int $index token index * @param list<_PhpTokenPrototypePartial|Token> $tokens possible tokens * @param bool $caseSensitive perform a case sensitive comparison */ public function getPrevTokenOfKind(int $index, array $tokens = [], bool $caseSensitive = true): ?int { return $this->getTokenOfKindSibling($index, -1, $tokens, $caseSensitive); } /** * Get index for closest sibling token of given kind. * * @param int $index token index * @param -1|1 $direction * @param list<_PhpTokenPrototypePartial|Token> $tokens possible tokens * @param bool $caseSensitive perform a case sensitive comparison */ public function getTokenOfKindSibling(int $index, int $direction, array $tokens = [], bool $caseSensitive = true): ?int { $tokens = array_values( array_filter( $tokens, fn ($token): bool => $this->isTokenKindFound($this->extractTokenKind($token)), ), ); if (0 === \count($tokens)) { return null; } while (true) { $index += $direction; if (!$this->offsetExists($index)) { return null; } if ($this[$index]->equalsAny($tokens, $caseSensitive)) { return $index; } } } /** * Get index for closest sibling token not of given kind. * * @param int $index token index * @param -1|1 $direction * @param list<_PhpTokenPrototypePartial|Token> $tokens possible tokens */ public function getTokenNotOfKindSibling(int $index, int $direction, array $tokens = []): ?int { return $this->getTokenNotOfKind( $index, $direction, fn (int $a): bool => $this[$a]->equalsAny($tokens), ); } /** * Get index for closest sibling token not of given kind. * * @param int $index token index * @param -1|1 $direction * @param list<int> $kinds possible tokens kinds */ public function getTokenNotOfKindsSibling(int $index, int $direction, array $kinds = []): ?int { return $this->getTokenNotOfKind( $index, $direction, fn (int $index): bool => $this[$index]->isGivenKind($kinds), ); } /** * Get index for closest sibling token that is not a whitespace, comment or attribute. * * @param int $index token index * @param -1|1 $direction */ public function getMeaningfulTokenSibling(int $index, int $direction): ?int { return $this->getTokenNotOfKindsSibling( $index, $direction, [\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT], ); } /** * Get index for closest sibling token which is not empty. * * @param int $index token index * @param -1|1 $direction */ public function getNonEmptySibling(int $index, int $direction): ?int { while (true) { $index += $direction; if (!$this->offsetExists($index)) { return null; } if (!$this->isEmptyAt($index)) { return $index; } } } /** * Get index for closest next token that is not a whitespace or comment. * * @param int $index token index */ public function getNextMeaningfulToken(int $index): ?int { return $this->getMeaningfulTokenSibling($index, 1); } /** * Get index for closest previous token that is not a whitespace or comment. * * @param int $index token index */ public function getPrevMeaningfulToken(int $index): ?int { return $this->getMeaningfulTokenSibling($index, -1); } /** * Find a sequence of meaningful tokens and returns the array of their locations. * * @param non-empty-list<_PhpTokenPrototypePartial|Token> $sequence an array of token (kinds) * @param int $start start index, defaulting to the start of the file * @param null|int $end end index, defaulting to the end of the file * @param array<int, bool>|bool $caseSensitive global case sensitiveness or a list of booleans, whose keys should match * the ones used in $sequence. If any is missing, the default case-sensitive * comparison is used * * @return null|non-empty-array<int<0, max>, Token> an array containing the tokens matching the sequence elements, indexed by their position */ public function findSequence(array $sequence, int $start = 0, ?int $end = null, $caseSensitive = true): ?array { $sequenceCount = \count($sequence); if (0 === $sequenceCount) { throw new \InvalidArgumentException('Invalid sequence.'); } // $end defaults to the end of the collection $end = null === $end ? \count($this) - 1 : min($end, \count($this) - 1); if ($start + $sequenceCount - 1 > $end) { return null; } $nonMeaningFullKind = [\T_COMMENT, \T_DOC_COMMENT, \T_WHITESPACE]; // make sure the sequence content is "meaningful" foreach ($sequence as $key => $token) { // if not a Token instance already, we convert it to verify the meaningfulness if (!$token instanceof Token) { if (\is_array($token) && !isset($token[1])) { // fake some content as it is required by the Token constructor, // although optional for search purposes $token[1] = 'DUMMY'; } $token = new Token($token); } if ($token->isGivenKind($nonMeaningFullKind)) { throw new \InvalidArgumentException(\sprintf('Non-meaningful token at position: "%s".', $key)); } if ('' === $token->getContent()) { throw new \InvalidArgumentException(\sprintf('Non-meaningful (empty) token at position: "%s".', $key)); } } foreach ($sequence as $token) { if (!$this->isTokenKindFound($this->extractTokenKind($token))) { return null; } } // remove the first token from the sequence, so we can freely iterate through the sequence after a match to // the first one is found $firstKey = array_key_first($sequence); $firstCs = self::isKeyCaseSensitive($caseSensitive, $firstKey); $firstToken = $sequence[$firstKey]; unset($sequence[$firstKey]); // begin searching for the first token in the sequence (start included) $index = $start - 1; while ($index <= $end) { $index = $this->getNextTokenOfKind($index, [$firstToken], $firstCs); // ensure we found a match and didn't get past the end index if (null === $index || $index > $end) { return null; } // initialise the result array with the current index $result = [$index => $this[$index]]; // advance cursor to the current position $currIdx = $index; // iterate through the remaining tokens in the sequence foreach ($sequence as $key => $token) { $currIdx = $this->getNextMeaningfulToken($currIdx); // ensure we didn't go too far if (null === $currIdx || $currIdx > $end) { return null; } if (!$this[$currIdx]->equals($token, self::isKeyCaseSensitive($caseSensitive, $key))) { // not a match, restart the outer loop continue 2; } // append index to the result array $result[$currIdx] = $this[$currIdx]; } // do we have a complete match? // hint: $result is bigger than $sequence since the first token has been removed from the latter if (\count($sequence) < \count($result)) { return $result; } } return null; } /** * Insert instances of Token inside collection. * * @param int $index start inserting index
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/Tokenizer/TransformerInterface.php
src/Tokenizer/TransformerInterface.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer; /** * Interface for Transformer class. * * Transformer role is to register custom tokens and transform Tokens collection to use them. * * Custom token is a user defined token type and is used to separate different meaning of original token type. * For example T_ARRAY is a token for both creating new array and typehinting a parameter. This two meaning should have two token types. * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ interface TransformerInterface { /** * Get tokens created by Transformer. * * @return list<int> */ public function getCustomTokens(): array; /** * Return the name of the transformer. * * The name must be all lowercase and without any spaces. * * @return string The name of the fixer */ public function getName(): string; /** * Returns the priority of the transformer. * * The default priority is 0 and higher priorities are executed first. */ public function getPriority(): int; /** * Return minimal required PHP version id to transform the code. * * Custom Token kinds from Transformers are always registered, but sometimes * there is no need to analyse the Tokens if for sure we cannot find examined * token kind, e.g. transforming `T_FUNCTION` in `<?php use function Foo\\bar;` * code. */ public function getRequiredPhpVersionId(): int; /** * Process Token to transform it into custom token when needed. */ public function process(Tokens $tokens, Token $token, int $index): void; }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/AbstractTypeTransformer.php
src/Tokenizer/AbstractTypeTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer; /** * @phpstan-import-type _PhpTokenPrototype from Token * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ abstract class AbstractTypeTransformer extends AbstractTransformer { private const TYPE_END_TOKENS = [')', [\T_CALLABLE], [\T_NS_SEPARATOR], [\T_STATIC], [\T_STRING], [CT::T_ARRAY_TYPEHINT]]; private const TYPE_TOKENS = [ '|', '&', '(', ...self::TYPE_END_TOKENS, [CT::T_TYPE_ALTERNATION], [CT::T_TYPE_INTERSECTION], // some siblings may already be transformed [\T_WHITESPACE], [\T_COMMENT], [\T_DOC_COMMENT], // technically these can be inside of type tokens array ]; abstract protected function replaceToken(Tokens $tokens, int $index): void; /** * @param _PhpTokenPrototype $originalToken */ protected function doProcess(Tokens $tokens, int $index, $originalToken): void { if (!$tokens[$index]->equals($originalToken)) { return; } if (!$this->isPartOfType($tokens, $index)) { return; } $this->replaceToken($tokens, $index); } private function isPartOfType(Tokens $tokens, int $index): bool { // return types and non-capturing catches $typeColonIndex = $tokens->getTokenNotOfKindSibling($index, -1, self::TYPE_TOKENS); if ($tokens[$typeColonIndex]->isGivenKind([\T_CATCH, CT::T_TYPE_COLON, \T_CONST])) { return true; } // for parameter there will be splat operator or variable after the type ("&" is ambiguous and can be reference or bitwise and) $afterTypeIndex = $tokens->getTokenNotOfKindSibling($index, 1, self::TYPE_TOKENS); if ($tokens[$afterTypeIndex]->isGivenKind(\T_ELLIPSIS)) { return true; } if (!$tokens[$afterTypeIndex]->isGivenKind(\T_VARIABLE)) { return false; } $beforeVariableIndex = $tokens->getPrevMeaningfulToken($afterTypeIndex); if ($tokens[$beforeVariableIndex]->equals('&')) { $prevIndex = $tokens->getPrevTokenOfKind( $index, [ '{', '}', ';', [\T_CLOSE_TAG], [\T_FN], [\T_FUNCTION], ], ); return null !== $prevIndex && $tokens[$prevIndex]->isGivenKind([\T_FN, \T_FUNCTION]); } return $tokens[$beforeVariableIndex]->equalsAny(self::TYPE_END_TOKENS); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Processor/ImportProcessor.php
src/Tokenizer/Processor/ImportProcessor.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Processor; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; use PhpCsFixer\WhitespacesFixerConfig; /** * @author Greg Korba <greg@codito.dev> * * @readonly * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ImportProcessor { private WhitespacesFixerConfig $whitespacesConfig; public function __construct(WhitespacesFixerConfig $whitespacesConfig) { $this->whitespacesConfig = $whitespacesConfig; } /** * @param array{ * const?: array<int|string, non-empty-string>, * class?: array<int|string, non-empty-string>, * function?: array<int|string, non-empty-string> * } $imports */ public function insertImports(Tokens $tokens, array $imports, int $atIndex): void { $lineEnding = $this->whitespacesConfig->getLineEnding(); $prevIndex = $tokens->getPrevMeaningfulToken($atIndex); if (null !== $prevIndex && $tokens[$prevIndex]->isGivenKind(\T_OPEN_TAG_WITH_ECHO)) { $tokens->insertAt($prevIndex, Tokens::fromCode("<?php\n?>")); $atIndex = $prevIndex + 1; } if (!$tokens[$atIndex]->isWhitespace() || !str_contains($tokens[$atIndex]->getContent(), "\n")) { $tokens->insertAt($atIndex, new Token([\T_WHITESPACE, $lineEnding])); } foreach ($imports as $type => $typeImports) { sort($typeImports); $items = []; foreach ($typeImports as $name) { $items = array_merge($items, [ new Token([\T_WHITESPACE, $lineEnding]), new Token([\T_USE, 'use']), new Token([\T_WHITESPACE, ' ']), ]); if ('const' === $type) { $items[] = new Token([CT::T_CONST_IMPORT, 'const']); $items[] = new Token([\T_WHITESPACE, ' ']); } elseif ('function' === $type) { $items[] = new Token([CT::T_FUNCTION_IMPORT, 'function']); $items[] = new Token([\T_WHITESPACE, ' ']); } $items = array_merge($items, self::tokenizeName($name)); $items[] = new Token(';'); } $tokens->insertAt($atIndex, $items); } } /** * @param non-empty-string $name * * @return list<Token> */ public static function tokenizeName(string $name): array { $parts = explode('\\', $name); $newTokens = []; if ('' === $parts[0]) { $newTokens[] = new Token([\T_NS_SEPARATOR, '\\']); array_shift($parts); } foreach ($parts as $part) { $newTokens[] = new Token([\T_STRING, $part]); $newTokens[] = new Token([\T_NS_SEPARATOR, '\\']); } array_pop($newTokens); 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/Tokenizer/Analyzer/AlternativeSyntaxAnalyzer.php
src/Tokenizer/Analyzer/AlternativeSyntaxAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\Tokenizer\Tokens; /** * @internal * * @TODO 4.0 remove this analyzer and move this logic into a transformer * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class AlternativeSyntaxAnalyzer { private const ALTERNATIVE_SYNTAX_BLOCK_EDGES = [ \T_IF => [\T_ENDIF, \T_ELSE, \T_ELSEIF], \T_ELSE => [\T_ENDIF], \T_ELSEIF => [\T_ENDIF, \T_ELSE, \T_ELSEIF], \T_FOR => [\T_ENDFOR], \T_FOREACH => [\T_ENDFOREACH], \T_WHILE => [\T_ENDWHILE], \T_SWITCH => [\T_ENDSWITCH], ]; public function belongsToAlternativeSyntax(Tokens $tokens, int $index): bool { if (!$tokens[$index]->equals(':')) { return false; } $prevIndex = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prevIndex]->isGivenKind(\T_ELSE)) { return true; } if (!$tokens[$prevIndex]->equals(')')) { return false; } $openParenthesisIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $prevIndex); $beforeOpenParenthesisIndex = $tokens->getPrevMeaningfulToken($openParenthesisIndex); return $tokens[$beforeOpenParenthesisIndex]->isGivenKind([ \T_DECLARE, \T_ELSEIF, \T_FOR, \T_FOREACH, \T_IF, \T_SWITCH, \T_WHILE, ]); } public function findAlternativeSyntaxBlockEnd(Tokens $tokens, int $index): int { if (!isset($tokens[$index])) { throw new \InvalidArgumentException("There is no token at index {$index}."); } if (!$this->isStartOfAlternativeSyntaxBlock($tokens, $index)) { throw new \InvalidArgumentException("Token at index {$index} is not the start of an alternative syntax block."); } $startTokenKind = $tokens[$index]->getId(); if (!isset(self::ALTERNATIVE_SYNTAX_BLOCK_EDGES[$startTokenKind])) { throw new \LogicException(\sprintf('Unknown startTokenKind: %s', $tokens[$index]->toJson())); } $endTokenKinds = self::ALTERNATIVE_SYNTAX_BLOCK_EDGES[$startTokenKind]; $findKinds = [[$startTokenKind]]; foreach ($endTokenKinds as $endTokenKind) { $findKinds[] = [$endTokenKind]; } while (true) { $index = $tokens->getNextTokenOfKind($index, $findKinds); if ($tokens[$index]->isGivenKind($endTokenKinds)) { return $index; } if ($this->isStartOfAlternativeSyntaxBlock($tokens, $index)) { $index = $this->findAlternativeSyntaxBlockEnd($tokens, $index); } } } private function isStartOfAlternativeSyntaxBlock(Tokens $tokens, int $index): bool { $map = self::ALTERNATIVE_SYNTAX_BLOCK_EDGES; $startTokenKind = $tokens[$index]->getId(); if (null === $startTokenKind || !isset($map[$startTokenKind])) { return false; } $index = $tokens->getNextMeaningfulToken($index); if ($tokens[$index]->equals('(')) { $index = $tokens->getNextMeaningfulToken( $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index), ); } return $tokens[$index]->equals(':'); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/ReferenceAnalyzer.php
src/Tokenizer/Analyzer/ReferenceAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Tokens; /** * @author Kuba Werłos <werlos@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ReferenceAnalyzer { public function isReference(Tokens $tokens, int $index): bool { if ($tokens[$index]->isGivenKind(CT::T_RETURN_REF)) { return true; } if (!$tokens[$index]->equals('&')) { return false; } /** @var int $index */ $index = $tokens->getPrevMeaningfulToken($index); if ($tokens[$index]->equalsAny(['=', [\T_AS], [\T_CALLABLE], [\T_DOUBLE_ARROW], [CT::T_ARRAY_TYPEHINT]])) { return true; } if ($tokens[$index]->isGivenKind(\T_STRING)) { $index = $tokens->getPrevMeaningfulToken($index); } return $tokens[$index]->equalsAny(['(', ',', [\T_NS_SEPARATOR], [CT::T_NULLABLE_TYPE]]); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/GotoLabelAnalyzer.php
src/Tokenizer/Analyzer/GotoLabelAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\Tokenizer\Tokens; /** * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class GotoLabelAnalyzer { public function belongsToGoToLabel(Tokens $tokens, int $index): bool { if (!$tokens[$index]->equals(':')) { return false; } $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$prevMeaningfulTokenIndex]->isGivenKind(\T_STRING)) { return false; } $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulTokenIndex); return $tokens[$prevMeaningfulTokenIndex]->equalsAny([':', ';', '{', '}', [\T_OPEN_TAG]]); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/NamespacesAnalyzer.php
src/Tokenizer/Analyzer/NamespacesAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; use PhpCsFixer\Tokenizer\Tokens; /** * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NamespacesAnalyzer { /** * @return list<NamespaceAnalysis> */ public function getDeclarations(Tokens $tokens): array { $namespaces = []; for ($index = 1, $count = \count($tokens); $index < $count; ++$index) { $token = $tokens[$index]; if (!$token->isGivenKind(\T_NAMESPACE)) { continue; } $declarationEndIndex = $tokens->getNextTokenOfKind($index, [';', '{']); $namespace = trim($tokens->generatePartialCode($index + 1, $declarationEndIndex - 1)); $declarationParts = explode('\\', $namespace); $shortName = end($declarationParts); if ($tokens[$declarationEndIndex]->equals('{')) { $scopeEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $declarationEndIndex); } else { $scopeEndIndex = $tokens->getNextTokenOfKind($declarationEndIndex, [[\T_NAMESPACE]]); if (null === $scopeEndIndex) { $scopeEndIndex = \count($tokens); } --$scopeEndIndex; } $namespaces[] = new NamespaceAnalysis( $namespace, $shortName, $index, $declarationEndIndex, $index, $scopeEndIndex, ); // Continue the analysis after the end of this namespace to find the next one $index = $scopeEndIndex; } if (0 === \count($namespaces) && $tokens->isTokenKindFound(\T_OPEN_TAG)) { $namespaces[] = new NamespaceAnalysis( '', '', $openTagIndex = $tokens[0]->isGivenKind(\T_INLINE_HTML) ? 1 : 0, $openTagIndex, $openTagIndex, \count($tokens) - 1, ); } return $namespaces; } public function getNamespaceAt(Tokens $tokens, int $index): NamespaceAnalysis { if (!$tokens->offsetExists($index)) { throw new \InvalidArgumentException(\sprintf('Token index %d does not exist.', $index)); } foreach ($this->getDeclarations($tokens) as $namespace) { if ($namespace->getScopeStartIndex() <= $index && $namespace->getScopeEndIndex() >= $index) { return $namespace; } } throw new \LogicException(\sprintf('Unable to get the namespace at index %d.', $index)); } /** * @return array{NamespaceAnalysis, array<string, NamespaceUseAnalysis>} */ public static function collectNamespaceAnalysis(Tokens $tokens, int $startIndex): array { $namespaceAnalysis = (new self())->getNamespaceAt($tokens, $startIndex); $namespaceUseAnalyses = (new NamespaceUsesAnalyzer())->getDeclarationsInNamespace($tokens, $namespaceAnalysis); $uses = []; foreach ($namespaceUseAnalyses as $use) { if (!$use->isClass()) { continue; } $uses[$use->getShortName()] = $use; } return [$namespaceAnalysis, $uses]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/BlocksAnalyzer.php
src/Tokenizer/Analyzer/BlocksAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @author Kuba Werłos <werlos@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class BlocksAnalyzer { public function isBlock(Tokens $tokens, int $openIndex, int $closeIndex): bool { if (!$tokens->offsetExists($openIndex)) { throw new \InvalidArgumentException(\sprintf('Tokex index %d for potential block opening does not exist.', $openIndex)); } if (!$tokens->offsetExists($closeIndex)) { throw new \InvalidArgumentException(\sprintf('Token index %d for potential block closure does not exist.', $closeIndex)); } $blockType = $this->getBlockType($tokens[$openIndex]); if (null === $blockType) { return false; } return $closeIndex === $tokens->findBlockEnd($blockType, $openIndex); } /** * @return Tokens::BLOCK_TYPE_* */ private function getBlockType(Token $token): ?int { foreach (Tokens::getBlockEdgeDefinitions() as $blockType => $definition) { if ($token->equals($definition['start'])) { return $blockType; } } return null; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/ControlCaseStructuresAnalyzer.php
src/Tokenizer/Analyzer/ControlCaseStructuresAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\Tokenizer\Analyzer\Analysis\AbstractControlCaseStructuresAnalysis; use PhpCsFixer\Tokenizer\Analyzer\Analysis\CaseAnalysis; use PhpCsFixer\Tokenizer\Analyzer\Analysis\DefaultAnalysis; use PhpCsFixer\Tokenizer\Analyzer\Analysis\EnumAnalysis; use PhpCsFixer\Tokenizer\Analyzer\Analysis\MatchAnalysis; use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Tokens; /** * @no-named-arguments Parameter names are not covered by the backward compatibility promise. * * @TODO 4.0: mark @internal */ final class ControlCaseStructuresAnalyzer { private const SUPPORTED_TYPES_WITH_CASE_OR_DEFAULT = [ \T_SWITCH, FCT::T_MATCH, FCT::T_ENUM, ]; /** * @param list<int> $types Token types of interest of which analyses must be returned * * @return \Generator<int, AbstractControlCaseStructuresAnalysis> */ public static function findControlStructures(Tokens $tokens, array $types): \Generator { if (\count($types) < 1) { return; // quick skip } foreach ($types as $type) { if (!\in_array($type, self::SUPPORTED_TYPES_WITH_CASE_OR_DEFAULT, true)) { throw new \InvalidArgumentException(\sprintf('Unexpected type "%d".', $type)); } } if (!$tokens->isAnyTokenKindsFound($types)) { return; // quick skip } $depth = -1; /** * @var list<array{ * kind: null|int, * index: int, * brace_count: int, * cases: list<array{index: int, open: int}>, * default: null|array{index: int, open: int}, * alternative_syntax: bool, * }> $stack */ $stack = []; $isTypeOfInterest = false; foreach ($tokens as $index => $token) { if ($token->isGivenKind(self::SUPPORTED_TYPES_WITH_CASE_OR_DEFAULT)) { ++$depth; $stack[$depth] = [ 'kind' => $token->getId(), 'index' => $index, 'brace_count' => 0, 'cases' => [], 'default' => null, 'alternative_syntax' => false, ]; $isTypeOfInterest = \in_array($stack[$depth]['kind'], $types, true); if ($token->isGivenKind(\T_SWITCH)) { $index = $tokens->getNextMeaningfulToken($index); $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); $stack[$depth]['open'] = $tokens->getNextMeaningfulToken($index); $stack[$depth]['alternative_syntax'] = $tokens[$stack[$depth]['open']]->equals(':'); } elseif ($token->isGivenKind(FCT::T_MATCH)) { $index = $tokens->getNextMeaningfulToken($index); $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); $stack[$depth]['open'] = $tokens->getNextMeaningfulToken($index); } elseif ($token->isGivenKind(FCT::T_ENUM)) { $stack[$depth]['open'] = $tokens->getNextTokenOfKind($index, ['{']); } continue; } if ($depth < 0) { continue; } if ($token->equals('{')) { ++$stack[$depth]['brace_count']; continue; } if ($token->equals('}')) { --$stack[$depth]['brace_count']; if (0 === $stack[$depth]['brace_count']) { if ($stack[$depth]['alternative_syntax']) { continue; } if ($isTypeOfInterest) { $stack[$depth]['end'] = $index; yield $stack[$depth]['index'] => self::buildControlCaseStructureAnalysis($stack[$depth]); } array_pop($stack); --$depth; if ($depth < -1) { // @phpstan-ignore-line throw new \RuntimeException('Analysis depth count failure.'); } if (isset($stack[$depth]['kind'])) { $isTypeOfInterest = \in_array($stack[$depth]['kind'], $types, true); } } continue; } if ($tokens[$index]->isGivenKind(\T_ENDSWITCH)) { if (!$stack[$depth]['alternative_syntax']) { throw new \RuntimeException('Analysis syntax failure, unexpected "T_ENDSWITCH".'); } if (\T_SWITCH !== $stack[$depth]['kind']) { throw new \RuntimeException('Analysis type failure, unexpected "T_ENDSWITCH".'); } if (0 !== $stack[$depth]['brace_count']) { throw new \RuntimeException('Analysis count failure, unexpected "T_ENDSWITCH".'); } $index = $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]); if ($isTypeOfInterest) { $stack[$depth]['end'] = $index; yield $stack[$depth]['index'] => self::buildControlCaseStructureAnalysis($stack[$depth]); } array_pop($stack); --$depth; if ($depth < -1) { // @phpstan-ignore-line throw new \RuntimeException('Analysis depth count failure ("T_ENDSWITCH").'); } if (isset($stack[$depth]['kind'])) { $isTypeOfInterest = \in_array($stack[$depth]['kind'], $types, true); } } if (!$isTypeOfInterest) { continue; // don't bother to analyse stuff that caller is not interested in } if ($token->isGivenKind(\T_CASE)) { $stack[$depth]['cases'][] = ['index' => $index, 'open' => self::findCaseOpen($tokens, $stack[$depth]['kind'], $index)]; } elseif ($token->isGivenKind(\T_DEFAULT)) { if (null !== $stack[$depth]['default']) { throw new \RuntimeException('Analysis multiple "default" found.'); } $stack[$depth]['default'] = ['index' => $index, 'open' => self::findDefaultOpen($tokens, $stack[$depth]['kind'], $index)]; } } } /** * @param array{ * kind: int, * index: int, * open: int, * end: int, * cases: list<array{index: int, open: int}>, * default: null|array{index: int, open: int}, * } $analysis */ private static function buildControlCaseStructureAnalysis(array $analysis): AbstractControlCaseStructuresAnalysis { $default = null === $analysis['default'] ? null : new DefaultAnalysis($analysis['default']['index'], $analysis['default']['open']); $cases = []; foreach ($analysis['cases'] as $case) { $cases[$case['index']] = new CaseAnalysis($case['index'], $case['open']); } sort($cases); if (\T_SWITCH === $analysis['kind']) { return new SwitchAnalysis( $analysis['index'], $analysis['open'], $analysis['end'], $cases, $default, ); } if (FCT::T_ENUM === $analysis['kind']) { return new EnumAnalysis( $analysis['index'], $analysis['open'], $analysis['end'], $cases, ); } if (FCT::T_MATCH === $analysis['kind']) { return new MatchAnalysis( $analysis['index'], $analysis['open'], $analysis['end'], $default, ); } throw new \InvalidArgumentException(\sprintf('Unexpected type "%d".', $analysis['kind'])); } private static function findCaseOpen(Tokens $tokens, int $kind, int $index): int { if (\T_SWITCH === $kind) { $ternariesCount = 0; --$index; while (true) { ++$index; if ($tokens[$index]->equalsAny(['(', '{'])) { // skip constructs $type = Tokens::detectBlockType($tokens[$index]); $index = $tokens->findBlockEnd($type['type'], $index); continue; } if ($tokens[$index]->equals('?')) { ++$ternariesCount; continue; } if ($tokens[$index]->equalsAny([':', ';'])) { if (0 === $ternariesCount) { break; } --$ternariesCount; } } return $index; } if (FCT::T_ENUM === $kind) { return $tokens->getNextTokenOfKind($index, ['=', ';']); } throw new \InvalidArgumentException(\sprintf('Unexpected case for type "%d".', $kind)); } private static function findDefaultOpen(Tokens $tokens, int $kind, int $index): int { if (\T_SWITCH === $kind) { return $tokens->getNextTokenOfKind($index, [':', ';']); } if (FCT::T_MATCH === $kind) { return $tokens->getNextTokenOfKind($index, [[\T_DOUBLE_ARROW]]); } throw new \InvalidArgumentException(\sprintf('Unexpected default for type "%d".', $kind)); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/AttributeAnalyzer.php
src/Tokenizer/Analyzer/AttributeAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\Preg; use PhpCsFixer\Tokenizer\Analyzer\Analysis\AttributeAnalysis; use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Tokens; /** * @internal * * @phpstan-import-type _AttributeItems from AttributeAnalysis * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class AttributeAnalyzer { private const TOKEN_KINDS_NOT_ALLOWED_IN_ATTRIBUTE = [ ';', '{', [\T_ATTRIBUTE], [\T_FUNCTION], [\T_OPEN_TAG], [\T_OPEN_TAG_WITH_ECHO], [\T_PRIVATE], [\T_PROTECTED], [\T_PUBLIC], [\T_RETURN], [\T_VARIABLE], [CT::T_ATTRIBUTE_CLOSE], ]; /** * Check if given index is an attribute declaration. */ public static function isAttribute(Tokens $tokens, int $index): bool { if ( !$tokens[$index]->isGivenKind(\T_STRING) // checked token is not a string || !$tokens->isAnyTokenKindsFound([FCT::T_ATTRIBUTE]) // no attributes in the tokens collection ) { return false; } $attributeStartIndex = $tokens->getPrevTokenOfKind($index, self::TOKEN_KINDS_NOT_ALLOWED_IN_ATTRIBUTE); if (!$tokens[$attributeStartIndex]->isGivenKind(\T_ATTRIBUTE)) { return false; } // now, between attribute start and the attribute candidate index cannot be more "(" than ")" $count = 0; for ($i = $attributeStartIndex + 1; $i < $index; ++$i) { if ($tokens[$i]->equals('(')) { ++$count; } elseif ($tokens[$i]->equals(')')) { --$count; } } return 0 === $count; } /** * Find all consecutive elements that start with #[ and end with ] and the attributes inside. * * @return non-empty-list<AttributeAnalysis> */ public static function collect(Tokens $tokens, int $index): array { if (!$tokens[$index]->isGivenKind(\T_ATTRIBUTE)) { throw new \InvalidArgumentException('Given index must point to an attribute.'); } // Rewind to first attribute in group while ($tokens[$prevIndex = $tokens->getPrevMeaningfulToken($index)]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $prevIndex); } $elements = []; $openingIndex = $index; do { $elements[] = $element = self::collectOne($tokens, $openingIndex); $openingIndex = $tokens->getNextMeaningfulToken($element->getEndIndex()); } while ($tokens[$openingIndex]->isGivenKind(\T_ATTRIBUTE)); return $elements; } /** * Find one element that starts with #[ and ends with ] and the attributes inside. */ public static function collectOne(Tokens $tokens, int $index): AttributeAnalysis { if (!$tokens[$index]->isGivenKind(\T_ATTRIBUTE)) { throw new \InvalidArgumentException('Given index must point to an attribute.'); } $startIndex = $index; $prevIndex = $tokens->getPrevMeaningfulToken($index); if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { // Include comments/PHPDoc if they are present $startIndex = $tokens->getNextNonWhitespace($prevIndex); } $closingIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); $endIndex = $tokens->getNextNonWhitespace($closingIndex); return new AttributeAnalysis( $startIndex, $endIndex - 1, $index, $closingIndex, self::collectAttributes($tokens, $index, $closingIndex), ); } public static function determineAttributeFullyQualifiedName(Tokens $tokens, string $name, int $index): string { if ('\\' === $name[0]) { return $name; } if (!$tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) { $index = $tokens->getNextTokenOfKind($index, [[\T_STRING], [\T_NS_SEPARATOR]]); } [$namespaceAnalysis, $namespaceUseAnalyses] = NamespacesAnalyzer::collectNamespaceAnalysis($tokens, $index); $namespace = $namespaceAnalysis->getFullName(); $firstTokenOfName = $tokens[$index]->getContent(); $namespaceUseAnalysis = $namespaceUseAnalyses[$firstTokenOfName] ?? false; if ($namespaceUseAnalysis instanceof NamespaceUseAnalysis) { $namespace = $namespaceUseAnalysis->getFullName(); if ($name === $firstTokenOfName) { return $namespace; } $name = substr((string) strstr($name, '\\'), 1); } return $namespace.'\\'.$name; } /** * @return _AttributeItems */ private static function collectAttributes(Tokens $tokens, int $index, int $closingIndex): array { $elements = []; do { $attributeStartIndex = $index + 1; $nameStartIndex = $tokens->getNextTokenOfKind($index, [[\T_STRING], [\T_NS_SEPARATOR]]); $index = $tokens->getNextTokenOfKind($attributeStartIndex, ['(', ',', [CT::T_ATTRIBUTE_CLOSE]]); $attributeName = $tokens->generatePartialCode($nameStartIndex, $tokens->getPrevMeaningfulToken($index)); // Find closing parentheses, we need to do this in case there's a comma inside the parentheses if ($tokens[$index]->equals('(')) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); $index = $tokens->getNextTokenOfKind($index, [',', [CT::T_ATTRIBUTE_CLOSE]]); } $elements[] = [ 'start' => $attributeStartIndex, 'end' => $index - 1, 'name' => $attributeName, ]; $nextIndex = $index; // In case there's a comma right before T_ATTRIBUTE_CLOSE if ($nextIndex < $closingIndex) { $nextIndex = $tokens->getNextMeaningfulToken($index); } } while ($nextIndex < $closingIndex); // End last element at newline if it exists and there's no trailing comma --$index; while ($tokens[$index]->isWhitespace()) { if (Preg::match('/\R/', $tokens[$index]->getContent())) { $lastElementKey = array_key_last($elements); $elements[$lastElementKey]['end'] = $index - 1; break; } --$index; } return $elements; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/PhpUnitTestCaseAnalyzer.php
src/Tokenizer/Analyzer/PhpUnitTestCaseAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\Preg; use PhpCsFixer\Tokenizer\Tokens; /** * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class PhpUnitTestCaseAnalyzer { /** * Returns an indices of PHPUnit classes in reverse appearance order. * Order is important - it's reverted, so if we inject tokens into collection, * we do it for bottom of file first, and then to the top of the file, so we * mitigate risk of not visiting whole collections (final indices). * * @return iterable<array{0: int, 1: int}> array of [int start, int end] indices from later to earlier classes */ public function findPhpUnitClasses(Tokens $tokens): iterable { for ($index = $tokens->count() - 1; $index > 0; --$index) { if (!$this->isPhpUnitClass($tokens, $index)) { continue; } $startIndex = $tokens->getNextTokenOfKind($index, ['{']); \assert(\is_int($startIndex)); $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startIndex); yield [$startIndex, $endIndex]; } } private function isPhpUnitClass(Tokens $tokens, int $index): bool { if (!$tokens[$index]->isGivenKind(\T_CLASS)) { return false; } $extendsIndex = $tokens->getNextTokenOfKind($index, ['{', [\T_EXTENDS]]); if (!$tokens[$extendsIndex]->isGivenKind(\T_EXTENDS)) { return false; } if (Preg::match('/(?:Test|TestCase)$/', $tokens[$index]->getContent())) { return true; } while (null !== $index = $tokens->getNextMeaningfulToken($index)) { if ($tokens[$index]->equals('{')) { break; // end of class signature } if (!$tokens[$index]->isGivenKind(\T_STRING)) { continue; // not part of extends nor part of implements; so continue } if (Preg::match('/(?:Test|TestCase)(?:Interface)?$/', $tokens[$index]->getContent())) { return true; } } return false; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/ArgumentsAnalyzer.php
src/Tokenizer/Analyzer/ArgumentsAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\Tokenizer\Analyzer\Analysis\ArgumentAnalysis; use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Tokens; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * @author Vladimir Reznichenko <kalessil@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ArgumentsAnalyzer { private const ARGUMENT_INFO_SKIP_TYPES = [\T_ELLIPSIS, \T_FINAL, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, FCT::T_READONLY, FCT::T_PRIVATE_SET, FCT::T_PROTECTED_SET, FCT::T_PUBLIC_SET]; /** * Count amount of parameters in a function/method reference. */ public function countArguments(Tokens $tokens, int $openParenthesis, int $closeParenthesis): int { return \count($this->getArguments($tokens, $openParenthesis, $closeParenthesis)); } /** * Returns start and end token indices of arguments. * * Returns an array with each key being the first token of an * argument and the value the last. Including non-function tokens * such as comments and white space tokens, but without the separation * tokens like '(', ',' and ')'. * * @return array<int, int> */ public function getArguments(Tokens $tokens, int $openParenthesis, int $closeParenthesis): array { $arguments = []; $firstSensibleToken = $tokens->getNextMeaningfulToken($openParenthesis); if ($tokens[$firstSensibleToken]->equals(')')) { return $arguments; } $paramContentIndex = $openParenthesis + 1; $argumentsStart = $paramContentIndex; for (; $paramContentIndex < $closeParenthesis; ++$paramContentIndex) { $token = $tokens[$paramContentIndex]; // skip nested (), [], {} constructs $blockDefinitionProbe = Tokens::detectBlockType($token); if (null !== $blockDefinitionProbe && true === $blockDefinitionProbe['isStart']) { $paramContentIndex = $tokens->findBlockEnd($blockDefinitionProbe['type'], $paramContentIndex); continue; } // if comma matched, increase arguments counter if ($token->equals(',')) { if ($tokens->getNextMeaningfulToken($paramContentIndex) === $closeParenthesis) { break; // trailing ',' in function call (PHP 7.3) } $arguments[$argumentsStart] = $paramContentIndex - 1; $argumentsStart = $paramContentIndex + 1; } } $arguments[$argumentsStart] = $paramContentIndex - 1; return $arguments; } public function getArgumentInfo(Tokens $tokens, int $argumentStart, int $argumentEnd): ArgumentAnalysis { $info = [ 'default' => null, 'name' => null, 'name_index' => null, 'type' => null, 'type_index_start' => null, 'type_index_end' => null, ]; $sawName = false; for ($index = $argumentStart; $index <= $argumentEnd; ++$index) { $token = $tokens[$index]; if ($token->isGivenKind(FCT::T_ATTRIBUTE)) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); continue; } if ( $token->isComment() || $token->isWhitespace() || $token->isGivenKind(self::ARGUMENT_INFO_SKIP_TYPES) || $token->equals('&') ) { continue; } if ($token->isGivenKind(\T_VARIABLE)) { $sawName = true; $info['name_index'] = $index; $info['name'] = $token->getContent(); continue; } if ($token->equals('=')) { continue; } if ($sawName) { $info['default'] .= $token->getContent(); } else { $info['type_index_start'] = ($info['type_index_start'] > 0) ? $info['type_index_start'] : $index; $info['type_index_end'] = $index; $info['type'] .= $token->getContent(); } } if (null === $info['name']) { $info['type'] = null; } return new ArgumentAnalysis( $info['name'], $info['name_index'], $info['default'], null !== $info['type'] ? new TypeAnalysis($info['type'], $info['type_index_start'], $info['type_index_end']) : 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/Tokenizer/Analyzer/CommentsAnalyzer.php
src/Tokenizer/Analyzer/CommentsAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\Preg; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @author Kuba Werłos <werlos@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class CommentsAnalyzer { private const TYPE_HASH = 1; private const TYPE_DOUBLE_SLASH = 2; private const TYPE_SLASH_ASTERISK = 3; private const SKIP_TYPES = [ \T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_VAR, \T_FUNCTION, \T_FN, \T_ABSTRACT, \T_CONST, \T_NAMESPACE, \T_REQUIRE, \T_REQUIRE_ONCE, \T_INCLUDE, \T_INCLUDE_ONCE, \T_FINAL, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, FCT::T_READONLY, FCT::T_PUBLIC_SET, FCT::T_PROTECTED_SET, FCT::T_PRIVATE_SET, ]; public function isHeaderComment(Tokens $tokens, int $index): bool { if (!$tokens[$index]->isGivenKind([\T_COMMENT, \T_DOC_COMMENT])) { throw new \InvalidArgumentException('Given index must point to a comment.'); } if (null === $tokens->getNextMeaningfulToken($index)) { return false; } $prevIndex = $tokens->getPrevNonWhitespace($index); if ($tokens[$prevIndex]->equals(';')) { $braceCloseIndex = $tokens->getPrevMeaningfulToken($prevIndex); if (!$tokens[$braceCloseIndex]->equals(')')) { return false; } $braceOpenIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $braceCloseIndex); $declareIndex = $tokens->getPrevMeaningfulToken($braceOpenIndex); if (!$tokens[$declareIndex]->isGivenKind(\T_DECLARE)) { return false; } $prevIndex = $tokens->getPrevNonWhitespace($declareIndex); } return $tokens[$prevIndex]->isGivenKind(\T_OPEN_TAG); } /** * Check if comment at given index precedes structural element. * * @see https://github.com/php-fig/fig-standards/blob/master/proposed/phpdoc.md#3-definitions */ public function isBeforeStructuralElement(Tokens $tokens, int $index): bool { $token = $tokens[$index]; if (!$token->isGivenKind([\T_COMMENT, \T_DOC_COMMENT])) { throw new \InvalidArgumentException('Given index must point to a comment.'); } $nextIndex = $this->getNextTokenIndex($tokens, $index); if (null === $nextIndex || $tokens[$nextIndex]->equals('}')) { return false; } if ($this->isStructuralElement($tokens, $nextIndex)) { return true; } if ($this->isValidControl($tokens, $token, $nextIndex)) { return true; } if ($this->isValidVariable($tokens, $nextIndex)) { return true; } if ($this->isValidVariableAssignment($tokens, $token, $nextIndex)) { return true; } if ($tokens[$nextIndex]->isGivenKind(CT::T_USE_TRAIT)) { return true; } return false; } /** * Check if comment at given index precedes return statement. */ public function isBeforeReturn(Tokens $tokens, int $index): bool { if (!$tokens[$index]->isGivenKind([\T_COMMENT, \T_DOC_COMMENT])) { throw new \InvalidArgumentException('Given index must point to a comment.'); } $nextIndex = $this->getNextTokenIndex($tokens, $index); if (null === $nextIndex || $tokens[$nextIndex]->equals('}')) { return false; } return $tokens[$nextIndex]->isGivenKind(\T_RETURN); } /** * Return array of indices that are part of a comment started at given index. * * @param int $index T_COMMENT index * * @return non-empty-list<int> */ public function getCommentBlockIndices(Tokens $tokens, int $index): array { if (!$tokens[$index]->isGivenKind(\T_COMMENT)) { throw new \InvalidArgumentException('Given index must point to a comment.'); } $commentType = $this->getCommentType($tokens[$index]->getContent()); $indices = [$index]; if (self::TYPE_SLASH_ASTERISK === $commentType) { return $indices; } $count = \count($tokens); ++$index; for (; $index < $count; ++$index) { if ($tokens[$index]->isComment()) { if ($commentType === $this->getCommentType($tokens[$index]->getContent())) { $indices[] = $index; continue; } break; } if (!$tokens[$index]->isWhitespace() || $this->getLineBreakCount($tokens, $index, $index + 1) > 1) { break; } } return $indices; } /** * @see https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md#3-definitions */ private function isStructuralElement(Tokens $tokens, int $index): bool { $token = $tokens[$index]; if ($token->isClassy() || $token->isGivenKind(self::SKIP_TYPES)) { return true; } if ($token->isGivenKind(\T_STRING)) { $content = strtolower($token->getContent()); return 'get' === $content || 'set' === $content; } if ($token->isGivenKind(\T_CASE)) { $enumParent = $tokens->getPrevTokenOfKind($index, [[FCT::T_ENUM], [\T_SWITCH]]); return $tokens[$enumParent]->isGivenKind(FCT::T_ENUM); } if ($token->isGivenKind(\T_STATIC)) { return !$tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(\T_DOUBLE_COLON); } return false; } /** * Checks control structures (for, foreach, if, switch, while) for correct docblock usage. * * @param Token $docsToken docs Token * @param int $controlIndex index of control structure Token */ private function isValidControl(Tokens $tokens, Token $docsToken, int $controlIndex): bool { if (!$tokens[$controlIndex]->isGivenKind([ \T_FOR, \T_FOREACH, \T_IF, \T_SWITCH, \T_WHILE, ])) { return false; } $openParenthesisIndex = $tokens->getNextMeaningfulToken($controlIndex); $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesisIndex); $docsContent = $docsToken->getContent(); for ($index = $openParenthesisIndex + 1; $index < $closeParenthesisIndex; ++$index) { $token = $tokens[$index]; if ( $token->isGivenKind(\T_VARIABLE) && str_contains($docsContent, $token->getContent()) ) { return true; } } return false; } /** * Checks variable assignments through `list()`, `print()` etc. calls for correct docblock usage. * * @param Token $docsToken docs Token * @param int $languageConstructIndex index of variable Token */ private function isValidVariableAssignment(Tokens $tokens, Token $docsToken, int $languageConstructIndex): bool { if (!$tokens[$languageConstructIndex]->isGivenKind([ \T_LIST, \T_PRINT, \T_ECHO, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, ])) { return false; } $endKind = $tokens[$languageConstructIndex]->isGivenKind(CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN) ? [CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE] : ')'; $endIndex = $tokens->getNextTokenOfKind($languageConstructIndex, [$endKind]); $docsContent = $docsToken->getContent(); for ($index = $languageConstructIndex + 1; $index < $endIndex; ++$index) { $token = $tokens[$index]; if ($token->isGivenKind(\T_VARIABLE) && str_contains($docsContent, $token->getContent())) { return true; } } return false; } /** * Checks variable assignments for correct docblock usage. * * @param int $index index of variable Token */ private function isValidVariable(Tokens $tokens, int $index): bool { if (!$tokens[$index]->isGivenKind(\T_VARIABLE)) { return false; } $nextIndex = $tokens->getNextMeaningfulToken($index); return $tokens[$nextIndex]->equalsAny([ '=', // arithmetic assignments [\T_PLUS_EQUAL, '+='], [\T_MINUS_EQUAL, '-='], [\T_MUL_EQUAL, '*='], [\T_DIV_EQUAL, '/='], [\T_MOD_EQUAL, '%='], [\T_POW_EQUAL, '**='], // bitwise assignments [\T_AND_EQUAL, '&='], [\T_OR_EQUAL, '|='], [\T_XOR_EQUAL, '^='], [\T_SL_EQUAL, '<<='], [\T_SR_EQUAL, '>>='], // other assignments [\T_COALESCE_EQUAL, '??='], [\T_CONCAT_EQUAL, '.='], ]); } 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 getNextTokenIndex(Tokens $tokens, int $startIndex): ?int { $nextIndex = $startIndex; do { $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); while (null !== $nextIndex && $tokens[$nextIndex]->isGivenKind(FCT::T_ATTRIBUTE)) { $nextIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $nextIndex); $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); } } while (null !== $nextIndex && $tokens[$nextIndex]->equals('(')); return $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/Tokenizer/Analyzer/SwitchAnalyzer.php
src/Tokenizer/Analyzer/SwitchAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis; use PhpCsFixer\Tokenizer\Tokens; /** * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class SwitchAnalyzer { /** @var array<non-empty-string, list<int>> */ private static array $cache = []; public static function belongsToSwitch(Tokens $tokens, int $index): bool { if (!$tokens[$index]->equals(':')) { return false; } $collectionHash = $tokens->getCollectionHash(); if (!\array_key_exists($collectionHash, self::$cache)) { self::$cache[$collectionHash] = self::getColonIndicesForSwitch(clone $tokens); } $arr = self::$cache[$collectionHash]; return \in_array($index, $arr, true); } /** * @return list<int> */ private static function getColonIndicesForSwitch(Tokens $tokens): array { $colonIndices = []; /** @var SwitchAnalysis $analysis */ foreach (ControlCaseStructuresAnalyzer::findControlStructures($tokens, [\T_SWITCH]) as $analysis) { if ($tokens[$analysis->getOpenIndex()]->equals(':')) { $colonIndices[] = $analysis->getOpenIndex(); } foreach ($analysis->getCases() as $case) { $colonIndices[] = $case->getColonIndex(); } $defaultAnalysis = $analysis->getDefaultAnalysis(); if (null !== $defaultAnalysis) { $colonIndices[] = $defaultAnalysis->getColonIndex(); } } return $colonIndices; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/DataProviderAnalyzer.php
src/Tokenizer/Analyzer/DataProviderAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\DocBlock\TypeExpression; use PhpCsFixer\Preg; use PhpCsFixer\Tokenizer\Analyzer\Analysis\DataProviderAnalysis; use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Tokens; /** * @author Kuba Werłos <werlos@gmail.com> * * @internal * * @phpstan-import-type _AttributeItem from \PhpCsFixer\Tokenizer\Analyzer\Analysis\AttributeAnalysis * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DataProviderAnalyzer { private const REGEX_CLASS = '(?:\\\?+'.TypeExpression::REGEX_IDENTIFIER .'(\\\\'.TypeExpression::REGEX_IDENTIFIER.')*+)'; /** * @return list<DataProviderAnalysis> */ public function getDataProviders(Tokens $tokens, int $startIndex, int $endIndex): array { $fullyQualifiedNameAnalyzer = new FullyQualifiedNameAnalyzer($tokens); $methods = $this->getMethods($tokens, $startIndex, $endIndex); $dataProviders = []; foreach ($methods as $methodIndex) { [$attributeIndex, $docCommentIndex] = $this->getAttributeIndexAndDocCommentIndices($tokens, $methodIndex); if (null !== $attributeIndex) { foreach (AttributeAnalyzer::collect($tokens, $attributeIndex) as $attributeAnalysis) { foreach ($attributeAnalysis->getAttributes() as $attribute) { $dataProviderNameIndex = $this->getDataProviderNameIndex($tokens, $fullyQualifiedNameAnalyzer, $attribute); if (null === $dataProviderNameIndex) { continue; } $dataProviders[substr($tokens[$dataProviderNameIndex]->getContent(), 1, -1)][] = [$dataProviderNameIndex, 0]; } } } if (null !== $docCommentIndex) { Preg::matchAll( '/@dataProvider\h+(('.self::REGEX_CLASS.'::)?'.TypeExpression::REGEX_IDENTIFIER.')/', $tokens[$docCommentIndex]->getContent(), $matches, \PREG_OFFSET_CAPTURE, ); foreach ($matches[1] as $k => [$matchName]) { \assert(isset($matches[0][$k])); $dataProviders[$matchName][] = [$docCommentIndex, $matches[0][$k][1]]; } } } $dataProviderAnalyses = []; foreach ($dataProviders as $dataProviderName => $dataProviderUsages) { $lowercaseDataProviderName = strtolower($dataProviderName); if (!\array_key_exists($lowercaseDataProviderName, $methods)) { continue; } $dataProviderAnalyses[$methods[$lowercaseDataProviderName]] = new DataProviderAnalysis( $tokens[$methods[$lowercaseDataProviderName]]->getContent(), $methods[$lowercaseDataProviderName], $dataProviderUsages, ); } ksort($dataProviderAnalyses); return array_values($dataProviderAnalyses); } /** * @return array<string, int> */ private function getMethods(Tokens $tokens, int $startIndex, int $endIndex): array { $functions = []; for ($index = $startIndex; $index < $endIndex; ++$index) { if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { continue; } $functionNameIndex = $tokens->getNextNonWhitespace($index); if (!$tokens[$functionNameIndex]->isGivenKind(\T_STRING)) { continue; } $functions[strtolower($tokens[$functionNameIndex]->getContent())] = $functionNameIndex; } return $functions; } /** * @return array{null|int, null|int} */ private function getAttributeIndexAndDocCommentIndices(Tokens $tokens, int $index): array { $attributeIndex = null; $docCommentIndex = null; while (!$tokens[$index]->equalsAny([';', '{', '}', [\T_OPEN_TAG]])) { --$index; if ($tokens[$index]->isGivenKind(FCT::T_ATTRIBUTE)) { $attributeIndex = $index; } elseif ($tokens[$index]->isGivenKind(\T_DOC_COMMENT)) { $docCommentIndex = $index; } } return [$attributeIndex, $docCommentIndex]; } /** * @param _AttributeItem $attribute */ private function getDataProviderNameIndex(Tokens $tokens, FullyQualifiedNameAnalyzer $fullyQualifiedNameAnalyzer, array $attribute): ?int { $fullyQualifiedName = $fullyQualifiedNameAnalyzer->getFullyQualifiedName( $attribute['name'], $tokens->getNextMeaningfulToken($attribute['start']), NamespaceUseAnalysis::TYPE_CLASS, ); if ('PHPUnit\Framework\Attributes\DataProvider' !== $fullyQualifiedName) { return null; } $closeParenthesisIndex = $tokens->getPrevTokenOfKind($attribute['end'] + 1, [')', [\T_ATTRIBUTE]]); if ($tokens[$closeParenthesisIndex]->isGivenKind(\T_ATTRIBUTE)) { return null; } $dataProviderNameIndex = $tokens->getPrevMeaningfulToken($closeParenthesisIndex); if (!$tokens[$dataProviderNameIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { return null; } $openParenthesisIndex = $tokens->getPrevMeaningfulToken($dataProviderNameIndex); if (!$tokens[$openParenthesisIndex]->equals('(')) { return null; } return $dataProviderNameIndex; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/FullyQualifiedNameAnalyzer.php
src/Tokenizer/Analyzer/FullyQualifiedNameAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; use PhpCsFixer\Tokenizer\Tokens; /** * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class FullyQualifiedNameAnalyzer { private Tokens $tokens; /** * @var list<NamespaceAnalysis> */ private array $namespaceAnalyses = []; /** * @var array<int, list<NamespaceUseAnalysis>> */ private array $namespaceUseAnalyses = []; public function __construct(Tokens $tokens) { $this->tokens = $tokens; } /** * @param NamespaceUseAnalysis::TYPE_* $importType */ public function getFullyQualifiedName(string $name, int $indexInNamespace, int $importType): string { return ltrim($this->getFullyQualifiedNameWithPossiblyLeadingSlash($name, $indexInNamespace, $importType), '\\'); } /** * @param NamespaceUseAnalysis::TYPE_* $importType */ private function getFullyQualifiedNameWithPossiblyLeadingSlash(string $name, int $indexInNamespace, int $importType): string { if ('\\' === $name[0]) { return $name; } $namespaceAnalysis = $this->getNamespaceAnalysis($indexInNamespace); $this->namespaceUseAnalyses[$namespaceAnalysis->getStartIndex()] ??= (new NamespaceUsesAnalyzer())->getDeclarationsInNamespace($this->tokens, $namespaceAnalysis); \assert(isset($this->namespaceUseAnalyses[$namespaceAnalysis->getStartIndex()])); $declarations = []; foreach ($this->namespaceUseAnalyses[$namespaceAnalysis->getStartIndex()] as $namespaceUseAnalysis) { if ($namespaceUseAnalysis->getType() !== $importType) { continue; } $declarations[strtolower($namespaceUseAnalysis->getShortName())] = $namespaceUseAnalysis->getFullName(); } $lowercaseName = strtolower($name); foreach ($declarations as $lowercaseShortName => $fullName) { if ($lowercaseName === $lowercaseShortName) { return $fullName; } if (!str_starts_with($lowercaseName, $lowercaseShortName.'\\')) { continue; } return $fullName.substr($name, \strlen($lowercaseShortName)); } return $namespaceAnalysis->getFullName().'\\'.$name; } private function getNamespaceAnalysis(int $index): NamespaceAnalysis { foreach ($this->namespaceAnalyses as $namespace) { if ($namespace->getScopeStartIndex() <= $index && $namespace->getScopeEndIndex() >= $index) { return $namespace; } } $namespace = (new NamespacesAnalyzer())->getNamespaceAt($this->tokens, $index); $this->namespaceAnalyses[] = $namespace; return $namespace; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/FunctionsAnalyzer.php
src/Tokenizer/Analyzer/FunctionsAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\Tokenizer\Analyzer\Analysis\ArgumentAnalysis; use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class FunctionsAnalyzer { private const POSSIBLE_KINDS = [ \T_DOUBLE_COLON, \T_FUNCTION, CT::T_NAMESPACE_OPERATOR, \T_NEW, CT::T_RETURN_REF, \T_STRING, \T_OBJECT_OPERATOR, FCT::T_NULLSAFE_OBJECT_OPERATOR, FCT::T_ATTRIBUTE]; /** * @var array{tokens: string, imports: list<NamespaceUseAnalysis>, declarations: list<int>} */ private array $functionsAnalysis = ['tokens' => '', 'imports' => [], 'declarations' => []]; /** * Important: risky because of the limited (file) scope of the tool. */ public function isGlobalFunctionCall(Tokens $tokens, int $index): bool { if (!$tokens[$index]->isGivenKind(\T_STRING)) { return false; } $openParenthesisIndex = $tokens->getNextMeaningfulToken($index); if (!$tokens[$openParenthesisIndex]->equals('(')) { return false; } $previousIsNamespaceSeparator = false; $prevIndex = $tokens->getPrevMeaningfulToken($index); if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { $previousIsNamespaceSeparator = true; $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); } if ($tokens[$prevIndex]->isGivenKind(self::POSSIBLE_KINDS)) { return false; } if ($tokens[$tokens->getNextMeaningfulToken($openParenthesisIndex)]->isGivenKind(CT::T_FIRST_CLASS_CALLABLE)) { return false; } if ($previousIsNamespaceSeparator) { return true; } $functionName = strtolower($tokens[$index]->getContent()); if ('set' === $functionName) { if (!$tokens[$prevIndex]->equalsAny([[CT::T_PROPERTY_HOOK_BRACE_OPEN], ';', '}'])) { return true; } $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesisIndex); $afterCloseParenthesisIndex = $tokens->getNextMeaningfulToken($closeParenthesisIndex); if ($tokens[$afterCloseParenthesisIndex]->equalsAny(['{', [\T_DOUBLE_ARROW]])) { return false; } } if ($tokens->isChanged() || $tokens->getCodeHash() !== $this->functionsAnalysis['tokens']) { $this->buildFunctionsAnalysis($tokens); } // figure out in which namespace we are $scopeStartIndex = 0; $scopeEndIndex = \count($tokens) - 1; $inGlobalNamespace = false; foreach ($tokens->getNamespaceDeclarations() as $declaration) { $scopeStartIndex = $declaration->getScopeStartIndex(); $scopeEndIndex = $declaration->getScopeEndIndex(); if ($index >= $scopeStartIndex && $index <= $scopeEndIndex) { $inGlobalNamespace = $declaration->isGlobalNamespace(); break; } } // check if the call is to a function declared in the same namespace as the call is done, // if the call is already in the global namespace than declared functions are in the same // global namespace and don't need checking if (!$inGlobalNamespace) { foreach ($this->functionsAnalysis['declarations'] as $functionNameIndex) { if ($functionNameIndex < $scopeStartIndex || $functionNameIndex > $scopeEndIndex) { continue; } if (strtolower($tokens[$functionNameIndex]->getContent()) === $functionName) { return false; } } } foreach ($this->functionsAnalysis['imports'] as $functionUse) { if ($functionUse->getStartIndex() < $scopeStartIndex || $functionUse->getEndIndex() > $scopeEndIndex) { continue; } if ($functionName !== strtolower($functionUse->getShortName())) { continue; } // global import like `use function \str_repeat;` return $functionUse->getShortName() === ltrim($functionUse->getFullName(), '\\'); } if (AttributeAnalyzer::isAttribute($tokens, $index)) { return false; } return true; } /** * @return array<string, ArgumentAnalysis> */ public function getFunctionArguments(Tokens $tokens, int $functionIndex): array { $argumentsStart = $tokens->getNextTokenOfKind($functionIndex, ['(']); $argumentsEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $argumentsStart); $argumentAnalyzer = new ArgumentsAnalyzer(); $arguments = []; foreach ($argumentAnalyzer->getArguments($tokens, $argumentsStart, $argumentsEnd) as $start => $end) { $argumentInfo = $argumentAnalyzer->getArgumentInfo($tokens, $start, $end); $arguments[$argumentInfo->getName()] = $argumentInfo; } return $arguments; } public function getFunctionReturnType(Tokens $tokens, int $methodIndex): ?TypeAnalysis { $argumentsStart = $tokens->getNextTokenOfKind($methodIndex, ['(']); $argumentsEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $argumentsStart); $typeColonIndex = $tokens->getNextMeaningfulToken($argumentsEnd); if (!$tokens[$typeColonIndex]->isGivenKind(CT::T_TYPE_COLON)) { return null; } $type = ''; $typeStartIndex = $tokens->getNextMeaningfulToken($typeColonIndex); $typeEndIndex = $typeStartIndex; $functionBodyStart = $tokens->getNextTokenOfKind($typeColonIndex, ['{', ';', [\T_DOUBLE_ARROW]]); for ($i = $typeStartIndex; $i < $functionBodyStart; ++$i) { if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) { continue; } $type .= $tokens[$i]->getContent(); $typeEndIndex = $i; } return new TypeAnalysis($type, $typeStartIndex, $typeEndIndex); } public function isTheSameClassCall(Tokens $tokens, int $index): bool { if (!$tokens->offsetExists($index)) { throw new \InvalidArgumentException(\sprintf('Token index %d does not exist.', $index)); } $operatorIndex = $tokens->getPrevMeaningfulToken($index); if (null === $operatorIndex) { return false; } if (!$tokens[$operatorIndex]->isObjectOperator() && !$tokens[$operatorIndex]->isGivenKind(\T_DOUBLE_COLON)) { return false; } $referenceIndex = $tokens->getPrevMeaningfulToken($operatorIndex); if (null === $referenceIndex) { return false; } if (!$tokens[$referenceIndex]->equalsAny([[\T_VARIABLE, '$this'], [\T_STRING, 'self'], [\T_STATIC, 'static']], false)) { return false; } return $tokens[$tokens->getNextMeaningfulToken($index)]->equals('('); } private function buildFunctionsAnalysis(Tokens $tokens): void { $this->functionsAnalysis = [ 'tokens' => $tokens->getCodeHash(), 'imports' => [], 'declarations' => [], ]; // find declarations if ($tokens->isTokenKindFound(\T_FUNCTION)) { $end = \count($tokens); for ($i = 0; $i < $end; ++$i) { // skip classy, we are looking for functions not methods if ($tokens[$i]->isGivenKind(Token::getClassyTokenKinds())) { $i = $tokens->getNextTokenOfKind($i, ['(', '{']); if ($tokens[$i]->equals('(')) { // anonymous class $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $i); $i = $tokens->getNextTokenOfKind($i, ['{']); } $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $i); continue; } if (!$tokens[$i]->isGivenKind(\T_FUNCTION)) { continue; } $i = $tokens->getNextMeaningfulToken($i); if ($tokens[$i]->isGivenKind(CT::T_RETURN_REF)) { $i = $tokens->getNextMeaningfulToken($i); } if (!$tokens[$i]->isGivenKind(\T_STRING)) { continue; } $this->functionsAnalysis['declarations'][] = $i; } } // find imported functions $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer(); if ($tokens->isTokenKindFound(CT::T_FUNCTION_IMPORT)) { $declarations = $namespaceUsesAnalyzer->getDeclarationsFromTokens($tokens); foreach ($declarations as $declaration) { if ($declaration->isFunction()) { $this->functionsAnalysis['imports'][] = $declaration; } } } } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/FixerAnnotationAnalyzer.php
src/Tokenizer/Analyzer/FixerAnnotationAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\Preg; use PhpCsFixer\Tokenizer\Tokens; /** * Extracts @php-cs-fixer-* annotations from the given Tokens collection. * * Those annotations are controlling low-level PHP CS Fixer internal * are looked for only at the top and at the bottom of the file. * Any syntax of comment is allowed. * * @internal * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class FixerAnnotationAnalyzer { /** * @return array<string, list<string>> */ public function find(Tokens $tokens): array { $comments = []; $annotations = []; $count = $tokens->count(); $index = 0; for (0; $index < $count; ++$index) { $token = $tokens[$index]; if ($token->isGivenKind([ \T_OPEN_TAG, \T_OPEN_TAG_WITH_ECHO, \T_WHITESPACE, ]) || $token->equals(';')) { continue; } if ($token->isGivenKind(\T_DECLARE)) { $nextIndex = $tokens->getNextMeaningfulToken($index); $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex); continue; } if ($token->isComment()) { $comments[] = $token->getContent(); continue; } break; } for ($indexBackwards = $count - 1; $indexBackwards > $index; --$indexBackwards) { $token = $tokens[$indexBackwards]; if ($token->isGivenKind([ \T_CLOSE_TAG, \T_WHITESPACE, ]) || $token->equals(';')) { continue; } if ($token->isComment()) { $comments[] = $token->getContent(); continue; } break; } Preg::matchAll( '/^\h*[*\/]+\h+@(php-cs-fixer-\w+\h+(?:@?[\w\/,])+)/m', implode("\n", $comments), $matches, ); foreach ($matches[1] as $match) { $matchParts = explode(' ', $match, 2); \assert(2 === \count($matchParts)); $annotations[$matchParts[0]] ??= []; array_push($annotations[$matchParts[0]], ...explode(',', $matchParts[1])); } foreach ($annotations as $annotation => $vals) { $duplicates = array_keys( array_filter( array_count_values($vals), static fn (int $c): bool => $c > 1, ), ); if (0 !== \count($duplicates)) { throw new \RuntimeException(\sprintf('Duplicated values found for annotation "@%s": "%s".', $annotation, implode('", "', $duplicates))); } sort($vals); $annotations[$annotation] = $vals; } return $annotations; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/NamespaceUsesAnalyzer.php
src/Tokenizer/Analyzer/NamespaceUsesAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Tokens; use PhpCsFixer\Tokenizer\TokensAnalyzer; /** * @author VeeWee <toonverwerft@gmail.com> * @author Greg Korba <greg@codito.dev> * * @internal * * @TODO Drop `allowMultiUses` opt-in flag when all fixers are updated and can handle multi-use statements. * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NamespaceUsesAnalyzer { /** * @return list<NamespaceUseAnalysis> */ public function getDeclarationsFromTokens(Tokens $tokens, bool $allowMultiUses = false): array { $tokenAnalyzer = new TokensAnalyzer($tokens); $useIndices = $tokenAnalyzer->getImportUseIndexes(); return $this->getDeclarations($tokens, $useIndices, $allowMultiUses); } /** * @return list<NamespaceUseAnalysis> */ public function getDeclarationsInNamespace(Tokens $tokens, NamespaceAnalysis $namespace, bool $allowMultiUses = false): array { $namespaceUses = []; foreach ($this->getDeclarationsFromTokens($tokens, $allowMultiUses) as $namespaceUse) { if ($namespaceUse->getStartIndex() >= $namespace->getScopeStartIndex() && $namespaceUse->getStartIndex() <= $namespace->getScopeEndIndex()) { $namespaceUses[] = $namespaceUse; } } return $namespaceUses; } /** * @param list<int> $useIndices * * @return list<NamespaceUseAnalysis> */ private function getDeclarations(Tokens $tokens, array $useIndices, bool $allowMultiUses = false): array { $uses = []; foreach ($useIndices as $index) { $endIndex = $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]); $declarations = $this->parseDeclarations($index, $endIndex, $tokens); if (false === $allowMultiUses) { $declarations = array_filter($declarations, static fn (NamespaceUseAnalysis $declaration) => !$declaration->isInMulti()); } if ([] !== $declarations) { $uses = array_merge($uses, $declarations); } } return $uses; } /** * @return list<NamespaceUseAnalysis> */ private function parseDeclarations(int $startIndex, int $endIndex, Tokens $tokens): array { $type = $this->determineImportType($tokens, $startIndex); $potentialMulti = $tokens->getNextTokenOfKind($startIndex, [',', [CT::T_GROUP_IMPORT_BRACE_OPEN]]); $multi = null !== $potentialMulti && $potentialMulti < $endIndex; $index = $tokens->getNextTokenOfKind($startIndex, [[\T_STRING], [\T_NS_SEPARATOR]]); $imports = []; while (null !== $index && $index <= $endIndex) { $qualifiedName = $this->getNearestQualifiedName($tokens, $index); $token = $tokens[$qualifiedName['afterIndex']]; if ($token->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { $groupStart = $groupIndex = $qualifiedName['afterIndex']; $groupEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_GROUP_IMPORT_BRACE, $groupStart); while ($groupIndex < $groupEnd) { $chunkStart = $tokens->getNextMeaningfulToken($groupIndex); // Finish parsing on trailing comma (no more chunks there) if ($tokens[$chunkStart]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)) { break; } $groupQualifiedName = $this->getNearestQualifiedName($tokens, $chunkStart); \assert('' !== $groupQualifiedName['fullName']); \assert('' !== $groupQualifiedName['shortName']); $imports[] = new NamespaceUseAnalysis( $type, $qualifiedName['fullName'].$groupQualifiedName['fullName'], $groupQualifiedName['shortName'], $groupQualifiedName['aliased'], true, $startIndex, $endIndex, $chunkStart, $tokens->getPrevMeaningfulToken($groupQualifiedName['afterIndex']), ); $groupIndex = $groupQualifiedName['afterIndex']; } $index = $groupIndex; } elseif ($token->equalsAny([',', ';', [\T_CLOSE_TAG]])) { $previousToken = $tokens->getPrevMeaningfulToken($qualifiedName['afterIndex']); if (!$tokens[$previousToken]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)) { \assert('' !== $qualifiedName['fullName']); \assert('' !== $qualifiedName['shortName']); $imports[] = new NamespaceUseAnalysis( $type, $qualifiedName['fullName'], $qualifiedName['shortName'], $qualifiedName['aliased'], $multi, $startIndex, $endIndex, $multi ? $index : null, $multi ? $previousToken : null, ); } $index = $qualifiedName['afterIndex']; } $index = $tokens->getNextMeaningfulToken($index); } return $imports; } /** * @return NamespaceUseAnalysis::TYPE_* */ private function determineImportType(Tokens $tokens, int $startIndex): int { $potentialType = $tokens[$tokens->getNextMeaningfulToken($startIndex)]; if ($potentialType->isGivenKind(CT::T_FUNCTION_IMPORT)) { return NamespaceUseAnalysis::TYPE_FUNCTION; } if ($potentialType->isGivenKind(CT::T_CONST_IMPORT)) { return NamespaceUseAnalysis::TYPE_CONSTANT; } return NamespaceUseAnalysis::TYPE_CLASS; } /** * @return array{fullName: string, shortName: string, aliased: bool, afterIndex: int} */ private function getNearestQualifiedName(Tokens $tokens, int $index): array { $fullName = $shortName = ''; $aliased = false; while (null !== $index) { $token = $tokens[$index]; if ($token->isGivenKind(\T_STRING)) { $shortName = $token->getContent(); if (!$aliased) { $fullName .= $shortName; } } elseif ($token->isGivenKind(\T_NS_SEPARATOR)) { $fullName .= $token->getContent(); } elseif ($token->isGivenKind(\T_AS)) { $aliased = true; } elseif ($token->equalsAny([ ',', ';', [CT::T_GROUP_IMPORT_BRACE_OPEN], [CT::T_GROUP_IMPORT_BRACE_CLOSE], [\T_CLOSE_TAG], ])) { break; } $index = $tokens->getNextMeaningfulToken($index); } return [ 'fullName' => $fullName, 'shortName' => $shortName, 'aliased' => $aliased, 'afterIndex' => $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/Tokenizer/Analyzer/ClassyAnalyzer.php
src/Tokenizer/Analyzer/ClassyAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Tokens; /** * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ClassyAnalyzer { public function isClassyInvocation(Tokens $tokens, int $index): bool { $token = $tokens[$index]; if (!$token->isGivenKind(\T_STRING)) { throw new \LogicException(\sprintf('No T_STRING at given index %d, got "%s".', $index, $tokens[$index]->getName())); } if ((new Analysis\TypeAnalysis($token->getContent()))->isReservedType()) { return false; } $next = $tokens->getNextMeaningfulToken($index); $nextToken = $tokens[$next]; if ($nextToken->isGivenKind(\T_NS_SEPARATOR)) { return false; } if ($nextToken->isGivenKind([\T_DOUBLE_COLON, \T_ELLIPSIS, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, \T_VARIABLE])) { return true; } $prev = $tokens->getPrevMeaningfulToken($index); while ($tokens[$prev]->isGivenKind([CT::T_NAMESPACE_OPERATOR, \T_NS_SEPARATOR, \T_STRING])) { $prev = $tokens->getPrevMeaningfulToken($prev); } $prevToken = $tokens[$prev]; if ($prevToken->isGivenKind([\T_EXTENDS, \T_INSTANCEOF, \T_INSTEADOF, \T_IMPLEMENTS, \T_NEW, CT::T_NULLABLE_TYPE, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, CT::T_TYPE_COLON, CT::T_USE_TRAIT])) { return true; } if (\PHP_VERSION_ID >= 8_00_00 && $nextToken->equals(')') && $prevToken->equals('(') && $tokens[$tokens->getPrevMeaningfulToken($prev)]->isGivenKind(\T_CATCH)) { return true; } if (AttributeAnalyzer::isAttribute($tokens, $index)) { return true; } // `Foo & $bar` could be: // - function reference parameter: function baz(Foo & $bar) {} // - bit operator: $x = Foo & $bar; if ($nextToken->equals('&') && $tokens[$tokens->getNextMeaningfulToken($next)]->isGivenKind(\T_VARIABLE)) { $checkIndex = $tokens->getPrevTokenOfKind($prev + 1, [';', '{', '}', [\T_FUNCTION], [\T_OPEN_TAG], [\T_OPEN_TAG_WITH_ECHO]]); return $tokens[$checkIndex]->isGivenKind(\T_FUNCTION); } if (!$prevToken->equals(',')) { return false; } do { $prev = $tokens->getPrevMeaningfulToken($prev); } while ($tokens[$prev]->equalsAny([',', [\T_NS_SEPARATOR], [\T_STRING], [CT::T_NAMESPACE_OPERATOR]])); return $tokens[$prev]->isGivenKind([\T_IMPLEMENTS, CT::T_USE_TRAIT]); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/RangeAnalyzer.php
src/Tokenizer/Analyzer/RangeAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Tokens; /** * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class RangeAnalyzer { private function __construct() { // cannot create instance of util. class } /** * Meaningful compare of tokens within ranges. * * @param array{start: int, end: int} $range1 * @param array{start: int, end: int} $range2 */ public static function rangeEqualsRange(Tokens $tokens, array $range1, array $range2): bool { $leftStart = $range1['start']; $leftEnd = $range1['end']; if ($tokens[$leftStart]->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { $leftStart = $tokens->getNextMeaningfulToken($leftStart); } while ($tokens[$leftStart]->equals('(') && $tokens[$leftEnd]->equals(')')) { $leftStart = $tokens->getNextMeaningfulToken($leftStart); $leftEnd = $tokens->getPrevMeaningfulToken($leftEnd); } $rightStart = $range2['start']; $rightEnd = $range2['end']; if ($tokens[$rightStart]->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { $rightStart = $tokens->getNextMeaningfulToken($rightStart); } while ($tokens[$rightStart]->equals('(') && $tokens[$rightEnd]->equals(')')) { $rightStart = $tokens->getNextMeaningfulToken($rightStart); $rightEnd = $tokens->getPrevMeaningfulToken($rightEnd); } $arrayOpenTypes = ['[', [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN]]; $arrayCloseTypes = [']', [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE]]; while (true) { $leftToken = $tokens[$leftStart]; $rightToken = $tokens[$rightStart]; if ( !$leftToken->equals($rightToken) && !($leftToken->equalsAny($arrayOpenTypes) && $rightToken->equalsAny($arrayOpenTypes)) && !($leftToken->equalsAny($arrayCloseTypes) && $rightToken->equalsAny($arrayCloseTypes)) ) { return false; } $leftStart = $tokens->getNextMeaningfulToken($leftStart); $rightStart = $tokens->getNextMeaningfulToken($rightStart); $reachedLeftEnd = null === $leftStart || $leftStart > $leftEnd; // reached end left or moved over $reachedRightEnd = null === $rightStart || $rightStart > $rightEnd; // reached end right or moved over if (!$reachedLeftEnd && !$reachedRightEnd) { continue; } return $reachedLeftEnd && $reachedRightEnd; } } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/WhitespacesAnalyzer.php
src/Tokenizer/Analyzer/WhitespacesAnalyzer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer; use PhpCsFixer\Tokenizer\Tokens; /** * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class WhitespacesAnalyzer { public static function detectIndent(Tokens $tokens, int $index): string { while (true) { $whitespaceIndex = $tokens->getPrevTokenOfKind($index, [[\T_WHITESPACE]]); if (null === $whitespaceIndex) { return ''; } $whitespaceToken = $tokens[$whitespaceIndex]; if (str_contains($whitespaceToken->getContent(), "\n")) { break; } $prevToken = $tokens[$whitespaceIndex - 1]; if ($prevToken->isGivenKind([\T_OPEN_TAG, \T_COMMENT]) && "\n" === substr($prevToken->getContent(), -1)) { break; } $index = $whitespaceIndex; } $explodedContent = explode("\n", $whitespaceToken->getContent()); return end($explodedContent); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/Analysis/AbstractControlCaseStructuresAnalysis.php
src/Tokenizer/Analyzer/Analysis/AbstractControlCaseStructuresAnalysis.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; /** * @readonly * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ abstract class AbstractControlCaseStructuresAnalysis { private int $index; private int $open; private int $close; public function __construct(int $index, int $open, int $close) { $this->index = $index; $this->open = $open; $this->close = $close; } public function getIndex(): int { return $this->index; } public function getOpenIndex(): int { return $this->open; } public function getCloseIndex(): int { return $this->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/Tokenizer/Analyzer/Analysis/EnumAnalysis.php
src/Tokenizer/Analyzer/Analysis/EnumAnalysis.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; /** * @readonly * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class EnumAnalysis extends AbstractControlCaseStructuresAnalysis { /** * @var list<CaseAnalysis> */ private array $cases; /** * @param list<CaseAnalysis> $cases */ public function __construct(int $index, int $open, int $close, array $cases) { parent::__construct($index, $open, $close); $this->cases = $cases; } /** * @return list<CaseAnalysis> */ public function getCases(): array { return $this->cases; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/Analysis/SwitchAnalysis.php
src/Tokenizer/Analyzer/Analysis/SwitchAnalysis.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; /** * @readonly * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class SwitchAnalysis extends AbstractControlCaseStructuresAnalysis { /** * @var list<CaseAnalysis> */ private array $cases; private ?DefaultAnalysis $defaultAnalysis; /** * @param list<CaseAnalysis> $cases */ public function __construct(int $index, int $open, int $close, array $cases, ?DefaultAnalysis $defaultAnalysis) { parent::__construct($index, $open, $close); $this->cases = $cases; $this->defaultAnalysis = $defaultAnalysis; } /** * @return list<CaseAnalysis> */ public function getCases(): array { return $this->cases; } public function getDefaultAnalysis(): ?DefaultAnalysis { return $this->defaultAnalysis; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/Analysis/NamespaceAnalysis.php
src/Tokenizer/Analyzer/Analysis/NamespaceAnalysis.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; /** * @readonly * * @TODO v4: previously was mareked as internal - yet it leaked to public interface of `DocBlock`, consider making it so again. * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NamespaceAnalysis { /** * The fully qualified namespace name. */ private string $fullName; /** * The short version of the namespace. */ private string $shortName; /** * The start index of the namespace declaration in the analysed Tokens. */ private int $startIndex; /** * The end index of the namespace declaration in the analysed Tokens. */ private int $endIndex; /** * The start index of the scope of the namespace in the analysed Tokens. */ private int $scopeStartIndex; /** * The end index of the scope of the namespace in the analysed Tokens. */ private int $scopeEndIndex; /** * @internal */ public function __construct(string $fullName, string $shortName, int $startIndex, int $endIndex, int $scopeStartIndex, int $scopeEndIndex) { $this->fullName = $fullName; $this->shortName = $shortName; $this->startIndex = $startIndex; $this->endIndex = $endIndex; $this->scopeStartIndex = $scopeStartIndex; $this->scopeEndIndex = $scopeEndIndex; } public function getFullName(): string { return $this->fullName; } public function getShortName(): string { return $this->shortName; } public function getStartIndex(): int { return $this->startIndex; } public function getEndIndex(): int { return $this->endIndex; } public function getScopeStartIndex(): int { return $this->scopeStartIndex; } public function getScopeEndIndex(): int { return $this->scopeEndIndex; } public function isGlobalNamespace(): bool { return '' === $this->getFullName(); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/Analysis/MatchAnalysis.php
src/Tokenizer/Analyzer/Analysis/MatchAnalysis.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; /** * @readonly * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class MatchAnalysis extends AbstractControlCaseStructuresAnalysis { private ?DefaultAnalysis $defaultAnalysis; public function __construct(int $index, int $open, int $close, ?DefaultAnalysis $defaultAnalysis) { parent::__construct($index, $open, $close); $this->defaultAnalysis = $defaultAnalysis; } public function getDefaultAnalysis(): ?DefaultAnalysis { return $this->defaultAnalysis; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/Analysis/ArgumentAnalysis.php
src/Tokenizer/Analyzer/Analysis/ArgumentAnalysis.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; /** * @readonly * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ArgumentAnalysis { /** * The name of the argument. */ private ?string $name; /** * The index where the name is located in the supplied Tokens object. */ private ?int $nameIndex; /** * The default value of the argument. */ private ?string $default; /** * The type analysis of the argument. */ private ?TypeAnalysis $typeAnalysis; public function __construct(?string $name, ?int $nameIndex, ?string $default, ?TypeAnalysis $typeAnalysis = null) { $this->name = $name; $this->nameIndex = $nameIndex; $this->default = $default ?? null; $this->typeAnalysis = $typeAnalysis ?? null; } public function getDefault(): ?string { return $this->default; } public function hasDefault(): bool { return null !== $this->default; } public function getName(): ?string { return $this->name; } public function getNameIndex(): ?int { return $this->nameIndex; } public function getTypeAnalysis(): ?TypeAnalysis { return $this->typeAnalysis; } public function hasTypeAnalysis(): bool { return null !== $this->typeAnalysis; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/Analysis/AttributeAnalysis.php
src/Tokenizer/Analyzer/Analysis/AttributeAnalysis.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; /** * @readonly * * @internal * * @phpstan-type _AttributeItem array{start: int, end: int, name: string} * @phpstan-type _AttributeItems non-empty-list<_AttributeItem> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class AttributeAnalysis { private int $startIndex; private int $endIndex; private int $openingBracketIndex; private int $closingBracketIndex; /** * @var _AttributeItems */ private array $attributes; /** * @param _AttributeItems $attributes */ public function __construct(int $startIndex, int $endIndex, int $openingBracketIndex, int $closingBracketIndex, array $attributes) { $this->startIndex = $startIndex; $this->endIndex = $endIndex; $this->openingBracketIndex = $openingBracketIndex; $this->closingBracketIndex = $closingBracketIndex; $this->attributes = $attributes; } public function getStartIndex(): int { return $this->startIndex; } public function getEndIndex(): int { return $this->endIndex; } public function getOpeningBracketIndex(): int { return $this->openingBracketIndex; } public function getClosingBracketIndex(): int { return $this->closingBracketIndex; } /** * @return _AttributeItems */ public function getAttributes(): array { return $this->attributes; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/Analysis/CaseAnalysis.php
src/Tokenizer/Analyzer/Analysis/CaseAnalysis.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; /** * @author Kuba Werłos <werlos@gmail.com> * * @readonly * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class CaseAnalysis { private int $index; private int $colonIndex; public function __construct(int $index, int $colonIndex) { $this->index = $index; $this->colonIndex = $colonIndex; } public function getIndex(): int { return $this->index; } public function getColonIndex(): int { return $this->colonIndex; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/Analysis/TypeAnalysis.php
src/Tokenizer/Analyzer/Analysis/TypeAnalysis.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; /** * @readonly * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class TypeAnalysis { /** * This list contains soft and hard reserved types that can be used or will be used by PHP at some point. * * More info: * * @var non-empty-list<string> * * @see https://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration.types * @see https://php.net/manual/en/reserved.other-reserved-words.php */ private const RESERVED_TYPES = [ 'array', 'bool', 'callable', 'false', 'float', 'int', 'iterable', 'list', 'mixed', 'never', 'null', 'object', 'parent', 'resource', 'self', 'static', 'string', 'true', 'void', ]; private string $name; private ?int $startIndex; private ?int $endIndex; private bool $nullable; /** * @param ($startIndex is null ? null : int) $endIndex */ public function __construct(string $name, ?int $startIndex = null, ?int $endIndex = null) { if (str_starts_with($name, '?')) { $this->name = substr($name, 1); $this->nullable = true; } elseif (\PHP_VERSION_ID >= 8_00_00) { $this->name = $name; $this->nullable = \in_array('null', array_map('trim', explode('|', strtolower($name))), true); } else { $this->name = $name; $this->nullable = false; } $this->startIndex = $startIndex; $this->endIndex = $endIndex; } public function getName(): string { return $this->name; } public function getStartIndex(): int { if (null === $this->startIndex) { throw new \RuntimeException('TypeAnalysis: no start index.'); } return $this->startIndex; } public function getEndIndex(): int { if (null === $this->endIndex) { throw new \RuntimeException('TypeAnalysis: no end index.'); } return $this->endIndex; } public function isReservedType(): bool { return \in_array(strtolower($this->name), self::RESERVED_TYPES, true); } public function isNullable(): bool { return $this->nullable; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/Analysis/DataProviderAnalysis.php
src/Tokenizer/Analyzer/Analysis/DataProviderAnalysis.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; /** * @internal * * @readonly * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DataProviderAnalysis { private string $name; private int $nameIndex; /** @var non-empty-list<array{int, int}> */ private array $usageIndices; /** * @param non-empty-list<array{int, int}> $usageIndices */ public function __construct(string $name, int $nameIndex, array $usageIndices) { if ([] === $usageIndices || !array_is_list($usageIndices)) { throw new \InvalidArgumentException( 'Parameter "usageIndices" should be a non-empty-list.', ); } $this->name = $name; $this->nameIndex = $nameIndex; $this->usageIndices = $usageIndices; } public function getName(): string { return $this->name; } public function getNameIndex(): int { return $this->nameIndex; } /** * @return non-empty-list<array{int, int}> */ public function getUsageIndices(): array { return $this->usageIndices; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysis.php
src/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysis.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; /** * @readonly * * @TODO v4: previously was mareked as internal - yet it leaked to public interface of `DocBlock`, consider making it so again. * * @phpstan-type _ImportType 'class'|'constant'|'function' * * @author VeeWee <toonverwerft@gmail.com> * @author Greg Korba <greg@codito.dev> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NamespaceUseAnalysis { public const TYPE_CLASS = 1; // "classy" could be class, interface or trait public const TYPE_FUNCTION = 2; public const TYPE_CONSTANT = 3; /** * The fully qualified use namespace. * * @var non-empty-string */ private string $fullName; /** * The short version of use namespace or the alias name in case of aliased use statements. * * @var non-empty-string */ private string $shortName; /** * Is the use statement part of multi-use (`use A, B, C;`, `use A\{B, C};`)? */ private bool $isInMulti; /** * Is the use statement being aliased? */ private bool $isAliased; /** * The start index of the namespace declaration in the analysed Tokens. */ private int $startIndex; /** * The end index of the namespace declaration in the analysed Tokens. */ private int $endIndex; /** * The start index of the single import in the multi-use statement. */ private ?int $chunkStartIndex; /** * The end index of the single import in the multi-use statement. */ private ?int $chunkEndIndex; /** * The type of import: class, function or constant. * * @var self::TYPE_* */ private int $type; /** * @param self::TYPE_* $type * @param non-empty-string $fullName * @param non-empty-string $shortName * * @internal */ public function __construct( int $type, string $fullName, string $shortName, bool $isAliased, bool $isInMulti, int $startIndex, int $endIndex, ?int $chunkStartIndex = null, ?int $chunkEndIndex = null ) { if (true === $isInMulti && (null === $chunkStartIndex || null === $chunkEndIndex)) { throw new \LogicException('Chunk start and end index must be set when the import is part of a multi-use statement.'); } $this->type = $type; $this->fullName = $fullName; $this->shortName = $shortName; $this->isAliased = $isAliased; $this->isInMulti = $isInMulti; $this->startIndex = $startIndex; $this->endIndex = $endIndex; $this->chunkStartIndex = $chunkStartIndex; $this->chunkEndIndex = $chunkEndIndex; } /** * @return non-empty-string */ public function getFullName(): string { return $this->fullName; } /** * @return non-empty-string */ public function getShortName(): string { return $this->shortName; } public function isAliased(): bool { return $this->isAliased; } public function isInMulti(): bool { return $this->isInMulti; } public function getStartIndex(): int { return $this->startIndex; } public function getEndIndex(): int { return $this->endIndex; } public function getChunkStartIndex(): ?int { return $this->chunkStartIndex; } public function getChunkEndIndex(): ?int { return $this->chunkEndIndex; } /** * @return self::TYPE_* */ public function getType(): int { return $this->type; } /** * @return _ImportType */ public function getHumanFriendlyType(): string { return [ self::TYPE_CLASS => 'class', self::TYPE_FUNCTION => 'function', self::TYPE_CONSTANT => 'constant', ][$this->type]; } public function isClass(): bool { return self::TYPE_CLASS === $this->type; } public function isFunction(): bool { return self::TYPE_FUNCTION === $this->type; } public function isConstant(): bool { return self::TYPE_CONSTANT === $this->type; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Analyzer/Analysis/DefaultAnalysis.php
src/Tokenizer/Analyzer/Analysis/DefaultAnalysis.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; /** * @readonly * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DefaultAnalysis { private int $index; private int $colonIndex; public function __construct(int $index, int $colonIndex) { $this->index = $index; $this->colonIndex = $colonIndex; } public function getIndex(): int { return $this->index; } public function getColonIndex(): int { return $this->colonIndex; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Transformer/BraceTransformer.php
src/Tokenizer/Transformer/BraceTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTransformer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Transform discriminate overloaded curly braces tokens. * * Performed transformations: * - closing `}` for T_CURLY_OPEN into CT::T_CURLY_CLOSE, * - closing `}` for T_DOLLAR_OPEN_CURLY_BRACES into CT::T_DOLLAR_CLOSE_CURLY_BRACES, * - in `$foo->{$bar}` into CT::T_DYNAMIC_PROP_BRACE_OPEN and CT::T_DYNAMIC_PROP_BRACE_CLOSE, * - in `${$foo}` into CT::T_DYNAMIC_VAR_BRACE_OPEN and CT::T_DYNAMIC_VAR_BRACE_CLOSE, * - in `$array{$index}` into CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN and CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE, * - in `use some\a\{ClassA, ClassB, ClassC as C}` into CT::T_GROUP_IMPORT_BRACE_OPEN, CT::T_GROUP_IMPORT_BRACE_CLOSE, * - in `class PropertyHooks { public string $bar _{_ set(string $value) { } _}_` into CT::T_PROPERTY_HOOK_BRACE_OPEN, CT::T_PROPERTY_HOOK_BRACE_CLOSE. * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class BraceTransformer extends AbstractTransformer { public function getRequiredPhpVersionId(): int { return 5_00_00; } public function process(Tokens $tokens, Token $token, int $index): void { $this->transformIntoCurlyCloseBrace($tokens, $index); $this->transformIntoDollarCloseBrace($tokens, $index); $this->transformIntoDynamicPropBraces($tokens, $index); $this->transformIntoDynamicVarBraces($tokens, $index); $this->transformIntoPropertyHookBraces($tokens, $index); $this->transformIntoCurlyIndexBraces($tokens, $index); $this->transformIntoGroupUseBraces($tokens, $index); $this->transformIntoDynamicClassConstantFetchBraces($tokens, $index); } public function getCustomTokens(): array { return [ CT::T_CURLY_CLOSE, CT::T_DOLLAR_CLOSE_CURLY_BRACES, CT::T_DYNAMIC_PROP_BRACE_OPEN, CT::T_DYNAMIC_PROP_BRACE_CLOSE, CT::T_DYNAMIC_VAR_BRACE_OPEN, CT::T_DYNAMIC_VAR_BRACE_CLOSE, CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE, CT::T_GROUP_IMPORT_BRACE_OPEN, CT::T_GROUP_IMPORT_BRACE_CLOSE, CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_OPEN, CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_CLOSE, CT::T_PROPERTY_HOOK_BRACE_OPEN, CT::T_PROPERTY_HOOK_BRACE_CLOSE, ]; } /** * Transform closing `}` for T_CURLY_OPEN into CT::T_CURLY_CLOSE. * * This should be done at very beginning of curly braces transformations. */ private function transformIntoCurlyCloseBrace(Tokens $tokens, int $index): void { $token = $tokens[$index]; if (!$token->isGivenKind(\T_CURLY_OPEN)) { return; } $level = 1; do { ++$index; if ($tokens[$index]->equals('{') || $tokens[$index]->isGivenKind(\T_CURLY_OPEN)) { // we count all kind of { ++$level; } elseif ($tokens[$index]->equals('}')) { // we count all kind of } --$level; } } while (0 < $level); $tokens[$index] = new Token([CT::T_CURLY_CLOSE, '}']); } private function transformIntoDollarCloseBrace(Tokens $tokens, int $index): void { $token = $tokens[$index]; if ($token->isGivenKind(\T_DOLLAR_OPEN_CURLY_BRACES)) { $nextIndex = $tokens->getNextTokenOfKind($index, ['}']); $tokens[$nextIndex] = new Token([CT::T_DOLLAR_CLOSE_CURLY_BRACES, '}']); } } private function transformIntoDynamicPropBraces(Tokens $tokens, int $index): void { $token = $tokens[$index]; if (!$token->isObjectOperator()) { return; } if (!$tokens[$index + 1]->equals('{')) { return; } $openIndex = $index + 1; $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $openIndex); $tokens[$openIndex] = new Token([CT::T_DYNAMIC_PROP_BRACE_OPEN, '{']); $tokens[$closeIndex] = new Token([CT::T_DYNAMIC_PROP_BRACE_CLOSE, '}']); } private function transformIntoDynamicVarBraces(Tokens $tokens, int $index): void { $token = $tokens[$index]; if (!$token->equals('$')) { return; } $openIndex = $tokens->getNextMeaningfulToken($index); if (null === $openIndex) { return; } $openToken = $tokens[$openIndex]; if (!$openToken->equals('{')) { return; } $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $openIndex); $tokens[$openIndex] = new Token([CT::T_DYNAMIC_VAR_BRACE_OPEN, '{']); $tokens[$closeIndex] = new Token([CT::T_DYNAMIC_VAR_BRACE_CLOSE, '}']); } private function transformIntoPropertyHookBraces(Tokens $tokens, int $index): void { if (\PHP_VERSION_ID < 8_04_00) { return; // @TODO: drop condition when PHP 8.4+ is required or majority of the users are using 8.4+ } $token = $tokens[$index]; if (!$token->equals('{')) { return; } $nextIndex = $tokens->getNextMeaningfulToken($index); // skip attributes while ($tokens[$nextIndex]->isGivenKind(FCT::T_ATTRIBUTE)) { $nextIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $nextIndex); $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); } if (!$tokens[$nextIndex]->equalsAny([ [\T_STRING, 'get'], [\T_STRING, 'set'], ], false)) { return; } $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex); if (!$tokens[$nextNextIndex]->equalsAny(['(', '{', ';', [\T_DOUBLE_ARROW]])) { return; } if ($tokens[$nextNextIndex]->equals('(')) { $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextNextIndex); $afterCloseParenthesisIndex = $tokens->getNextMeaningfulToken($closeParenthesisIndex); if (!$tokens[$afterCloseParenthesisIndex]->equalsAny(['{', [\T_DOUBLE_ARROW]])) { return; } } $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $index); $tokens[$index] = new Token([CT::T_PROPERTY_HOOK_BRACE_OPEN, '{']); $tokens[$closeIndex] = new Token([CT::T_PROPERTY_HOOK_BRACE_CLOSE, '}']); } private function transformIntoCurlyIndexBraces(Tokens $tokens, int $index): void { // Support for fetching array index with braces syntax (`$arr{$index}`) // was deprecated in 7.4 and removed in 8.0. However, the PHP's behaviour // differs between 8.0-8.3 (fatal error in runtime) and 8.4 (parse error). // // @TODO Do not replace `CT::T_ARRAY_INDEX_CURLY_BRACE_*` for 8.0-8.3, as further optimization if (\PHP_VERSION_ID >= 8_04_00) { return; } $token = $tokens[$index]; if (!$token->equals('{')) { return; } $prevIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$prevIndex]->equalsAny([ [\T_STRING], [\T_VARIABLE], [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], ']', ')', ])) { return; } if ( $tokens[$prevIndex]->isGivenKind(\T_STRING) && !$tokens[$tokens->getPrevMeaningfulToken($prevIndex)]->isObjectOperator() ) { return; } if ( $tokens[$prevIndex]->equals(')') && !$tokens[$tokens->getPrevMeaningfulToken( $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $prevIndex), )]->isGivenKind(\T_ARRAY) ) { return; } $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $index); $tokens[$index] = new Token([CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, '{']); $tokens[$closeIndex] = new Token([CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE, '}']); } private function transformIntoGroupUseBraces(Tokens $tokens, int $index): void { $token = $tokens[$index]; if (!$token->equals('{')) { return; } $prevIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { return; } $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $index); $tokens[$index] = new Token([CT::T_GROUP_IMPORT_BRACE_OPEN, '{']); $tokens[$closeIndex] = new Token([CT::T_GROUP_IMPORT_BRACE_CLOSE, '}']); } private function transformIntoDynamicClassConstantFetchBraces(Tokens $tokens, int $index): void { if (\PHP_VERSION_ID < 8_03_00) { return; // @TODO: drop condition when PHP 8.3+ is required or majority of the users are using 8.3+ } $token = $tokens[$index]; if (!$token->equals('{')) { return; } $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($index); while (!$tokens[$prevMeaningfulTokenIndex]->isGivenKind(\T_DOUBLE_COLON)) { if (!$tokens[$prevMeaningfulTokenIndex]->equals(')')) { return; } $prevMeaningfulTokenIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $prevMeaningfulTokenIndex); $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulTokenIndex); if (!$tokens[$prevMeaningfulTokenIndex]->equals('}')) { return; } $prevMeaningfulTokenIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $prevMeaningfulTokenIndex); $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulTokenIndex); } $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $index); $nextMeaningfulTokenIndexAfterCloseIndex = $tokens->getNextMeaningfulToken($closeIndex); if (!$tokens[$nextMeaningfulTokenIndexAfterCloseIndex]->equalsAny([';', [\T_CLOSE_TAG], [\T_DOUBLE_COLON]])) { return; } $tokens[$index] = new Token([CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_OPEN, '{']); $tokens[$closeIndex] = new Token([CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_CLOSE, '}']); } /** * We do not want to rely on `$tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index)` here, * as it relies on block types that are assuming that `}` tokens are already transformed to Custom Tokens that are allowing to distinguish different block types. * As we are just about to transform `{` and `}` into Custom Tokens by this transformer, thus we need to compare those tokens manually by content without using `Tokens::findBlockEnd`. */ private function naivelyFindCurlyBlockEnd(Tokens $tokens, int $startIndex): int { if (!$tokens->offsetExists($startIndex)) { throw new \OutOfBoundsException(\sprintf('Unavailable index: "%s".', $startIndex)); } if ('{' !== $tokens[$startIndex]->getContent()) { throw new \InvalidArgumentException(\sprintf('Wrong start index: "%s".', $startIndex)); } $blockLevel = 1; $endIndex = $tokens->count() - 1; for ($index = $startIndex + 1; $index !== $endIndex; ++$index) { $token = $tokens[$index]; if ('{' === $token->getContent()) { ++$blockLevel; continue; } if ('}' === $token->getContent()) { --$blockLevel; if (0 === $blockLevel) { if (!$token->equals('}')) { throw new \UnexpectedValueException(\sprintf('Detected block end for index: "%s" was already transformed into other token type: "%s".', $startIndex, $token->getName())); } return $index; } } } throw new \UnexpectedValueException(\sprintf('Missing block end for index: "%s".', $startIndex)); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Transformer/ClassConstantTransformer.php
src/Tokenizer/Transformer/ClassConstantTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTransformer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Transform `class` class' constant from T_CLASS into CT::T_CLASS_CONSTANT. * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ClassConstantTransformer extends AbstractTransformer { public function getRequiredPhpVersionId(): int { return 5_05_00; } public function process(Tokens $tokens, Token $token, int $index): void { if (!$token->equalsAny([ [\T_CLASS, 'class'], [\T_STRING, 'class'], ], false)) { return; } $prevIndex = $tokens->getPrevMeaningfulToken($index); $prevToken = $tokens[$prevIndex]; if ($prevToken->isGivenKind(\T_DOUBLE_COLON)) { $tokens[$index] = new Token([CT::T_CLASS_CONSTANT, $token->getContent()]); } } public function getCustomTokens(): array { return [CT::T_CLASS_CONSTANT]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Transformer/NullableTypeTransformer.php
src/Tokenizer/Transformer/NullableTypeTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTransformer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Transform `?` operator into CT::T_NULLABLE_TYPE in `function foo(?Bar $b) {}`. * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NullableTypeTransformer extends AbstractTransformer { private const TYPES = [ '(', ',', [CT::T_TYPE_COLON], [CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC], [CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED], [CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE], [CT::T_ATTRIBUTE_CLOSE], [\T_PRIVATE], [\T_PROTECTED], [\T_PUBLIC], [\T_VAR], [\T_STATIC], [\T_CONST], [\T_ABSTRACT], [\T_FINAL], [FCT::T_READONLY], [FCT::T_PRIVATE_SET], [FCT::T_PROTECTED_SET], [FCT::T_PUBLIC_SET], ]; public function getPriority(): int { // needs to run after TypeColonTransformer return -20; } public function getRequiredPhpVersionId(): int { return 7_01_00; } public function process(Tokens $tokens, Token $token, int $index): void { if (!$token->equals('?')) { return; } $prevIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$prevIndex]->equalsAny(self::TYPES)) { return; } if ( $tokens[$prevIndex]->isGivenKind(\T_STATIC) && $tokens[$tokens->getPrevMeaningfulToken($prevIndex)]->isGivenKind(\T_INSTANCEOF) ) { return; } $tokens[$index] = new Token([CT::T_NULLABLE_TYPE, '?']); } public function getCustomTokens(): array { return [CT::T_NULLABLE_TYPE]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Transformer/ArrayTypehintTransformer.php
src/Tokenizer/Transformer/ArrayTypehintTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTransformer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Transform `array` typehint from T_ARRAY into CT::T_ARRAY_TYPEHINT. * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ArrayTypehintTransformer extends AbstractTransformer { public function getRequiredPhpVersionId(): int { return 5_00_00; } public function process(Tokens $tokens, Token $token, int $index): void { if (!$token->isGivenKind(\T_ARRAY)) { return; } $nextIndex = $tokens->getNextMeaningfulToken($index); $nextToken = $tokens[$nextIndex]; if (!$nextToken->equals('(')) { $tokens[$index] = new Token([CT::T_ARRAY_TYPEHINT, $token->getContent()]); } } public function getCustomTokens(): array { return [CT::T_ARRAY_TYPEHINT]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Transformer/TypeAlternationTransformer.php
src/Tokenizer/Transformer/TypeAlternationTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTypeTransformer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Transform `|` operator into CT::T_TYPE_ALTERNATION in `function foo(Type1 | Type2 $x) {` * or `} catch (ExceptionType1 | ExceptionType2 $e) {`. * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class TypeAlternationTransformer extends AbstractTypeTransformer { public function getPriority(): int { // needs to run after ArrayTypehintTransformer, TypeColonTransformer and AttributeTransformer return -15; } public function getRequiredPhpVersionId(): int { return 7_01_00; } public function process(Tokens $tokens, Token $token, int $index): void { $this->doProcess($tokens, $index, '|'); } public function getCustomTokens(): array { return [CT::T_TYPE_ALTERNATION]; } protected function replaceToken(Tokens $tokens, int $index): void { $tokens[$index] = new Token([CT::T_TYPE_ALTERNATION, '|']); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Transformer/NamedArgumentTransformer.php
src/Tokenizer/Transformer/NamedArgumentTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTransformer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Transform named argument tokens. * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NamedArgumentTransformer extends AbstractTransformer { public function getPriority(): int { // needs to run after TypeColonTransformer return -15; } public function getRequiredPhpVersionId(): int { return 8_00_00; } public function process(Tokens $tokens, Token $token, int $index): void { if (!$tokens[$index]->equals(':')) { return; } $stringIndex = $tokens->getPrevMeaningfulToken($index); if (!$tokens[$stringIndex]->isGivenKind(\T_STRING)) { return; } $preStringIndex = $tokens->getPrevMeaningfulToken($stringIndex); // if equals any [';', '{', '}', [T_OPEN_TAG]] than it is a goto label // if equals ')' than likely it is a type colon, but sure not a name argument // if equals '?' than it is part of ternary statement if (!$tokens[$preStringIndex]->equalsAny([',', '('])) { return; } $tokens[$stringIndex] = new Token([CT::T_NAMED_ARGUMENT_NAME, $tokens[$stringIndex]->getContent()]); $tokens[$index] = new Token([CT::T_NAMED_ARGUMENT_COLON, ':']); } public function getCustomTokens(): array { return [ CT::T_NAMED_ARGUMENT_COLON, CT::T_NAMED_ARGUMENT_NAME, ]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Transformer/DisjunctiveNormalFormTypeParenthesisTransformer.php
src/Tokenizer/Transformer/DisjunctiveNormalFormTypeParenthesisTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTransformer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Transform DNF parentheses into CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN and CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE. * * @see https://wiki.php.net/rfc/dnf_types * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class DisjunctiveNormalFormTypeParenthesisTransformer extends AbstractTransformer { public function getPriority(): int { // needs to run after TypeAlternationTransformer return -16; } public function getRequiredPhpVersionId(): int { return 8_02_00; } public function process(Tokens $tokens, Token $token, int $index): void { if ($token->equals('(') && $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(CT::T_TYPE_ALTERNATION)) { $openIndex = $index; $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); } elseif ($token->equals(')') && $tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(CT::T_TYPE_ALTERNATION)) { $openIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); $closeIndex = $index; } else { return; } $tokens[$openIndex] = new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, '(']); $tokens[$closeIndex] = new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, ')']); } public function getCustomTokens(): array { return [ CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_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/Tokenizer/Transformer/WhitespacyCommentTransformer.php
src/Tokenizer/Transformer/WhitespacyCommentTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTransformer; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Move trailing whitespaces from comments and docs into following T_WHITESPACE token. * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class WhitespacyCommentTransformer extends AbstractTransformer { public function getRequiredPhpVersionId(): int { return 5_00_00; } public function process(Tokens $tokens, Token $token, int $index): void { if (!$token->isComment()) { return; } $content = $token->getContent(); $trimmedContent = rtrim($content); // nothing trimmed, nothing to do if ($content === $trimmedContent) { return; } $whitespaces = substr($content, \strlen($trimmedContent)); $tokens[$index] = new Token([$token->getId(), $trimmedContent]); if (isset($tokens[$index + 1]) && $tokens[$index + 1]->isWhitespace()) { $tokens[$index + 1] = new Token([\T_WHITESPACE, $whitespaces.$tokens[$index + 1]->getContent()]); } else { $tokens->insertAt($index + 1, new Token([\T_WHITESPACE, $whitespaces])); } } public function getCustomTokens(): array { return []; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Transformer/ReturnRefTransformer.php
src/Tokenizer/Transformer/ReturnRefTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTransformer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Transform `&` operator into CT::T_RETURN_REF in `function & foo() {}`. * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ReturnRefTransformer extends AbstractTransformer { public function getRequiredPhpVersionId(): int { return 5_00_00; } public function process(Tokens $tokens, Token $token, int $index): void { if ($token->equals('&') && $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind([\T_FUNCTION, \T_FN])) { $tokens[$index] = new Token([CT::T_RETURN_REF, '&']); } } public function getCustomTokens(): array { return [CT::T_RETURN_REF]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Transformer/TypeColonTransformer.php
src/Tokenizer/Transformer/TypeColonTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTransformer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Transform `:` operator into CT::T_TYPE_COLON in `function foo() : int {}`. * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class TypeColonTransformer extends AbstractTransformer { public function getPriority(): int { // needs to run after ReturnRefTransformer and UseTransformer // and before TypeAlternationTransformer return -10; } public function getRequiredPhpVersionId(): int { return 7_00_00; } public function process(Tokens $tokens, Token $token, int $index): void { if (!$token->equals(':')) { return; } $endIndex = $tokens->getPrevMeaningfulToken($index); if ($tokens[$tokens->getPrevMeaningfulToken($endIndex)]->isGivenKind(FCT::T_ENUM)) { $tokens[$index] = new Token([CT::T_TYPE_COLON, ':']); return; } if (!$tokens[$endIndex]->equals(')')) { return; } $startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $endIndex); $prevIndex = $tokens->getPrevMeaningfulToken($startIndex); $prevToken = $tokens[$prevIndex]; // if this could be a function name we need to take one more step if ($prevToken->isGivenKind(\T_STRING)) { $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); $prevToken = $tokens[$prevIndex]; } if ($prevToken->isGivenKind([\T_FUNCTION, CT::T_RETURN_REF, CT::T_USE_LAMBDA, \T_FN])) { $tokens[$index] = new Token([CT::T_TYPE_COLON, ':']); } } public function getCustomTokens(): array { return [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/Tokenizer/Transformer/ImportTransformer.php
src/Tokenizer/Transformer/ImportTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTransformer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Transform const/function import tokens. * * Performed transformations: * - T_CONST into CT::T_CONST_IMPORT * - T_FUNCTION into CT::T_FUNCTION_IMPORT * * @author Gregor Harlan <gharlan@web.de> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ImportTransformer extends AbstractTransformer { public function getPriority(): int { // Should run after CurlyBraceTransformer and ReturnRefTransformer return -1; } public function getRequiredPhpVersionId(): int { return 5_06_00; } public function process(Tokens $tokens, Token $token, int $index): void { if (!$token->isGivenKind([\T_CONST, \T_FUNCTION])) { return; } $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; if (!$prevToken->isGivenKind(\T_USE)) { $nextToken = $tokens[$tokens->getNextTokenOfKind($index, ['=', '(', [CT::T_RETURN_REF], [CT::T_GROUP_IMPORT_BRACE_CLOSE]])]; if (!$nextToken->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)) { return; } } $tokens[$index] = new Token([ $token->isGivenKind(\T_FUNCTION) ? CT::T_FUNCTION_IMPORT : CT::T_CONST_IMPORT, $token->getContent(), ]); } public function getCustomTokens(): array { return [CT::T_CONST_IMPORT, CT::T_FUNCTION_IMPORT]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Transformer/UseTransformer.php
src/Tokenizer/Transformer/UseTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTransformer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Transform T_USE into: * - CT::T_USE_TRAIT for imports, * - CT::T_USE_LAMBDA for lambda variable uses. * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class UseTransformer extends AbstractTransformer { private const CLASS_TYPES = [\T_TRAIT, FCT::T_ENUM]; public function getPriority(): int { // Should run after CurlyBraceTransformer and before TypeColonTransformer return -5; } public function getRequiredPhpVersionId(): int { return 5_03_00; } public function process(Tokens $tokens, Token $token, int $index): void { if ($token->isGivenKind(\T_USE) && $this->isUseForLambda($tokens, $index)) { $tokens[$index] = new Token([CT::T_USE_LAMBDA, $token->getContent()]); return; } // Only search inside class/trait body for `T_USE` for traits. // Cannot import traits inside interfaces or anywhere else if ($token->isGivenKind(\T_CLASS)) { if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(\T_DOUBLE_COLON)) { return; } } elseif (!$token->isGivenKind(self::CLASS_TYPES)) { return; } $index = $tokens->getNextTokenOfKind($index, ['{']); $innerLimit = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); while ($index < $innerLimit) { $token = $tokens[++$index]; if (!$token->isGivenKind(\T_USE)) { continue; } if ($this->isUseForLambda($tokens, $index)) { $tokens[$index] = new Token([CT::T_USE_LAMBDA, $token->getContent()]); } else { $tokens[$index] = new Token([CT::T_USE_TRAIT, $token->getContent()]); } } } public function getCustomTokens(): array { return [CT::T_USE_TRAIT, CT::T_USE_LAMBDA]; } /** * Check if token under given index is `use` statement for lambda function. */ private function isUseForLambda(Tokens $tokens, int $index): bool { $nextToken = $tokens[$tokens->getNextMeaningfulToken($index)]; // test `function () use ($foo) {}` case return $nextToken->equals('('); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Transformer/SquareBraceTransformer.php
src/Tokenizer/Transformer/SquareBraceTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTransformer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Transform discriminate overloaded square braces tokens. * * Performed transformations: * - in `[1, 2, 3]` into CT::T_ARRAY_SQUARE_BRACE_OPEN and CT::T_ARRAY_SQUARE_BRACE_CLOSE, * - in `[$a, &$b, [$c]] = array(1, 2, array(3))` into CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN and CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE. * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class SquareBraceTransformer extends AbstractTransformer { public function getPriority(): int { // must run after CurlyBraceTransformer and AttributeTransformer return -1; } public function getRequiredPhpVersionId(): int { // Short array syntax was introduced in PHP 5.4, but the fixer is smart // enough to handle it even before 5.4. // Same for array destructing syntax sugar `[` introduced in PHP 7.1. return 5_00_00; } public function process(Tokens $tokens, Token $token, int $index): void { if ($this->isArrayDestructing($tokens, $index)) { $this->transformIntoDestructuringSquareBrace($tokens, $index); return; } if ($this->isShortArray($tokens, $index)) { $this->transformIntoArraySquareBrace($tokens, $index); } } public function getCustomTokens(): array { return [ CT::T_ARRAY_SQUARE_BRACE_OPEN, CT::T_ARRAY_SQUARE_BRACE_CLOSE, CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, ]; } private function transformIntoArraySquareBrace(Tokens $tokens, int $index): void { $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index); $tokens[$index] = new Token([CT::T_ARRAY_SQUARE_BRACE_OPEN, '[']); $tokens[$endIndex] = new Token([CT::T_ARRAY_SQUARE_BRACE_CLOSE, ']']); } private function transformIntoDestructuringSquareBrace(Tokens $tokens, int $index): void { $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index); $tokens[$index] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, '[']); $tokens[$endIndex] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, ']']); $previousMeaningfulIndex = $index; $index = $tokens->getNextMeaningfulToken($index); while ($index < $endIndex) { if ($tokens[$index]->equals('[') && $tokens[$previousMeaningfulIndex]->equalsAny([[CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN], ','])) { $tokens[$tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index)] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, ']']); $tokens[$index] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, '[']); } $previousMeaningfulIndex = $index; $index = $tokens->getNextMeaningfulToken($index); } } /** * Check if token under given index is short array opening. */ private function isShortArray(Tokens $tokens, int $index): bool { if (!$tokens[$index]->equals('[')) { return false; } $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; if ($prevToken->equalsAny([ ')', ']', '}', '"', [\T_CONSTANT_ENCAPSED_STRING], [\T_STRING], [\T_STRING_VARNAME], [\T_VARIABLE], [CT::T_ARRAY_SQUARE_BRACE_CLOSE], [CT::T_DYNAMIC_PROP_BRACE_CLOSE], [CT::T_DYNAMIC_VAR_BRACE_CLOSE], [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], ])) { return false; } $nextToken = $tokens[$tokens->getNextMeaningfulToken($index)]; if ($nextToken->equals(']')) { return true; } return !$this->isArrayDestructing($tokens, $index); } private function isArrayDestructing(Tokens $tokens, int $index): bool { if (!$tokens[$index]->equals('[')) { return false; } $prevIndex = $tokens->getPrevMeaningfulToken($index); $prevToken = $tokens[$prevIndex]; if ($prevToken->equalsAny([ ')', ']', '"', [\T_CONSTANT_ENCAPSED_STRING], [\T_STRING], [\T_STRING_VARNAME], [\T_VARIABLE], [CT::T_ARRAY_SQUARE_BRACE_CLOSE], [CT::T_DYNAMIC_PROP_BRACE_CLOSE], [CT::T_DYNAMIC_VAR_BRACE_CLOSE], [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], ])) { return false; } if ($prevToken->isGivenKind(\T_AS)) { return true; } if ($prevToken->isGivenKind(\T_DOUBLE_ARROW)) { $variableIndex = $tokens->getPrevMeaningfulToken($prevIndex); if (!$tokens[$variableIndex]->isGivenKind(\T_VARIABLE)) { return false; } $prevVariableIndex = $tokens->getPrevMeaningfulToken($variableIndex); if ($tokens[$prevVariableIndex]->isGivenKind(\T_AS)) { return true; } } $type = Tokens::detectBlockType($tokens[$index]); $end = $tokens->findBlockEnd($type['type'], $index); $nextToken = $tokens[$tokens->getNextMeaningfulToken($end)]; return $nextToken->equals('='); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Transformer/FirstClassCallableTransformer.php
src/Tokenizer/Transformer/FirstClassCallableTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTransformer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class FirstClassCallableTransformer extends AbstractTransformer { public function getRequiredPhpVersionId(): int { return 8_01_00; } public function process(Tokens $tokens, Token $token, int $index): void { if ( $token->isGivenKind(\T_ELLIPSIS) && $tokens[$tokens->getPrevMeaningfulToken($index)]->equals('(') && $tokens[$tokens->getNextMeaningfulToken($index)]->equals(')') ) { $tokens[$index] = new Token([CT::T_FIRST_CLASS_CALLABLE, '...']); } } public function getCustomTokens(): array { return [ CT::T_FIRST_CLASS_CALLABLE, ]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Transformer/ConstructorPromotionTransformer.php
src/Tokenizer/Transformer/ConstructorPromotionTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTransformer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Transforms for Constructor Property Promotion. * * Transform T_PUBLIC, T_PROTECTED and T_PRIVATE of Constructor Property Promotion into custom tokens. * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class ConstructorPromotionTransformer extends AbstractTransformer { public function getRequiredPhpVersionId(): int { return 8_00_00; } public function process(Tokens $tokens, Token $token, int $index): void { if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { return; } $functionNameIndex = $tokens->getNextMeaningfulToken($index); if (!$tokens[$functionNameIndex]->isGivenKind(\T_STRING) || '__construct' !== strtolower($tokens[$functionNameIndex]->getContent())) { return; } /** @var int $openParenthesisIndex */ $openParenthesisIndex = $tokens->getNextMeaningfulToken($functionNameIndex); // we are @ '(' now $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesisIndex); for ($argsIndex = $openParenthesisIndex; $argsIndex < $closeParenthesisIndex; ++$argsIndex) { if ($tokens[$argsIndex]->isGivenKind(\T_PUBLIC)) { $tokens[$argsIndex] = new Token([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, $tokens[$argsIndex]->getContent()]); } elseif ($tokens[$argsIndex]->isGivenKind(\T_PROTECTED)) { $tokens[$argsIndex] = new Token([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, $tokens[$argsIndex]->getContent()]); } elseif ($tokens[$argsIndex]->isGivenKind(\T_PRIVATE)) { $tokens[$argsIndex] = new Token([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, $tokens[$argsIndex]->getContent()]); } } } public function getCustomTokens(): array { return [ CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, ]; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Transformer/BraceClassInstantiationTransformer.php
src/Tokenizer/Transformer/BraceClassInstantiationTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTransformer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Transform braced class instantiation braces in `(new Foo())` into CT::T_BRACE_CLASS_INSTANTIATION_OPEN * and CT::T_BRACE_CLASS_INSTANTIATION_CLOSE. * * @author Sebastiaans Stok <s.stok@rollerscapes.net> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class BraceClassInstantiationTransformer extends AbstractTransformer { public function getPriority(): int { // must run after CurlyBraceTransformer and SquareBraceTransformer return -2; } public function getRequiredPhpVersionId(): int { return 5_00_00; } public function process(Tokens $tokens, Token $token, int $index): void { if (!$tokens[$index]->equals('(') || !$tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(\T_NEW)) { return; } if ($tokens[$tokens->getPrevMeaningfulToken($index)]->equalsAny([ ')', ']', [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], [CT::T_ARRAY_SQUARE_BRACE_CLOSE], [CT::T_BRACE_CLASS_INSTANTIATION_CLOSE], [\T_ARRAY], [\T_CLASS], [\T_ELSEIF], [\T_FOR], [\T_FOREACH], [\T_IF], [\T_STATIC], [\T_STRING], [\T_SWITCH], [\T_VARIABLE], [\T_WHILE], ])) { return; } $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); $tokens[$index] = new Token([CT::T_BRACE_CLASS_INSTANTIATION_OPEN, '(']); $tokens[$closeIndex] = new Token([CT::T_BRACE_CLASS_INSTANTIATION_CLOSE, ')']); } public function getCustomTokens(): array { return [CT::T_BRACE_CLASS_INSTANTIATION_OPEN, CT::T_BRACE_CLASS_INSTANTIATION_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/Tokenizer/Transformer/TypeIntersectionTransformer.php
src/Tokenizer/Transformer/TypeIntersectionTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTypeTransformer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Transform `&` operator into CT::T_TYPE_INTERSECTION in `function foo(Type1 & Type2 $x) {` * or `} catch (ExceptionType1 & ExceptionType2 $e) {`. * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class TypeIntersectionTransformer extends AbstractTypeTransformer { public function getPriority(): int { // needs to run after ArrayTypehintTransformer, TypeColonTransformer and AttributeTransformer return -15; } public function getRequiredPhpVersionId(): int { return 8_01_00; } public function process(Tokens $tokens, Token $token, int $index): void { $this->doProcess($tokens, $index, [\T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG, '&']); } public function getCustomTokens(): array { return [CT::T_TYPE_INTERSECTION]; } protected function replaceToken(Tokens $tokens, int $index): void { $tokens[$index] = new Token([CT::T_TYPE_INTERSECTION, '&']); } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Tokenizer/Transformer/AttributeTransformer.php
src/Tokenizer/Transformer/AttributeTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTransformer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Transforms attribute related Tokens. * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class AttributeTransformer extends AbstractTransformer { public function getPriority(): int { // must run before all other transformers that might touch attributes return 200; } public function getRequiredPhpVersionId(): int { return 8_00_00; } public function process(Tokens $tokens, Token $token, int $index): void { if (!$tokens[$index]->isGivenKind(\T_ATTRIBUTE)) { return; } do { ++$index; if ($tokens[$index]->equals('(')) { $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index) + 1; } } while (!$tokens[$index]->equals(']')); $tokens[$index] = new Token([CT::T_ATTRIBUTE_CLOSE, ']']); } public function getCustomTokens(): array { return [ CT::T_ATTRIBUTE_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/Tokenizer/Transformer/NamespaceOperatorTransformer.php
src/Tokenizer/Transformer/NamespaceOperatorTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTransformer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Transform `namespace` operator from T_NAMESPACE into CT::T_NAMESPACE_OPERATOR. * * @author Gregor Harlan <gharlan@web.de> * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NamespaceOperatorTransformer extends AbstractTransformer { public function getRequiredPhpVersionId(): int { return 5_03_00; } public function process(Tokens $tokens, Token $token, int $index): void { if (!$token->isGivenKind(\T_NAMESPACE)) { return; } $nextIndex = $tokens->getNextMeaningfulToken($index); if ($tokens[$nextIndex]->isGivenKind(\T_NS_SEPARATOR)) { $tokens[$index] = new Token([CT::T_NAMESPACE_OPERATOR, $token->getContent()]); } } public function getCustomTokens(): array { return [CT::T_NAMESPACE_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/Tokenizer/Transformer/NameQualifiedTransformer.php
src/Tokenizer/Transformer/NameQualifiedTransformer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tokenizer\Transformer; use PhpCsFixer\Tokenizer\AbstractTransformer; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Processor\ImportProcessor; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * Transform NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED and T_NAME_RELATIVE into T_NAMESPACE T_NS_SEPARATOR T_STRING. * * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ final class NameQualifiedTransformer extends AbstractTransformer { public function getPriority(): int { return 1; // must run before NamespaceOperatorTransformer } public function getRequiredPhpVersionId(): int { return 8_00_00; } public function process(Tokens $tokens, Token $token, int $index): void { if ($token->isGivenKind([FCT::T_NAME_QUALIFIED, FCT::T_NAME_FULLY_QUALIFIED])) { $this->transformQualified($tokens, $token, $index); } elseif ($token->isGivenKind(FCT::T_NAME_RELATIVE)) { $this->transformRelative($tokens, $token, $index); } } public function getCustomTokens(): array { return []; } private function transformQualified(Tokens $tokens, Token $token, int $index): void { $newTokens = ImportProcessor::tokenizeName($token->getContent()); $tokens->overrideRange($index, $index, $newTokens); } private function transformRelative(Tokens $tokens, Token $token, int $index): void { $newTokens = ImportProcessor::tokenizeName($token->getContent()); $newTokens[0] = new Token([\T_NAMESPACE, 'namespace']); $tokens->overrideRange($index, $index, $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/FixerInterface.php
src/Fixer/FixerInterface.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer; use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; use PhpCsFixer\Tokenizer\Tokens; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * @author Fabien Potencier <fabien@symfony.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ interface FixerInterface { /** * Check if the fixer is a candidate for given Tokens collection. * * Fixer is a candidate when the collection contains tokens that may be fixed * during fixer work. This could be considered as some kind of bloom filter. * When this method returns true then to the Tokens collection may or may not * need a fixing, but when this method returns false then the Tokens collection * need no fixing for sure. */ public function isCandidate(Tokens $tokens): bool; /** * Check if fixer is risky or not. * * Risky fixer could change code behaviour! */ public function isRisky(): bool; /** * Fixes a file. * * @param \SplFileInfo $file A \SplFileInfo instance * @param Tokens $tokens Tokens collection */ public function fix(\SplFileInfo $file, Tokens $tokens): void; /** * Returns the definition of the fixer. */ public function getDefinition(): FixerDefinitionInterface; /** * Returns the name of the fixer. * * The name must be all lowercase and without any spaces. * * @return string The name of the fixer */ public function getName(): string; /** * Returns the priority of the fixer. * * The default priority is 0 and higher priorities are executed first. */ public function getPriority(): int; /** * Returns true if the file is supported by this fixer. * * @return bool true if the file is supported by this fixer, false otherwise */ public function supports(\SplFileInfo $file): bool; }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ExperimentalFixerInterface.php
src/Fixer/ExperimentalFixerInterface.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer; /** * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ interface ExperimentalFixerInterface extends FixerInterface {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/WhitespacesAwareFixerInterface.php
src/Fixer/WhitespacesAwareFixerInterface.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer; use PhpCsFixer\WhitespacesFixerConfig; /** * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ interface WhitespacesAwareFixerInterface extends FixerInterface { public function setWhitespacesConfig(WhitespacesFixerConfig $config): void; }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/InternalFixerInterface.php
src/Fixer/InternalFixerInterface.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer; /** * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ interface InternalFixerInterface extends FixerInterface {}
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/AbstractPhpUnitFixer.php
src/Fixer/AbstractPhpUnitFixer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer; use PhpCsFixer\AbstractFixer; use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer; use PhpCsFixer\Tokenizer\Analyzer\FullyQualifiedNameAnalyzer; use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; use PhpCsFixer\Tokenizer\Analyzer\PhpUnitTestCaseAnalyzer; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Tokens; /** * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ abstract class AbstractPhpUnitFixer extends AbstractFixer { use DocBlockAnnotationTrait; public function isCandidate(Tokens $tokens): bool { return $tokens->isAllTokenKindsFound([\T_CLASS, \T_STRING]); } final protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { foreach ((new PhpUnitTestCaseAnalyzer())->findPhpUnitClasses($tokens) as $indices) { $this->applyPhpUnitClassFix($tokens, $indices[0], $indices[1]); } } abstract protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void; /** * @return iterable<array{ * index: int, * loweredName: string, * openBraceIndex: int, * closeBraceIndex: int, * }> */ protected function getPreviousAssertCall(Tokens $tokens, int $startIndex, int $endIndex): iterable { $functionsAnalyzer = new FunctionsAnalyzer(); for ($index = $endIndex; $index > $startIndex; --$index) { $index = $tokens->getPrevTokenOfKind($index, [[\T_STRING]]); if (null === $index) { return; } // test if "assert" something call $loweredContent = strtolower($tokens[$index]->getContent()); if (!str_starts_with($loweredContent, 'assert')) { continue; } // test candidate for simple calls like: ([\]+'some fixable call'(...)) $openBraceIndex = $tokens->getNextMeaningfulToken($index); if (!$tokens[$openBraceIndex]->equals('(')) { continue; } if (!$functionsAnalyzer->isTheSameClassCall($tokens, $index)) { continue; } yield [ 'index' => $index, 'loweredName' => $loweredContent, 'openBraceIndex' => $openBraceIndex, 'closeBraceIndex' => $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openBraceIndex), ]; } } final protected function isTestAttributePresent(Tokens $tokens, int $index): bool { $attributeIndex = $tokens->getPrevTokenOfKind($index, ['{', [FCT::T_ATTRIBUTE]]); if (!$tokens[$attributeIndex]->isGivenKind(FCT::T_ATTRIBUTE)) { return false; } $fullyQualifiedNameAnalyzer = new FullyQualifiedNameAnalyzer($tokens); foreach (AttributeAnalyzer::collect($tokens, $attributeIndex) as $attributeAnalysis) { foreach ($attributeAnalysis->getAttributes() as $attribute) { $attributeName = strtolower($fullyQualifiedNameAnalyzer->getFullyQualifiedName($attribute['name'], $attribute['start'], NamespaceUseAnalysis::TYPE_CLASS)); if ('phpunit\framework\attributes\test' === $attributeName) { return true; } } } return false; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/AbstractShortOperatorFixer.php
src/Fixer/AbstractShortOperatorFixer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer; use PhpCsFixer\AbstractFixer; use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer; use PhpCsFixer\Tokenizer\Analyzer\RangeAnalyzer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @internal * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ abstract class AbstractShortOperatorFixer extends AbstractFixer { protected function applyFix(\SplFileInfo $file, Tokens $tokens): void { $alternativeSyntaxAnalyzer = new AlternativeSyntaxAnalyzer(); for ($index = \count($tokens) - 1; $index > 3; --$index) { if (!$this->isOperatorTokenCandidate($tokens, $index)) { continue; } // get what is before the operator $beforeRange = $this->getBeforeOperatorRange($tokens, $index); $equalsIndex = $tokens->getPrevMeaningfulToken($beforeRange['start']); // make sure that before that is '=' if (!$tokens[$equalsIndex]->equals('=')) { continue; } // get and check what is before '=' $assignRange = $this->getBeforeOperatorRange($tokens, $equalsIndex); $beforeAssignmentIndex = $tokens->getPrevMeaningfulToken($assignRange['start']); if ($tokens[$beforeAssignmentIndex]->equals(':')) { if (!$this->belongsToSwitchOrAlternativeSyntax($alternativeSyntaxAnalyzer, $tokens, $beforeAssignmentIndex)) { continue; } } elseif (!$tokens[$beforeAssignmentIndex]->equalsAny([';', '{', '}', '(', ')', ',', [\T_OPEN_TAG], [\T_RETURN]])) { continue; } // check if "assign" and "before" the operator are (functionally) the same if (RangeAnalyzer::rangeEqualsRange($tokens, $assignRange, $beforeRange)) { $this->shortenOperation($tokens, $equalsIndex, $index, $assignRange, $beforeRange); continue; } if (!$this->isOperatorCommutative($tokens[$index])) { continue; } $afterRange = $this->getAfterOperatorRange($tokens, $index); // check if "assign" and "after" the operator are (functionally) the same if (!RangeAnalyzer::rangeEqualsRange($tokens, $assignRange, $afterRange)) { continue; } $this->shortenOperation($tokens, $equalsIndex, $index, $assignRange, $afterRange); } } abstract protected function getReplacementToken(Token $token): Token; abstract protected function isOperatorTokenCandidate(Tokens $tokens, int $index): bool; /** * @param array{start: int, end: int} $assignRange * @param array{start: int, end: int} $operatorRange */ private function shortenOperation( Tokens $tokens, int $equalsIndex, int $operatorIndex, array $assignRange, array $operatorRange ): void { $tokens[$equalsIndex] = $this->getReplacementToken($tokens[$operatorIndex]); $tokens->clearTokenAndMergeSurroundingWhitespace($operatorIndex); $this->clearMeaningfulFromRange($tokens, $operatorRange); foreach ([$equalsIndex, $assignRange['end']] as $i) { $i = $tokens->getNonEmptySibling($i, 1); if ($tokens[$i]->isWhitespace(" \t")) { $tokens[$i] = new Token([\T_WHITESPACE, ' ']); } elseif (!$tokens[$i]->isWhitespace()) { $tokens->insertAt($i, new Token([\T_WHITESPACE, ' '])); } } } /** * @return array{start: int, end: int} */ private function getAfterOperatorRange(Tokens $tokens, int $index): array { $index = $tokens->getNextMeaningfulToken($index); $range = ['start' => $index]; while (true) { $nextIndex = $tokens->getNextMeaningfulToken($index); if (null === $nextIndex || $tokens[$nextIndex]->equalsAny([';', ',', [\T_CLOSE_TAG]])) { break; } $blockType = Tokens::detectBlockType($tokens[$nextIndex]); if (null === $blockType) { $index = $nextIndex; continue; } if (false === $blockType['isStart']) { break; } $index = $tokens->findBlockEnd($blockType['type'], $nextIndex); } $range['end'] = $index; return $range; } /** * @return array{start: int, end: int} */ private function getBeforeOperatorRange(Tokens $tokens, int $index): array { static $blockOpenTypes; if (null === $blockOpenTypes) { $blockOpenTypes = [',']; // not a true "block type", but speeds up things foreach (Tokens::getBlockEdgeDefinitions() as $definition) { $blockOpenTypes[] = $definition['start']; } } $controlStructureWithoutBracesTypes = [\T_IF, \T_ELSE, \T_ELSEIF, \T_FOR, \T_FOREACH, \T_WHILE]; $previousIndex = $tokens->getPrevMeaningfulToken($index); $previousToken = $tokens[$previousIndex]; if ($tokens[$previousIndex]->equalsAny($blockOpenTypes)) { return ['start' => $index, 'end' => $index]; } $range = ['end' => $previousIndex]; $index = $previousIndex; while ($previousToken->equalsAny([ '$', ']', ')', [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], [CT::T_DYNAMIC_PROP_BRACE_CLOSE], [CT::T_DYNAMIC_VAR_BRACE_CLOSE], [\T_NS_SEPARATOR], [\T_STRING], [\T_VARIABLE], ])) { $blockType = Tokens::detectBlockType($previousToken); if (null !== $blockType) { $blockStart = $tokens->findBlockStart($blockType['type'], $previousIndex); if ($tokens[$previousIndex]->equals(')') && $tokens[$tokens->getPrevMeaningfulToken($blockStart)]->isGivenKind($controlStructureWithoutBracesTypes)) { break; // we went too far back } $previousIndex = $blockStart; } $index = $previousIndex; $previousIndex = $tokens->getPrevMeaningfulToken($previousIndex); $previousToken = $tokens[$previousIndex]; } if ($previousToken->isGivenKind(\T_OBJECT_OPERATOR)) { $index = $this->getBeforeOperatorRange($tokens, $previousIndex)['start']; } elseif ($previousToken->isGivenKind(\T_PAAMAYIM_NEKUDOTAYIM)) { $index = $this->getBeforeOperatorRange($tokens, $tokens->getPrevMeaningfulToken($previousIndex))['start']; } $range['start'] = $index; return $range; } /** * @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); } } private function isOperatorCommutative(Token $operatorToken): bool { if ($operatorToken->isGivenKind(\T_COALESCE)) { return false; } // check for commutative kinds if ($operatorToken->equalsAny(['*', '|', '&', '^'])) { // note that for arrays in PHP `+` is not commutative return true; } // check for non-commutative kinds if ($operatorToken->equalsAny(['-', '/', '.', '%', '+'])) { return false; } throw new \InvalidArgumentException(\sprintf('Not supported operator "%s".', $operatorToken->toJson())); } private function belongsToSwitchOrAlternativeSyntax(AlternativeSyntaxAnalyzer $alternativeSyntaxAnalyzer, Tokens $tokens, int $index): bool { $candidate = $index; $index = $tokens->getPrevMeaningfulToken($candidate); if ($tokens[$index]->isGivenKind(\T_DEFAULT)) { return true; } $index = $tokens->getPrevMeaningfulToken($index); if ($tokens[$index]->isGivenKind(\T_CASE)) { return true; } return $alternativeSyntaxAnalyzer->belongsToAlternativeSyntax($tokens, $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/IndentationTrait.php
src/Fixer/IndentationTrait.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer; use PhpCsFixer\Preg; use PhpCsFixer\Tokenizer\Tokens; /** * @internal * * @phpstan-require-implements FixerInterface * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ trait IndentationTrait { private function getLineIndentation(Tokens $tokens, int $index): string { $newlineTokenIndex = $this->getPreviousNewlineTokenIndex($tokens, $index); if (null === $newlineTokenIndex) { return ''; } return $this->extractIndent($this->computeNewLineContent($tokens, $newlineTokenIndex)); } private function extractIndent(string $content): string { if (Preg::match('/\R(\h*)[^\r\n]*$/D', $content, $matches)) { return $matches[1]; } return ''; } private function getPreviousNewlineTokenIndex(Tokens $tokens, int $index): ?int { while ($index > 0) { $index = $tokens->getPrevTokenOfKind($index, [[\T_WHITESPACE], [\T_INLINE_HTML]]); if (null === $index) { break; } if ($this->isNewLineToken($tokens, $index)) { return $index; } } return null; } private function computeNewLineContent(Tokens $tokens, int $index): string { $content = $tokens[$index]->getContent(); if (0 !== $index && $tokens[$index - 1]->isGivenKind([\T_OPEN_TAG, \T_CLOSE_TAG])) { $content = Preg::replace('/\S/', '', $tokens[$index - 1]->getContent()).$content; } return $content; } private function isNewLineToken(Tokens $tokens, int $index): bool { $token = $tokens[$index]; if ( $token->isGivenKind(\T_OPEN_TAG) && isset($tokens[$index + 1]) && !$tokens[$index + 1]->isWhitespace() && Preg::match('/\R/', $token->getContent()) ) { return true; } if (!$tokens[$index]->isGivenKind([\T_WHITESPACE, \T_INLINE_HTML])) { return false; } return Preg::match('/\R/', $this->computeNewLineContent($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/DocBlockAnnotationTrait.php
src/Fixer/DocBlockAnnotationTrait.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer; use PhpCsFixer\DocBlock\DocBlock; use PhpCsFixer\DocBlock\Line; use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer; use PhpCsFixer\Tokenizer\Analyzer\FullyQualifiedNameAnalyzer; use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; use PhpCsFixer\Tokenizer\CT; use PhpCsFixer\Tokenizer\FCT; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; /** * @internal * * @phpstan-require-implements FixerInterface * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ trait DocBlockAnnotationTrait { final protected function getDocBlockIndex(Tokens $tokens, int $index): int { do { $index = $tokens->getPrevNonWhitespace($index); if ($tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { $index = $tokens->getPrevTokenOfKind($index, [[\T_ATTRIBUTE]]); } } while ($tokens[$index]->isGivenKind([\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_FINAL, \T_ABSTRACT, \T_COMMENT, FCT::T_ATTRIBUTE, FCT::T_READONLY])); return $index; } /** * @param list<string> $preventingAnnotations * @param list<non-empty-lowercase-string> $preventingAttributes */ final protected function ensureIsDocBlockWithAnnotation( Tokens $tokens, int $index, string $annotation, array $preventingAnnotations, array $preventingAttributes ): void { $docBlockIndex = $this->getDocBlockIndex($tokens, $index); if ($this->isPreventedByAttribute($tokens, $index, $preventingAttributes)) { return; } if ($tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT)) { $this->updateDocBlockIfNeeded($tokens, $docBlockIndex, $annotation, $preventingAnnotations); } else { $this->createDocBlock($tokens, $docBlockIndex, $annotation); } } protected function createDocBlock(Tokens $tokens, int $docBlockIndex, string $annotation): void { $lineEnd = $this->whitespacesConfig->getLineEnding(); $originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex)); $toInsert = [ new Token([\T_DOC_COMMENT, "/**{$lineEnd}{$originalIndent} * @{$annotation}{$lineEnd}{$originalIndent} */"]), new Token([\T_WHITESPACE, $lineEnd.$originalIndent]), ]; $index = $tokens->getNextMeaningfulToken($docBlockIndex); $tokens->insertAt($index, $toInsert); if (!$tokens[$index - 1]->isGivenKind(\T_WHITESPACE)) { $extraNewLines = $this->whitespacesConfig->getLineEnding(); if (!$tokens[$index - 1]->isGivenKind(\T_OPEN_TAG)) { $extraNewLines .= $this->whitespacesConfig->getLineEnding(); } $tokens->insertAt($index, [ new Token([\T_WHITESPACE, $extraNewLines.WhitespacesAnalyzer::detectIndent($tokens, $index)]), ]); } } /** * @param list<string> $preventingAnnotations */ private function updateDocBlockIfNeeded( Tokens $tokens, int $docBlockIndex, string $annotation, array $preventingAnnotations ): void { $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); foreach ($preventingAnnotations as $preventingAnnotation) { if ([] !== $doc->getAnnotationsOfType($preventingAnnotation)) { return; } } $doc = $this->makeDocBlockMultiLineIfNeeded($doc, $tokens, $docBlockIndex, $annotation); $lines = $this->addAnnotation($doc, $tokens, $docBlockIndex, $annotation); $lines = implode('', $lines); $tokens->getNamespaceDeclarations(); $tokens[$docBlockIndex] = new Token([\T_DOC_COMMENT, $lines]); } /** * @param list<lowercase-string> $preventingAttributes */ private function isPreventedByAttribute(Tokens $tokens, int $index, array $preventingAttributes): bool { if ([] === $preventingAttributes) { return false; } do { $index = $tokens->getPrevMeaningfulToken($index); } while ($tokens[$index]->isGivenKind([\T_FINAL, FCT::T_READONLY])); if (!$tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { return false; } $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); $fullyQualifiedNameAnalyzer = new FullyQualifiedNameAnalyzer($tokens); foreach (AttributeAnalyzer::collect($tokens, $index) as $attributeAnalysis) { foreach ($attributeAnalysis->getAttributes() as $attribute) { if (\in_array(strtolower($fullyQualifiedNameAnalyzer->getFullyQualifiedName($attribute['name'], $attribute['start'], NamespaceUseAnalysis::TYPE_CLASS)), $preventingAttributes, true)) { return true; } } } return false; } /** * @return non-empty-list<Line> */ private function addAnnotation( DocBlock $docBlock, Tokens $tokens, int $docBlockIndex, string $annotation ): array { $lines = $docBlock->getLines(); $originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $docBlockIndex); $lineEnd = $this->whitespacesConfig->getLineEnding(); array_splice($lines, -1, 0, [new Line($originalIndent.' * @'.$annotation.$lineEnd)]); return $lines; } private function makeDocBlockMultiLineIfNeeded( DocBlock $doc, Tokens $tokens, int $docBlockIndex, string $annotation ): DocBlock { $lines = $doc->getLines(); if (1 === \count($lines) && [] === $doc->getAnnotationsOfType($annotation)) { $indent = WhitespacesAnalyzer::detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex)); $doc->makeMultiLine($indent, $this->whitespacesConfig->getLineEnding()); return $doc; } return $doc; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/ConfigurableFixerTrait.php
src/Fixer/ConfigurableFixerTrait.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer; use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; use PhpCsFixer\ConfigurationException\InvalidForEnvFixerConfigurationException; use PhpCsFixer\ConfigurationException\RequiredFixerConfigurationException; use PhpCsFixer\Console\Application; use PhpCsFixer\FixerConfiguration\DeprecatedFixerOption; use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; use PhpCsFixer\FixerConfiguration\InvalidOptionsForEnvException; use PhpCsFixer\Future; use Symfony\Component\OptionsResolver\Exception\ExceptionInterface; use Symfony\Component\OptionsResolver\Exception\MissingOptionsException; /** * @internal * * @template TFixerInputConfig of array<string, mixed> * @template TFixerComputedConfig of array<string, mixed> * * @phpstan-require-implements ConfigurableFixerInterface<TFixerInputConfig, TFixerComputedConfig> * * @author Dariusz Rumiński <dariusz.ruminski@gmail.com> * * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ trait ConfigurableFixerTrait { /** * @var null|TFixerComputedConfig */ protected ?array $configuration = null; private ?FixerConfigurationResolverInterface $configurationDefinition = null; /** * @param TFixerInputConfig $configuration */ final public function configure(array $configuration): void { $this->configurePreNormalisation($configuration); foreach ($this->getConfigurationDefinition()->getOptions() as $option) { if (!$option instanceof DeprecatedFixerOption) { continue; } $name = $option->getName(); if (\array_key_exists($name, $configuration)) { Future::triggerDeprecation(new \InvalidArgumentException(\sprintf( 'Option "%s" for rule "%s" is deprecated and will be removed in version %d.0. %s', $name, $this->getName(), Application::getMajorVersion() + 1, str_replace('`', '"', $option->getDeprecationMessage()), ))); } } try { $this->configuration = $this->getConfigurationDefinition()->resolve($configuration); // @phpstan-ignore-line ->configuration typehint is autogenerated base on ConfigurationDefinition } catch (MissingOptionsException $exception) { throw new RequiredFixerConfigurationException( $this->getName(), \sprintf('Missing required configuration: %s', $exception->getMessage()), $exception, ); } catch (InvalidOptionsForEnvException $exception) { throw new InvalidForEnvFixerConfigurationException( $this->getName(), \sprintf('Invalid configuration for env: %s', $exception->getMessage()), $exception, ); } catch (ExceptionInterface $exception) { throw new InvalidFixerConfigurationException( $this->getName(), \sprintf('Invalid configuration: %s', $exception->getMessage()), $exception, ); } $this->configurePostNormalisation(); } final public function getConfigurationDefinition(): FixerConfigurationResolverInterface { if (null === $this->configurationDefinition) { $this->configurationDefinition = $this->createConfigurationDefinition(); } return $this->configurationDefinition; } abstract public function getName(): string; /** * One can override me. * * @param TFixerInputConfig $configuration */ protected function configurePreNormalisation(array &$configuration): void { // 🤔 ideally this method won't be needed, maybe we can remove it over time } /** * One can override me. */ protected function configurePostNormalisation(): void { // 🤔 ideally this method won't be needed, maybe we can remove it over time } abstract protected function createConfigurationDefinition(): FixerConfigurationResolverInterface; }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false
PHP-CS-Fixer/PHP-CS-Fixer
https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/63b024eaaf8a48445494964bd21a6c38c788f40f/src/Fixer/AbstractIncrementOperatorFixer.php
src/Fixer/AbstractIncrementOperatorFixer.php
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer; use PhpCsFixer\AbstractFixer; use PhpCsFixer\Tokenizer\Tokens; /** * @no-named-arguments Parameter names are not covered by the backward compatibility promise. */ abstract class AbstractIncrementOperatorFixer extends AbstractFixer { final protected function findStart(Tokens $tokens, int $index): int { do { $index = $tokens->getPrevMeaningfulToken($index); $token = $tokens[$index]; $blockType = Tokens::detectBlockType($token); if (null !== $blockType && !$blockType['isStart']) { $index = $tokens->findBlockStart($blockType['type'], $index); $token = $tokens[$index]; } } while (!$token->equalsAny(['$', [\T_VARIABLE]])); $prevIndex = $tokens->getPrevMeaningfulToken($index); $prevToken = $tokens[$prevIndex]; if ($prevToken->equals('$')) { return $this->findStart($tokens, $index); } if ($prevToken->isObjectOperator()) { return $this->findStart($tokens, $prevIndex); } if ($prevToken->isGivenKind(\T_PAAMAYIM_NEKUDOTAYIM)) { $prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex); if (!$tokens[$prevPrevIndex]->isGivenKind([\T_STATIC, \T_STRING])) { return $this->findStart($tokens, $prevIndex); } $index = $tokens->getTokenNotOfKindsSibling($prevIndex, -1, [\T_NS_SEPARATOR, \T_STATIC, \T_STRING]); $index = $tokens->getNextMeaningfulToken($index); } return $index; } }
php
MIT
63b024eaaf8a48445494964bd21a6c38c788f40f
2026-01-04T15:02:54.911792Z
false