ReturnFixer.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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\All;
  11. use Symfony\CS\FixerInterface;
  12. use Symfony\CS\Token;
  13. use Symfony\CS\Tokens;
  14. /**
  15. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  16. */
  17. class ReturnFixer implements FixerInterface
  18. {
  19. /**
  20. * {@inheritdoc}
  21. */
  22. public function fix(\SplFileInfo $file, $content)
  23. {
  24. $tokens = Tokens::fromCode($content);
  25. for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) {
  26. $token = $tokens[$index];
  27. if (!$token->isGivenKind(T_RETURN)) {
  28. continue;
  29. }
  30. $prevNonWhitespaceToken = $tokens->getPrevNonWhitespace($index);
  31. if (!in_array($prevNonWhitespaceToken->content, array(';', '}'), true)) {
  32. continue;
  33. }
  34. $prevToken = $tokens[$index - 1];
  35. if ($prevToken->isWhitespace()) {
  36. $parts = explode("\n", $prevToken->content);
  37. $countParts = count($parts);
  38. if (1 === $countParts) {
  39. $prevToken->content = rtrim($prevToken->content, " \t")."\n\n";
  40. } elseif (count($parts) <= 2) {
  41. $prevToken->content = "\n".$prevToken->content;
  42. }
  43. } else {
  44. $tokens->insertAt($index, new Token(array(T_WHITESPACE, "\n\n")));
  45. ++$index;
  46. ++$limit;
  47. }
  48. }
  49. return $tokens->generateCode();
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public function getLevel()
  55. {
  56. return FixerInterface::ALL_LEVEL;
  57. }
  58. /**
  59. * {@inheritdoc}
  60. */
  61. public function getPriority()
  62. {
  63. return 0;
  64. }
  65. /**
  66. * {@inheritdoc}
  67. */
  68. public function supports(\SplFileInfo $file)
  69. {
  70. return true;
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. public function getName()
  76. {
  77. return 'return';
  78. }
  79. /**
  80. * {@inheritdoc}
  81. */
  82. public function getDescription()
  83. {
  84. return 'An empty line feed should precede a return statement.';
  85. }
  86. }