Skip to content

Instantly share code, notes, and snippets.

@ivastly
Last active September 2, 2024 12:31
Show Gist options
  • Select an option

  • Save ivastly/f23c1dd793145272e07dda3f68ed128d to your computer and use it in GitHub Desktop.

Select an option

Save ivastly/f23c1dd793145272e07dda3f68ed128d to your computer and use it in GitHub Desktop.
Rector rule to replace `test_` prefix with [#Test] attribute
<?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