WhitespaceAfterCommaInArrayFixer.php 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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\ArrayNotation;
  13. use PhpCsFixer\AbstractFixer;
  14. use PhpCsFixer\Fixer\ConfigurableFixerInterface;
  15. use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
  16. use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
  17. use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
  18. use PhpCsFixer\FixerDefinition\CodeSample;
  19. use PhpCsFixer\FixerDefinition\FixerDefinition;
  20. use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
  21. use PhpCsFixer\Preg;
  22. use PhpCsFixer\Tokenizer\CT;
  23. use PhpCsFixer\Tokenizer\Token;
  24. use PhpCsFixer\Tokenizer\Tokens;
  25. /**
  26. * @author Adam Marczuk <adam@marczuk.info>
  27. */
  28. final class WhitespaceAfterCommaInArrayFixer extends AbstractFixer implements ConfigurableFixerInterface
  29. {
  30. public function getDefinition(): FixerDefinitionInterface
  31. {
  32. return new FixerDefinition(
  33. 'In array declaration, there MUST be a whitespace after each comma.',
  34. [
  35. new CodeSample("<?php\n\$sample = array(1,'a',\$b,);\n"),
  36. new CodeSample("<?php\n\$sample = [1,2, 3, 4, 5];\n", ['ensure_single_space' => true]),
  37. ]
  38. );
  39. }
  40. public function isCandidate(Tokens $tokens): bool
  41. {
  42. return $tokens->isAnyTokenKindsFound([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]);
  43. }
  44. protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
  45. {
  46. return new FixerConfigurationResolver([
  47. (new FixerOptionBuilder('ensure_single_space', 'If there are only horizontal whitespaces after the comma then ensure it is a single space.'))
  48. ->setAllowedTypes(['bool'])
  49. ->setDefault(false)
  50. ->getOption(),
  51. ]);
  52. }
  53. protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
  54. {
  55. $tokensToInsert = [];
  56. for ($index = $tokens->count() - 1; $index >= 0; --$index) {
  57. if (!$tokens[$index]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) {
  58. continue;
  59. }
  60. if ($tokens[$index]->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) {
  61. $startIndex = $index;
  62. $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $startIndex);
  63. } else {
  64. $startIndex = $tokens->getNextTokenOfKind($index, ['(']);
  65. $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex);
  66. }
  67. for ($i = $endIndex - 1; $i > $startIndex; --$i) {
  68. $i = $this->skipNonArrayElements($i, $tokens);
  69. if (!$tokens[$i]->equals(',')) {
  70. continue;
  71. }
  72. if (!$tokens[$i + 1]->isWhitespace()) {
  73. $tokensToInsert[$i + 1] = new Token([T_WHITESPACE, ' ']);
  74. } elseif (
  75. true === $this->configuration['ensure_single_space']
  76. && ' ' !== $tokens[$i + 1]->getContent()
  77. && Preg::match('/^\h+$/', $tokens[$i + 1]->getContent())
  78. && (!$tokens[$i + 2]->isComment() || Preg::match('/^\h+$/', $tokens[$i + 3]->getContent()))
  79. ) {
  80. $tokens[$i + 1] = new Token([T_WHITESPACE, ' ']);
  81. }
  82. }
  83. }
  84. if ([] !== $tokensToInsert) {
  85. $tokens->insertSlices($tokensToInsert);
  86. }
  87. }
  88. /**
  89. * Method to move index over the non-array elements like function calls or function declarations.
  90. *
  91. * @return int New index
  92. */
  93. private function skipNonArrayElements(int $index, Tokens $tokens): int
  94. {
  95. if ($tokens[$index]->equals('}')) {
  96. return $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
  97. }
  98. if ($tokens[$index]->equals(')')) {
  99. $startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
  100. $startIndex = $tokens->getPrevMeaningfulToken($startIndex);
  101. if (!$tokens[$startIndex]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) {
  102. return $startIndex;
  103. }
  104. }
  105. if ($tokens[$index]->equals(',') && $this->commaIsPartOfImplementsList($index, $tokens)) {
  106. --$index;
  107. }
  108. return $index;
  109. }
  110. private function commaIsPartOfImplementsList(int $index, Tokens $tokens): bool
  111. {
  112. do {
  113. $index = $tokens->getPrevMeaningfulToken($index);
  114. $current = $tokens[$index];
  115. } while ($current->isGivenKind(T_STRING) || $current->equals(','));
  116. return $current->isGivenKind(T_IMPLEMENTS);
  117. }
  118. }