Last active
September 2, 2024 12:31
-
-
Save ivastly/f23c1dd793145272e07dda3f68ed128d to your computer and use it in GitHub Desktop.
Rector rule to replace `test_` prefix with [#Test] attribute
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| declare(strict_types=1); | |
| namespace Zable\Rector\Rules; | |
| use PhpParser\Node; | |
| use PhpParser\Node\Attribute; | |
| use PhpParser\Node\AttributeGroup; | |
| use PhpParser\Node\Name\FullyQualified; | |
| use PhpParser\Node\Stmt\ClassMethod; | |
| use PHPUnit\Framework\Attributes\Test; | |
| use Rector\PHPUnit\NodeAnalyzer\TestsNodeAnalyzer; | |
| use Rector\Rector\AbstractRector; | |
| use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; | |
| use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; | |
| final class ConvertTestPrefixToAttributeRector extends AbstractRector | |
| { | |
| public function __construct( | |
| private readonly TestsNodeAnalyzer $testsNodeAnalyzer, | |
| ) { | |
| } | |
| #[\Override] | |
| public function getRuleDefinition(): RuleDefinition | |
| { | |
| return new RuleDefinition('Change `test_` prefix to `#[Test]` attribute', | |
| [ | |
| new CodeSample( | |
| <<<'CODE_SAMPLE' | |
| public function testSomething(): void | |
| { | |
| } | |
| CODE_SAMPLE | |
| , | |
| <<<'CODE_SAMPLE' | |
| #[Test] | |
| public function something(): void | |
| { | |
| } | |
| CODE_SAMPLE | |
| ), | |
| ]); | |
| } | |
| /** | |
| * @return array<class-string<Node>> | |
| */ | |
| #[\Override] | |
| public function getNodeTypes(): array | |
| { | |
| return [ClassMethod::class]; | |
| } | |
| /** | |
| * @param ClassMethod $node | |
| */ | |
| #[\Override] | |
| public function refactor(Node $node): ?Node | |
| { | |
| if (!$this->testsNodeAnalyzer->isInTestClass($node)) { | |
| return null; | |
| } | |
| if (!str_starts_with($node->name->toString(), 'test_')) { | |
| return null; | |
| } | |
| $node->name->name = str_replace('test_', '', $node->name->name); | |
| $node->attrGroups[] = new AttributeGroup([$this->createTestAttribute()]); | |
| return $node; | |
| } | |
| private function createTestAttribute(): Attribute | |
| { | |
| $fullyQualified = new FullyQualified(Test::class); | |
| return new Attribute($fullyQualified); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment