PhpUnitFqcnAnnotationFixer.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 PhpCsFixer\Fixer\PhpUnit;
  12. use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
  13. use PhpCsFixer\FixerDefinition\CodeSample;
  14. use PhpCsFixer\FixerDefinition\FixerDefinition;
  15. use PhpCsFixer\Preg;
  16. use PhpCsFixer\Tokenizer\Token;
  17. use PhpCsFixer\Tokenizer\Tokens;
  18. /**
  19. * @author Roland Franssen <franssen.roland@gmail.com>
  20. */
  21. final class PhpUnitFqcnAnnotationFixer extends AbstractPhpUnitFixer
  22. {
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function getDefinition()
  27. {
  28. return new FixerDefinition(
  29. 'PHPUnit annotations should be a FQCNs including a root namespace.',
  30. [new CodeSample(
  31. '<?php
  32. final class MyTest extends \PHPUnit_Framework_TestCase
  33. {
  34. /**
  35. * @expectedException InvalidArgumentException
  36. * @covers Project\NameSpace\Something
  37. * @coversDefaultClass Project\Default
  38. * @uses Project\Test\Util
  39. */
  40. public function testSomeTest()
  41. {
  42. }
  43. }
  44. '
  45. )]
  46. );
  47. }
  48. /**
  49. * {@inheritdoc}
  50. *
  51. * Must run before NoUnusedImportsFixer, PhpUnitOrderedCoversFixer.
  52. */
  53. public function getPriority()
  54. {
  55. return -9;
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. protected function applyPhpUnitClassFix(Tokens $tokens, $startIndex, $endIndex)
  61. {
  62. $prevDocCommentIndex = $tokens->getPrevTokenOfKind($startIndex, [[T_DOC_COMMENT]]);
  63. if (null !== $prevDocCommentIndex) {
  64. $startIndex = $prevDocCommentIndex;
  65. }
  66. $this->fixPhpUnitClass($tokens, $startIndex, $endIndex);
  67. }
  68. /**
  69. * @param int $startIndex
  70. * @param int $endIndex
  71. */
  72. private function fixPhpUnitClass(Tokens $tokens, $startIndex, $endIndex)
  73. {
  74. for ($index = $startIndex; $index < $endIndex; ++$index) {
  75. if ($tokens[$index]->isGivenKind(T_DOC_COMMENT)) {
  76. $tokens[$index] = new Token([T_DOC_COMMENT, Preg::replace(
  77. '~^(\s*\*\s*@(?:expectedException|covers|coversDefaultClass|uses)\h+)(?!(?:self|static)::)(\w.*)$~m',
  78. '$1\\\\$2',
  79. $tokens[$index]->getContent()
  80. )]);
  81. }
  82. }
  83. }
  84. }