Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tomschlick/b49df06dcc7f956baddad694383ac798 to your computer and use it in GitHub Desktop.
Save tomschlick/b49df06dcc7f956baddad694383ac798 to your computer and use it in GitHub Desktop.
Replace phpunit test_* method prefix with #[Test] attribute
<?php
declare(strict_types=1);
namespace App\Rector;
use PhpParser\Node;
use PhpParser\Node\Stmt\ClassMethod;
use PHPUnit\Framework\Attributes\Test;
use Rector\Core\Rector\AbstractRector;
use Rector\Php80\NodeAnalyzer\PhpAttributeAnalyzer;
use Rector\PhpAttribute\NodeFactory\PhpAttributeGroupFactory;
use Rector\PHPUnit\NodeAnalyzer\TestsNodeAnalyzer;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
class ReplacePrefixedFunctionTestWithAttributeRector extends AbstractRector
{
public function __construct(
private readonly TestsNodeAnalyzer $testsNodeAnalyzer,
private readonly PhpAttributeGroupFactory $phpAttributeGroupFactory,
private readonly PhpAttributeAnalyzer $phpAttributeAnalyzer
) {
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Replace prefixed function test with PHPUnit #[Test] annotation', [
new CodeSample(
<<<'CODE_SAMPLE'
class SomeTest extends \PHPUnit\Framework\TestCase
{
/**
* @test
*/
public function onePlusOneShouldBeTwo()
{
$this->assertSame(2, 1+1);
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
class SomeTest extends \PHPUnit\Framework\TestCase
{
public function testOnePlusOneShouldBeTwo()
{
$this->assertSame(2, 1+1);
}
}
CODE_SAMPLE
),
]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [ClassMethod::class];
}
/**
* @param ClassMethod $node
*/
public function refactor(Node $node): ?Node
{
if (! $this->testsNodeAnalyzer->isInTestClass($node)) {
return null;
}
if (! $this->isName($node->name, 'test*')) {
return null;
}
if (! $this->phpAttributeAnalyzer->hasPhpAttribute($node, Test::class)) {
$node->attrGroups = array_merge(
$node->attrGroups,
[$this->phpAttributeGroupFactory->createFromClass(Test::class)]
);
}
$node->name->name = lcfirst(
ltrim(preg_replace('/^test?/', '', $node->name->name), '_')
);
return $node;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment