NativeTypeDeclarationCasingFixer.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of PHP CS Fixer.
  5. *
  6. * (c) Fabien Potencier <fabien@symfony.com>
  7. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  8. *
  9. * This source file is subject to the MIT license that is bundled
  10. * with this source code in the file LICENSE.
  11. */
  12. namespace PhpCsFixer\Fixer\Casing;
  13. use PhpCsFixer\AbstractFixer;
  14. use PhpCsFixer\FixerDefinition\CodeSample;
  15. use PhpCsFixer\FixerDefinition\FixerDefinition;
  16. use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
  17. use PhpCsFixer\FixerDefinition\VersionSpecification;
  18. use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
  19. use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis;
  20. use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
  21. use PhpCsFixer\Tokenizer\CT;
  22. use PhpCsFixer\Tokenizer\Token;
  23. use PhpCsFixer\Tokenizer\Tokens;
  24. use PhpCsFixer\Tokenizer\TokensAnalyzer;
  25. final class NativeTypeDeclarationCasingFixer extends AbstractFixer
  26. {
  27. /*
  28. * https://wiki.php.net/rfc/typed_class_constants
  29. * Supported types
  30. * Class constant type declarations support all type declarations supported by PHP,
  31. * except `void`, `callable`, `never`.
  32. *
  33. * array
  34. * bool
  35. * callable
  36. * float
  37. * int
  38. * iterable
  39. * object
  40. * mixed
  41. * parent
  42. * self
  43. * string
  44. * any class or interface name -> not native, so not applicable for this Fixer
  45. * ?type -> not native, `?` has no casing, so not applicable for this Fixer
  46. *
  47. * Not in the list referenced but supported:
  48. * null
  49. * static
  50. */
  51. private const CLASS_CONST_SUPPORTED_HINTS = [
  52. 'array' => true,
  53. 'bool' => true,
  54. 'float' => true,
  55. 'int' => true,
  56. 'iterable' => true,
  57. 'mixed' => true,
  58. 'null' => true,
  59. 'object' => true,
  60. 'parent' => true,
  61. 'self' => true,
  62. 'string' => true,
  63. 'static' => true,
  64. ];
  65. private const CLASS_PROPERTY_SUPPORTED_HINTS = [
  66. 'array' => true,
  67. 'bool' => true,
  68. 'float' => true,
  69. 'int' => true,
  70. 'iterable' => true,
  71. 'mixed' => true,
  72. 'null' => true,
  73. 'object' => true,
  74. 'parent' => true,
  75. 'self' => true,
  76. 'static' => true,
  77. 'string' => true,
  78. ];
  79. private const TYPE_SEPARATION_TYPES = [
  80. CT::T_TYPE_ALTERNATION,
  81. CT::T_TYPE_INTERSECTION,
  82. CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN,
  83. CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE,
  84. ];
  85. /**
  86. * https://secure.php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration.
  87. *
  88. * self PHP 5.0
  89. * array PHP 5.1
  90. * callable PHP 5.4
  91. * bool PHP 7.0
  92. * float PHP 7.0
  93. * int PHP 7.0
  94. * string PHP 7.0
  95. * iterable PHP 7.1
  96. * void PHP 7.1
  97. * object PHP 7.2
  98. * static PHP 8.0 (return type only)
  99. * mixed PHP 8.0
  100. * false PHP 8.0 (union return type only)
  101. * null PHP 8.0 (union return type only)
  102. * never PHP 8.1 (return type only)
  103. * true PHP 8.2 (standalone type: https://wiki.php.net/rfc/true-type)
  104. * false PHP 8.2 (standalone type: https://wiki.php.net/rfc/null-false-standalone-types)
  105. * null PHP 8.2 (standalone type: https://wiki.php.net/rfc/null-false-standalone-types)
  106. *
  107. * @var array<string, true>
  108. */
  109. private array $functionTypeHints;
  110. private FunctionsAnalyzer $functionsAnalyzer;
  111. /**
  112. * @var list<list<int>>
  113. */
  114. private array $propertyTypeModifiers;
  115. public function __construct()
  116. {
  117. parent::__construct();
  118. $this->propertyTypeModifiers = [[T_PRIVATE], [T_PROTECTED], [T_PUBLIC]];
  119. $this->functionTypeHints = [
  120. 'array' => true,
  121. 'bool' => true,
  122. 'callable' => true,
  123. 'float' => true,
  124. 'int' => true,
  125. 'iterable' => true,
  126. 'object' => true,
  127. 'self' => true,
  128. 'string' => true,
  129. 'void' => true,
  130. ];
  131. if (\PHP_VERSION_ID >= 8_00_00) {
  132. $this->functionTypeHints['false'] = true;
  133. $this->functionTypeHints['mixed'] = true;
  134. $this->functionTypeHints['null'] = true;
  135. $this->functionTypeHints['static'] = true;
  136. }
  137. if (\PHP_VERSION_ID >= 8_01_00) {
  138. $this->functionTypeHints['never'] = true;
  139. $this->propertyTypeModifiers[] = [T_READONLY];
  140. }
  141. if (\PHP_VERSION_ID >= 8_02_00) {
  142. $this->functionTypeHints['true'] = true;
  143. }
  144. $this->functionsAnalyzer = new FunctionsAnalyzer();
  145. }
  146. public function getDefinition(): FixerDefinitionInterface
  147. {
  148. return new FixerDefinition(
  149. 'Native type declarations should be used in the correct case.',
  150. [
  151. new CodeSample(
  152. "<?php\nclass Bar {\n public function Foo(CALLABLE \$bar): INT\n {\n return 1;\n }\n}\n"
  153. ),
  154. new VersionSpecificCodeSample(
  155. "<?php\nclass Foo\n{\n const INT BAR = 1;\n}\n",
  156. new VersionSpecification(8_03_00),
  157. ),
  158. ]
  159. );
  160. }
  161. public function isCandidate(Tokens $tokens): bool
  162. {
  163. $classyFound = $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds());
  164. return
  165. $tokens->isAnyTokenKindsFound([T_FUNCTION, T_FN])
  166. || ($classyFound && $tokens->isTokenKindFound(T_STRING))
  167. || (
  168. \PHP_VERSION_ID >= 8_03_00
  169. && $tokens->isTokenKindFound(T_CONST)
  170. && $classyFound
  171. );
  172. }
  173. protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
  174. {
  175. $this->fixFunctions($tokens);
  176. $this->fixClassConstantsAndProperties($tokens);
  177. }
  178. private function fixFunctions(Tokens $tokens): void
  179. {
  180. for ($index = $tokens->count() - 1; $index >= 0; --$index) {
  181. if ($tokens[$index]->isGivenKind([T_FUNCTION, T_FN])) {
  182. $this->fixFunctionReturnType($tokens, $index);
  183. $this->fixFunctionArgumentTypes($tokens, $index);
  184. }
  185. }
  186. }
  187. private function fixFunctionArgumentTypes(Tokens $tokens, int $index): void
  188. {
  189. foreach ($this->functionsAnalyzer->getFunctionArguments($tokens, $index) as $argument) {
  190. $this->fixArgumentType($tokens, $argument->getTypeAnalysis());
  191. }
  192. }
  193. private function fixFunctionReturnType(Tokens $tokens, int $index): void
  194. {
  195. $this->fixArgumentType($tokens, $this->functionsAnalyzer->getFunctionReturnType($tokens, $index));
  196. }
  197. private function fixArgumentType(Tokens $tokens, ?TypeAnalysis $type = null): void
  198. {
  199. if (null === $type) {
  200. return;
  201. }
  202. for ($index = $type->getStartIndex(); $index <= $type->getEndIndex(); ++$index) {
  203. if ($tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(T_NS_SEPARATOR)) {
  204. continue;
  205. }
  206. $this->fixCasing($this->functionTypeHints, $tokens, $index);
  207. }
  208. }
  209. private function fixClassConstantsAndProperties(Tokens $tokens): void
  210. {
  211. $analyzer = new TokensAnalyzer($tokens);
  212. $elements = array_reverse($analyzer->getClassyElements(), true);
  213. foreach ($elements as $index => $element) {
  214. if ('const' === $element['type']) {
  215. if (\PHP_VERSION_ID >= 8_03_00 && !$this->isConstWithoutType($tokens, $index)) {
  216. foreach ($this->getNativeTypeHintCandidatesForConstant($tokens, $index) as $nativeTypeHintIndex) {
  217. $this->fixCasing($this::CLASS_CONST_SUPPORTED_HINTS, $tokens, $nativeTypeHintIndex);
  218. }
  219. }
  220. continue;
  221. }
  222. if ('property' === $element['type']) {
  223. foreach ($this->getNativeTypeHintCandidatesForProperty($tokens, $index) as $nativeTypeHintIndex) {
  224. $this->fixCasing($this::CLASS_PROPERTY_SUPPORTED_HINTS, $tokens, $nativeTypeHintIndex);
  225. }
  226. }
  227. }
  228. }
  229. /** @return iterable<int> */
  230. private function getNativeTypeHintCandidatesForConstant(Tokens $tokens, int $index): iterable
  231. {
  232. $constNameIndex = $this->getConstNameIndex($tokens, $index);
  233. $index = $this->getFirstIndexOfType($tokens, $index);
  234. do {
  235. $typeEnd = $this->getTypeEnd($tokens, $index, $constNameIndex);
  236. if ($typeEnd === $index) {
  237. yield $index;
  238. }
  239. do {
  240. $index = $tokens->getNextMeaningfulToken($index);
  241. } while ($tokens[$index]->isGivenKind(self::TYPE_SEPARATION_TYPES));
  242. } while ($index < $constNameIndex);
  243. }
  244. private function isConstWithoutType(Tokens $tokens, int $index): bool
  245. {
  246. $index = $tokens->getNextMeaningfulToken($index);
  247. return $tokens[$index]->isGivenKind(T_STRING) && $tokens[$tokens->getNextMeaningfulToken($index)]->equals('=');
  248. }
  249. private function getConstNameIndex(Tokens $tokens, int $index): int
  250. {
  251. return $tokens->getPrevMeaningfulToken(
  252. $tokens->getNextTokenOfKind($index, ['=']),
  253. );
  254. }
  255. /** @return iterable<int> */
  256. private function getNativeTypeHintCandidatesForProperty(Tokens $tokens, int $index): iterable
  257. {
  258. $propertyNameIndex = $index;
  259. $index = $tokens->getPrevTokenOfKind($index, $this->propertyTypeModifiers);
  260. $index = $this->getFirstIndexOfType($tokens, $index);
  261. do {
  262. $typeEnd = $this->getTypeEnd($tokens, $index, $propertyNameIndex);
  263. if ($typeEnd === $index) {
  264. yield $index;
  265. }
  266. do {
  267. $index = $tokens->getNextMeaningfulToken($index);
  268. } while ($tokens[$index]->isGivenKind(self::TYPE_SEPARATION_TYPES));
  269. } while ($index < $propertyNameIndex);
  270. return [];
  271. }
  272. private function getFirstIndexOfType(Tokens $tokens, int $index): int
  273. {
  274. $index = $tokens->getNextMeaningfulToken($index);
  275. if ($tokens[$index]->isGivenKind(CT::T_NULLABLE_TYPE)) {
  276. $index = $tokens->getNextMeaningfulToken($index);
  277. }
  278. if ($tokens[$index]->isGivenKind(CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN)) {
  279. $index = $tokens->getNextMeaningfulToken($index);
  280. }
  281. return $index;
  282. }
  283. private function getTypeEnd(Tokens $tokens, int $index, int $upperLimit): int
  284. {
  285. if (!$tokens[$index]->isGivenKind([T_STRING, T_NS_SEPARATOR])) {
  286. return $index; // callable, array, self, static, etc.
  287. }
  288. $endIndex = $index;
  289. while ($tokens[$index]->isGivenKind([T_STRING, T_NS_SEPARATOR]) && $index < $upperLimit) {
  290. $endIndex = $index;
  291. $index = $tokens->getNextMeaningfulToken($index);
  292. }
  293. return $endIndex;
  294. }
  295. /**
  296. * @param array<string, true> $supportedTypeHints
  297. */
  298. private function fixCasing(array $supportedTypeHints, Tokens $tokens, int $index): void
  299. {
  300. $typeContent = $tokens[$index]->getContent();
  301. $typeContentLower = strtolower($typeContent);
  302. if (isset($supportedTypeHints[$typeContentLower]) && $typeContent !== $typeContentLower) {
  303. $tokens[$index] = new Token([$tokens[$index]->getId(), $typeContentLower]);
  304. }
  305. }
  306. }