SingleLineAfterImportsFixer.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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\Token;
  13. use Symfony\CS\Tokenizer\Tokens;
  14. use Symfony\CS\Utils;
  15. /**
  16. * Fixer for rules defined in PSR2 ¶3.
  17. *
  18. * @author Ceeram <ceeram@cakephp.org>
  19. * @author Graham Campbell <graham@mineuk.com>
  20. */
  21. class SingleLineAfterImportsFixer extends AbstractFixer
  22. {
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function fix(\SplFileInfo $file, $content)
  27. {
  28. $tokens = Tokens::fromCode($content);
  29. foreach ($tokens->getImportUseIndexes() as $index) {
  30. $indent = '';
  31. // if previous line ends with comment and current line starts with whitespace, use current indent
  32. if ($tokens[$index - 1]->isWhitespace(array('whitespaces' => " \t")) && $tokens[$index - 2]->isGivenKind(T_COMMENT)) {
  33. $indent = $tokens[$index - 1]->getContent();
  34. } elseif ($tokens[$index - 1]->isWhitespace()) {
  35. $indent = Utils::calculateTrailingWhitespaceIndent($tokens[$index - 1]);
  36. }
  37. $newline = "\n";
  38. // Handle insert index for inline T_COMMENT with whitespace after semicolon
  39. $semicolonIndex = $tokens->getNextTokenOfKind($index, array(';', '{'));
  40. $insertIndex = $semicolonIndex + 1;
  41. if ($tokens[$insertIndex]->isWhitespace(array('whitespaces' => " \t")) && $tokens[$insertIndex + 1]->isComment()) {
  42. ++$insertIndex;
  43. }
  44. // Do not add newline after inline T_COMMENT as it is part of T_COMMENT already
  45. if ($tokens[$insertIndex]->isGivenKind(T_COMMENT)) {
  46. $newline = '';
  47. }
  48. // Increment insert index for inline T_COMMENT or T_DOC_COMMENT
  49. if ($tokens[$insertIndex]->isComment()) {
  50. ++$insertIndex;
  51. }
  52. $afterSemicolon = $tokens->getNextMeaningfulToken($semicolonIndex);
  53. if (!$tokens[$afterSemicolon]->isGivenKind(T_USE)) {
  54. $newline .= "\n";
  55. }
  56. if ($tokens[$insertIndex]->isWhitespace()) {
  57. $nextToken = $tokens[$insertIndex];
  58. $nextToken->setContent($newline.$indent.ltrim($nextToken->getContent()));
  59. } else {
  60. $tokens->insertAt($insertIndex, new Token(array(T_WHITESPACE, $newline.$indent)));
  61. }
  62. }
  63. return $tokens->generateCode();
  64. }
  65. /**
  66. * {@inheritdoc}
  67. */
  68. public function getDescription()
  69. {
  70. return 'Each namespace use MUST go on its own line and there MUST be one blank line after the use statements block.';
  71. }
  72. }