PageRenderTime 46ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/Symfony/CS/Fixer/Symfony/SpacesCastFixer.php

http://github.com/fabpot/PHP-CS-Fixer
PHP | 74 lines | 39 code | 10 blank | 25 comment | 2 complexity | f730fc8b1825399d27d6d57cc781b6ba MD5 | raw file
  1. <?php
  2. /*
  3. * This file is part of PHP CS Fixer.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  7. *
  8. * This source file is subject to the MIT license that is bundled
  9. * with this source code in the file LICENSE.
  10. */
  11. namespace Symfony\CS\Fixer\Symfony;
  12. use Symfony\CS\AbstractFixer;
  13. use Symfony\CS\Tokenizer\Token;
  14. use Symfony\CS\Tokenizer\Tokens;
  15. /**
  16. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  17. */
  18. class SpacesCastFixer extends AbstractFixer
  19. {
  20. /**
  21. * {@inheritdoc}
  22. */
  23. public function fix(\SplFileInfo $file, $content)
  24. {
  25. static $insideCastSpaceReplaceMap = array(
  26. ' ' => '',
  27. "\t" => '',
  28. "\n" => '',
  29. "\r" => '',
  30. "\0" => '',
  31. "\x0B" => '',
  32. );
  33. $tokens = Tokens::fromCode($content);
  34. foreach ($tokens as $index => $token) {
  35. if ($token->isCast()) {
  36. $token->setContent(strtr($token->getContent(), $insideCastSpaceReplaceMap));
  37. // force single whitespace after cast token:
  38. if ($tokens[$index + 1]->isWhitespace(array('whitespaces' => " \t"))) {
  39. // - if next token is whitespaces that contains only spaces and tabs - override next token with single space
  40. $tokens[$index + 1]->setContent(' ');
  41. } elseif (!$tokens[$index + 1]->isWhitespace()) {
  42. // - if next token is not whitespaces that contains spaces, tabs and new lines - append single space to current token
  43. $tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
  44. }
  45. }
  46. }
  47. return $tokens->generateCode();
  48. }
  49. /**
  50. * {@inheritdoc}
  51. */
  52. public function getDescription()
  53. {
  54. return 'A single space should be between cast and variable.';
  55. }
  56. /**
  57. * {@inheritdoc}
  58. */
  59. public function getPriority()
  60. {
  61. // should be ran after the ShortBoolCastFixer
  62. return -10;
  63. }
  64. }