SwitchCaseSpaceFixer.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /*
  3. * This file is part of the PHP CS utility.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace Symfony\CS\Fixer\PSR2;
  11. use Symfony\CS\AbstractFixer;
  12. use Symfony\CS\Tokenizer\Tokens;
  13. /**
  14. * Fixer for rules defined in PSR2 ¶5.2.
  15. *
  16. * @author Sullivan Senechal <soullivaneuh@gmail.com>
  17. */
  18. final class SwitchCaseSpaceFixer extends AbstractFixer
  19. {
  20. /**
  21. * {@inheritdoc}
  22. */
  23. public function fix(\SplFileInfo $file, $content)
  24. {
  25. $tokens = Tokens::fromCode($content);
  26. foreach ($tokens as $index => $token) {
  27. if (!$token->isGivenKind(array(T_CASE, T_DEFAULT))) {
  28. continue;
  29. }
  30. $ternariesCount = 0;
  31. for ($colonIndex = $index + 1; ; ++$colonIndex) {
  32. // We have to skip ternary case for colons.
  33. if ($tokens[$colonIndex]->equals('?')) {
  34. ++$ternariesCount;
  35. }
  36. if ($tokens[$colonIndex]->equals(':')) {
  37. if (0 === $ternariesCount) {
  38. break;
  39. }
  40. --$ternariesCount;
  41. }
  42. }
  43. $valueIndex = $tokens->getPrevNonWhitespace($colonIndex);
  44. if (2 + $valueIndex === $colonIndex) {
  45. $tokens[$valueIndex + 1]->clear();
  46. }
  47. }
  48. return $tokens->generateCode();
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function getDescription()
  54. {
  55. return 'Removes extra spaces between colon and case value.';
  56. }
  57. }