SpacesCastFixer.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 SpacesCastFixer implements FixerInterface
  18. {
  19. /**
  20. * {@inheritdoc}
  21. */
  22. public function fix(\SplFileInfo $file, $content)
  23. {
  24. static $insideCastSpaceReplaceMap = array (
  25. ' ' => '',
  26. "\t" => '',
  27. "\n" => '',
  28. );
  29. $tokens = Tokens::fromCode($content);
  30. foreach ($tokens as $index => $token) {
  31. if ($token->isCast()) {
  32. $token->content = strtr($token->content, $insideCastSpaceReplaceMap);
  33. // force single whitespace after cast token:
  34. if ($tokens[$index + 1]->isWhitespace(array('whitespaces' => " \t"))) {
  35. // - if next token is whitespaces that contains only spaces and tabs - override next token with single space
  36. $tokens[$index + 1]->content = ' ';
  37. } elseif (!$tokens[$index + 1]->isWhitespace()) {
  38. // - if next token is not whitespaces that contains spaces, tabs and new lines - append single space to current token
  39. $tokens->insertAt($index + 1, new Token(' '));
  40. }
  41. }
  42. }
  43. return $tokens->generateCode();
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. public function getLevel()
  49. {
  50. return FixerInterface::ALL_LEVEL;
  51. }
  52. /**
  53. * {@inheritdoc}
  54. */
  55. public function getPriority()
  56. {
  57. return 0;
  58. }
  59. /**
  60. * {@inheritdoc}
  61. */
  62. public function supports(\SplFileInfo $file)
  63. {
  64. return true;
  65. }
  66. /**
  67. * {@inheritdoc}
  68. */
  69. public function getName()
  70. {
  71. return 'spaces_cast';
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public function getDescription()
  77. {
  78. return 'A single space should be between cast and variable.';
  79. }
  80. }