EofEndingFixer.php 1.5 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\Token;
  13. use Symfony\CS\Tokenizer\Tokens;
  14. /**
  15. * Fixer for rules defined in PSR2 ¶2.2.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. */
  19. class EofEndingFixer extends AbstractFixer
  20. {
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public function fix(\SplFileInfo $file, $content)
  25. {
  26. $tokens = Tokens::fromCode($content);
  27. $count = $tokens->count();
  28. if (0 === $count) {
  29. return '';
  30. }
  31. $token = $tokens[$count - 1];
  32. if ($token->isGivenKind(array(T_INLINE_HTML, T_CLOSE_TAG, T_OPEN_TAG))) {
  33. return $content;
  34. }
  35. if ($token->isWhitespace()) {
  36. $lineBreak = false === strrpos($token->getContent(), "\r") ? "\n" : "\r\n";
  37. $token->setContent($lineBreak);
  38. } else {
  39. $tokens->insertAt($count, new Token(array(T_WHITESPACE, "\n")));
  40. }
  41. return $tokens->generateCode();
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function getDescription()
  47. {
  48. return 'A file must always end with a single empty line feed.';
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function getPriority()
  54. {
  55. // must run last to be sure the file is properly formatted before it runs
  56. return -50;
  57. }
  58. }