SingleClassElementPerStatementFixer.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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\ClassNotation;
  13. use PhpCsFixer\AbstractFixer;
  14. use PhpCsFixer\Fixer\ConfigurableFixerInterface;
  15. use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
  16. use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
  17. use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
  18. use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
  19. use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
  20. use PhpCsFixer\FixerDefinition\CodeSample;
  21. use PhpCsFixer\FixerDefinition\FixerDefinition;
  22. use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
  23. use PhpCsFixer\Preg;
  24. use PhpCsFixer\Tokenizer\CT;
  25. use PhpCsFixer\Tokenizer\Token;
  26. use PhpCsFixer\Tokenizer\Tokens;
  27. use PhpCsFixer\Tokenizer\TokensAnalyzer;
  28. /**
  29. * Fixer for rules defined in PSR2 ¶4.2.
  30. *
  31. * @author Javier Spagnoletti <phansys@gmail.com>
  32. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  33. */
  34. final class SingleClassElementPerStatementFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
  35. {
  36. public function isCandidate(Tokens $tokens): bool
  37. {
  38. return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds());
  39. }
  40. /**
  41. * {@inheritdoc}
  42. *
  43. * Must run before ClassAttributesSeparationFixer.
  44. */
  45. public function getPriority(): int
  46. {
  47. return 56;
  48. }
  49. public function getDefinition(): FixerDefinitionInterface
  50. {
  51. return new FixerDefinition(
  52. 'There MUST NOT be more than one property or constant declared per statement.',
  53. [
  54. new CodeSample(
  55. '<?php
  56. final class Example
  57. {
  58. const FOO_1 = 1, FOO_2 = 2;
  59. private static $bar1 = array(1,2,3), $bar2 = [1,2,3];
  60. }
  61. '
  62. ),
  63. new CodeSample(
  64. '<?php
  65. final class Example
  66. {
  67. const FOO_1 = 1, FOO_2 = 2;
  68. private static $bar1 = array(1,2,3), $bar2 = [1,2,3];
  69. }
  70. ',
  71. ['elements' => ['property']]
  72. ),
  73. ]
  74. );
  75. }
  76. protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
  77. {
  78. $analyzer = new TokensAnalyzer($tokens);
  79. $elements = array_reverse($analyzer->getClassyElements(), true);
  80. foreach ($elements as $index => $element) {
  81. if (!\in_array($element['type'], $this->configuration['elements'], true)) {
  82. continue; // not in configuration
  83. }
  84. $this->fixElement($tokens, $element['type'], $index);
  85. }
  86. }
  87. protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
  88. {
  89. $values = ['const', 'property'];
  90. return new FixerConfigurationResolver([
  91. (new FixerOptionBuilder('elements', 'List of strings which element should be modified.'))
  92. ->setDefault($values)
  93. ->setAllowedTypes(['string[]'])
  94. ->setAllowedValues([new AllowedValueSubset($values)])
  95. ->getOption(),
  96. ]);
  97. }
  98. private function fixElement(Tokens $tokens, string $type, int $index): void
  99. {
  100. $tokensAnalyzer = new TokensAnalyzer($tokens);
  101. $repeatIndex = $index;
  102. while (true) {
  103. $repeatIndex = $tokens->getNextMeaningfulToken($repeatIndex);
  104. $repeatToken = $tokens[$repeatIndex];
  105. if ($tokensAnalyzer->isArray($repeatIndex)) {
  106. if ($repeatToken->isGivenKind(T_ARRAY)) {
  107. $repeatIndex = $tokens->getNextTokenOfKind($repeatIndex, ['(']);
  108. $repeatIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $repeatIndex);
  109. } else {
  110. $repeatIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $repeatIndex);
  111. }
  112. continue;
  113. }
  114. if ($repeatToken->equals(';')) {
  115. return; // no repeating found, no fixing needed
  116. }
  117. if ($repeatToken->equals(',')) {
  118. break;
  119. }
  120. }
  121. $start = $tokens->getPrevTokenOfKind($index, [';', '{', '}']);
  122. $this->expandElement(
  123. $tokens,
  124. $type,
  125. $tokens->getNextMeaningfulToken($start),
  126. $tokens->getNextTokenOfKind($index, [';'])
  127. );
  128. }
  129. private function expandElement(Tokens $tokens, string $type, int $startIndex, int $endIndex): void
  130. {
  131. $divisionContent = null;
  132. if ($tokens[$startIndex - 1]->isWhitespace()) {
  133. $divisionContent = $tokens[$startIndex - 1]->getContent();
  134. if (Preg::match('#(\n|\r\n)#', $divisionContent, $matches)) {
  135. $divisionContent = $matches[0].trim($divisionContent, "\r\n");
  136. }
  137. }
  138. // iterate variables to split up
  139. for ($i = $endIndex - 1; $i > $startIndex; --$i) {
  140. $token = $tokens[$i];
  141. if ($token->equals(')')) {
  142. $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $i);
  143. continue;
  144. }
  145. if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_CLOSE)) {
  146. $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $i);
  147. continue;
  148. }
  149. if (!$tokens[$i]->equals(',')) {
  150. continue;
  151. }
  152. $tokens[$i] = new Token(';');
  153. if ($tokens[$i + 1]->isWhitespace()) {
  154. $tokens->clearAt($i + 1);
  155. }
  156. if (null !== $divisionContent && '' !== $divisionContent) {
  157. $tokens->insertAt($i + 1, new Token([T_WHITESPACE, $divisionContent]));
  158. }
  159. // collect modifiers
  160. $sequence = $this->getModifiersSequences($tokens, $type, $startIndex, $endIndex);
  161. $tokens->insertAt($i + 2, $sequence);
  162. }
  163. }
  164. /**
  165. * @return list<Token>
  166. */
  167. private function getModifiersSequences(Tokens $tokens, string $type, int $startIndex, int $endIndex): array
  168. {
  169. if ('property' === $type) {
  170. $tokenKinds = [T_PUBLIC, T_PROTECTED, T_PRIVATE, T_STATIC, T_VAR, T_STRING, T_NS_SEPARATOR, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION];
  171. if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.1+ is required
  172. $tokenKinds[] = T_READONLY;
  173. }
  174. } else {
  175. $tokenKinds = [T_PUBLIC, T_PROTECTED, T_PRIVATE, T_CONST];
  176. }
  177. $sequence = [];
  178. for ($i = $startIndex; $i < $endIndex - 1; ++$i) {
  179. if ($tokens[$i]->isComment()) {
  180. continue;
  181. }
  182. if (!$tokens[$i]->isWhitespace() && !$tokens[$i]->isGivenKind($tokenKinds)) {
  183. break;
  184. }
  185. $sequence[] = clone $tokens[$i];
  186. }
  187. return $sequence;
  188. }
  189. }