-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathRenameTestClassMethodRector.php
97 lines (81 loc) · 2.4 KB
/
RenameTestClassMethodRector.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
declare(strict_types=1);
namespace Rector\PhpSpecToPHPUnit\Rector\ClassMethod;
use PhpParser\Node;
use PhpParser\Node\Identifier;
use PhpParser\Node\Stmt\ClassMethod;
use Rector\PhpSpecToPHPUnit\Enum\PhpSpecMethodName;
use Rector\PhpSpecToPHPUnit\Naming\PhpSpecRenaming;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \Rector\PhpSpecToPHPUnit\Tests\Rector\ClassMethod\RenameTestMethodRector\RenameTestMethodRectorTest
*/
final class RenameTestClassMethodRector extends AbstractRector
{
public function __construct(
private readonly PhpSpecRenaming $phpSpecRenaming,
) {
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [ClassMethod::class];
}
/**
* @param ClassMethod $node
*/
public function refactor(Node $node): ?Node
{
if (! $node->isPublic()) {
return null;
}
// special case, @see https://johannespichler.com/writing-custom-phpspec-matchers/
if ($this->isNames($node, PhpSpecMethodName::RESERVED_CLASS_METHOD_NAMES)) {
return null;
}
/** @var string $methodName */
$methodName = $this->getName($node);
// is already renamed
if (str_starts_with($methodName, 'test')) {
return null;
}
// change name to phpunit test case format
$phpUnitTestMethodName = $this->phpSpecRenaming->resolvePHPUnitTestMethodName($methodName);
if (! is_string($phpUnitTestMethodName)) {
return null;
}
$node->name = new Identifier($phpUnitTestMethodName);
$node->returnType = new Identifier('void');
return $node;
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Rename test method from underscore PhpSpec syntax to test* PHPUnit syntax', [
new CodeSample(
<<<'CODE_SAMPLE'
use PhpSpec\ObjectBehavior;
class RenameMethodTest extends ObjectBehavior
{
public function is_shoud_be_valid()
{
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
use PhpSpec\ObjectBehavior;
class RenameMethodTest extends ObjectBehavior
{
public function testShouldBeValid(): void
{
}
}
CODE_SAMPLE
),
]);
}
}