PhpdocSingleLineVarFixer.php 2.0 KB

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