NoSpaceAroundDoubleColonFixer.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of PHP CS Fixer.
  5. *
  6. * (c) Fabien Potencier <fabien@symfony.com>
  7. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  8. *
  9. * This source file is subject to the MIT license that is bundled
  10. * with this source code in the file LICENSE.
  11. */
  12. namespace PhpCsFixer\Fixer\Operator;
  13. use PhpCsFixer\AbstractFixer;
  14. use PhpCsFixer\FixerDefinition\CodeSample;
  15. use PhpCsFixer\FixerDefinition\FixerDefinition;
  16. use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
  17. use PhpCsFixer\Tokenizer\Tokens;
  18. final class NoSpaceAroundDoubleColonFixer extends AbstractFixer
  19. {
  20. /**
  21. * {@inheritdoc}
  22. */
  23. public function getDefinition(): FixerDefinitionInterface
  24. {
  25. return new FixerDefinition(
  26. 'There must be no space around double colons (also called Scope Resolution Operator or Paamayim Nekudotayim).',
  27. [new CodeSample("\n<?php echo Foo\\Bar :: class;\n")]
  28. );
  29. }
  30. /**
  31. * {@inheritdoc}
  32. */
  33. public function isCandidate(Tokens $tokens): bool
  34. {
  35. return $tokens->isTokenKindFound(T_DOUBLE_COLON);
  36. }
  37. /**
  38. * {@inheritdoc}
  39. */
  40. protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
  41. {
  42. for ($index = \count($tokens) - 2; $index > 1; --$index) {
  43. if ($tokens[$index]->isGivenKind(T_DOUBLE_COLON)) {
  44. $this->removeSpace($tokens, $index, 1);
  45. $this->removeSpace($tokens, $index, -1);
  46. }
  47. }
  48. }
  49. private function removeSpace(Tokens $tokens, int $index, int $direction): void
  50. {
  51. if (!$tokens[$index + $direction]->isWhitespace()) {
  52. return;
  53. }
  54. if ($tokens[$tokens->getNonWhitespaceSibling($index, $direction)]->isComment()) {
  55. return;
  56. }
  57. $tokens->clearAt($index + $direction);
  58. }
  59. }