This repository has been archived by the owner on Aug 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
SetUpTearDownToBeforeEachAfterEachRector.php
106 lines (90 loc) · 2.69 KB
/
SetUpTearDownToBeforeEachAfterEachRector.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
98
99
100
101
102
103
104
105
106
<?php
declare(strict_types=1);
namespace Rector\Pest\Rector\ClassMethod;
use PhpParser\Node;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Expression;
use Rector\Core\Rector\AbstractRector;
use Rector\PHPUnit\NodeAnalyzer\TestsNodeAnalyzer;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \Rector\Pest\Tests\Rector\ClassMethod\SetUpTearDownToBeforeEachAfterEachRector\SetUpTearDownToBeforeEachAfterEachRectorTest
*/
final class SetUpTearDownToBeforeEachAfterEachRector extends AbstractRector
{
/**
* @var array<string, string>
*/
private const METHOD_NAMES_TO_FUNCTION_NAMES = [
'setUp' => 'beforeEach',
'tearDown' => 'afterEach',
];
public function __construct(
private readonly TestsNodeAnalyzer $testsNodeAnalyzer
) {
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Change setUp() class method to beforeEach() func call',
[new CodeSample(
<<<'CODE_SAMPLE'
use PHPUnit\Framework\TestCase;
class SetUpTest extends TestCase
{
protected function setUp(): void
{
$value = 100;
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
beforeEach(function () {
$value = 100;
});
CODE_SAMPLE
)]
);
}
public function getNodeTypes(): array
{
return [Class_::class];
}
/**
* @param Class_ $node
* @return Stmt[]|null
*/
public function refactor(Node $node): ?array
{
if (! $this->testsNodeAnalyzer->isInTestClass($node)) {
return null;
}
$funcCallExpressions = [];
foreach (self::METHOD_NAMES_TO_FUNCTION_NAMES as $methodName => $functionName) {
$desiredClassMethod = $node->getMethod($methodName);
if (! $desiredClassMethod instanceof ClassMethod) {
continue;
}
$this->removeNode($desiredClassMethod);
$funcCallExpressions[] = $this->createFuncCallExpression($desiredClassMethod, $functionName);
}
if ($funcCallExpressions === []) {
return null;
}
return [...$funcCallExpressions, ...[$node]];
}
private function createFuncCallExpression(ClassMethod $classMethod, string $functionName): Expression
{
$funcCall = $this->nodeFactory->createFuncCall($functionName, [
new Closure([
'stmts' => $classMethod->stmts,
]),
]);
return new Expression($funcCall);
}
}