PhpdocSingleLineVarFixer.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace PharIo\CSFixer;
  3. use PhpCsFixer\Fixer\FixerInterface;
  4. use PhpCsFixer\FixerDefinition\CodeSample;
  5. use PhpCsFixer\FixerDefinition\FixerDefinition;
  6. use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
  7. use PhpCsFixer\Tokenizer\Tokens;
  8. use PhpCsFixer\Tokenizer\Token;
  9. /**
  10. * Main implementation taken from kubawerlos/php-cs-fixer-customere-fixers
  11. * Copyright (c) 2018 Kuba Werłos
  12. *
  13. * Slightly modified to work without the gazillion of composer dependencies
  14. *
  15. * Original:
  16. * https://github.com/kubawerlos/php-cs-fixer-custom-fixers/blob/master/src/Fixer/PhpdocSingleLineVarFixer.php
  17. *
  18. */
  19. class PhpdocSingleLineVarFixer implements FixerInterface {
  20. public function getDefinition(): FixerDefinitionInterface {
  21. return new FixerDefinition(
  22. '`@var` annotation must be in single line when is the only content.',
  23. [new CodeSample('<?php
  24. /**
  25. * @var string
  26. */
  27. ')]
  28. );
  29. }
  30. public function isCandidate(Tokens $tokens): bool {
  31. return $tokens->isTokenKindFound(T_DOC_COMMENT);
  32. }
  33. public function isRisky(): bool {
  34. return false;
  35. }
  36. public function fix(\SplFileInfo $file, Tokens $tokens): void {
  37. foreach($tokens as $index => $token) {
  38. if (!$token->isGivenKind(T_DOC_COMMENT)) {
  39. continue;
  40. }
  41. if (\stripos($token->getContent(), '@var') === false) {
  42. continue;
  43. }
  44. if (preg_match('#^/\*\*[\s\*]+(@var[^\r\n]+)[\s\*]*\*\/$#u', $token->getContent(), $matches) !== 1) {
  45. continue;
  46. }
  47. $newContent = '/** ' . \rtrim($matches[1]) . ' */';
  48. if ($newContent === $token->getContent()) {
  49. continue;
  50. }
  51. $tokens[$index] = new Token([T_DOC_COMMENT, $newContent]);
  52. }
  53. }
  54. public function getPriority(): int {
  55. return 0;
  56. }
  57. public function getName(): string {
  58. return 'PharIo/phpdoc_single_line_var_fixer';
  59. }
  60. public function supports(\SplFileInfo $file): bool {
  61. return true;
  62. }
  63. }