ElseifFixer.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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.1.
  15. *
  16. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  17. */
  18. class ElseifFixer extends AbstractFixer
  19. {
  20. /**
  21. * Replace all `else if` (T_ELSE T_IF) with `elseif` (T_ELSEIF).
  22. *
  23. * {@inheritdoc}
  24. */
  25. public function fix(\SplFileInfo $file, $content)
  26. {
  27. $tokens = Tokens::fromCode($content);
  28. foreach ($tokens->findGivenKind(T_ELSE) as $index => $token) {
  29. $nextIndex = $tokens->getNextNonWhitespace($index);
  30. $nextToken = $tokens[$nextIndex];
  31. // if next meaning token is not T_IF - continue searching, this is not the case for fixing
  32. if (!$nextToken->isGivenKind(T_IF)) {
  33. continue;
  34. }
  35. // now we have T_ELSE following by T_IF so we could fix this
  36. // 1. clear whitespaces between T_ELSE and T_IF
  37. $tokens[$index + 1]->clear();
  38. // 2. change token from T_ELSE into T_ELSEIF
  39. $tokens->overrideAt($index, array(T_ELSEIF, 'elseif', $token->getLine()));
  40. // 3. clear succeeding T_IF
  41. $nextToken->clear();
  42. }
  43. // handle `T_ELSE T_WHITESPACE T_IF` treated as single `T_ELSEIF` by HHVM
  44. // see https://github.com/facebook/hhvm/issues/4796
  45. if (defined('HHVM_VERSION')) {
  46. foreach ($tokens->findGivenKind(T_ELSEIF) as $token) {
  47. $token->setContent('elseif');
  48. }
  49. }
  50. return $tokens->generateCode();
  51. }
  52. /**
  53. * {@inheritdoc}
  54. */
  55. public function getDescription()
  56. {
  57. return 'The keyword elseif should be used instead of else if so that all control keywords looks like single words.';
  58. }
  59. }