ExtraEmptyLinesFixer.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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\Symfony;
  11. use Symfony\CS\AbstractFixer;
  12. use Symfony\CS\Tokenizer\Token;
  13. use Symfony\CS\Tokenizer\Tokens;
  14. /**
  15. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  16. */
  17. class ExtraEmptyLinesFixer extends AbstractFixer
  18. {
  19. /**
  20. * {@inheritdoc}
  21. */
  22. public function fix(\SplFileInfo $file, $content)
  23. {
  24. $tokens = Tokens::fromCode($content);
  25. /** @var Token $token */
  26. foreach ($tokens->findGivenKind(T_WHITESPACE) as $index => $token) {
  27. $content = '';
  28. $count = 0;
  29. if ($index > 0 && $tokens[$index - 1]->isComment()) {
  30. $prevContent = $tokens[$index - 1]->getContent();
  31. $count = strrpos($prevContent, "\n") === strlen($prevContent) - 1 ? 1 : 0;
  32. }
  33. $parts = explode("\n", $token->getContent());
  34. for ($i = 0, $last = count($parts) - 1; $i <= $last; ++$i) {
  35. if ('' === $parts[$i]) {
  36. // if part is empty then we between two \n
  37. ++$count;
  38. } else {
  39. $content .= $parts[$i];
  40. }
  41. if ($i !== $last && $count < 3) {
  42. $content .= "\n";
  43. }
  44. }
  45. $token->setContent($content);
  46. }
  47. return $tokens->generateCode();
  48. }
  49. /**
  50. * {@inheritdoc}
  51. */
  52. public function getDescription()
  53. {
  54. return 'Removes extra empty lines.';
  55. }
  56. /**
  57. * {@inheritdoc}
  58. */
  59. public function getPriority()
  60. {
  61. // should be run after the UnusedUseFixer and DuplicateSemicolonFixer
  62. return -20;
  63. }
  64. }