forked from rectorphp/rector-phpunit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGetMockRector.php
104 lines (89 loc) · 2.75 KB
/
GetMockRector.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
<?php
declare(strict_types=1);
namespace Rector\PHPUnit\PHPUnit50\Rector\StaticCall;
use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Identifier;
use PHPStan\Reflection\ClassReflection;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\Reflection\ReflectionResolver;
use Rector\PHPUnit\NodeAnalyzer\TestsNodeAnalyzer;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @changelog https://github.com/sebastianbergmann/phpunit/blob/5.7.0/src/Framework/TestCase.php#L1623
* @changelog https://github.com/sebastianbergmann/phpunit/blob/6.0.0/src/Framework/TestCase.php#L1452
*
* @see \Rector\PHPUnit\Tests\PHPUnit50\Rector\StaticCall\GetMockRector\GetMockRectorTest
*/
final class GetMockRector extends AbstractRector
{
public function __construct(
private readonly TestsNodeAnalyzer $testsNodeAnalyzer,
private readonly ReflectionResolver $reflectionResolver,
) {
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Turns getMock*() methods to createMock()', [
new CodeSample(
<<<'CODE_SAMPLE'
use PHPUnit\Framework\TestCase;
final class SomeTest extends TestCase
{
public function test()
{
$classMock = $this->getMock("Class");
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
use PHPUnit\Framework\TestCase;
final class SomeTest extends TestCase
{
public function test()
{
$classMock = $this->createMock("Class");
}
}
CODE_SAMPLE
), ]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [MethodCall::class, StaticCall::class];
}
/**
* @param MethodCall|StaticCall $node
*/
public function refactor(Node $node): ?Node
{
if (! $this->testsNodeAnalyzer->isPHPUnitMethodCallNames(
$node,
['getMock', 'getMockWithoutInvokingTheOriginalConstructor']
)) {
return null;
}
if ($node instanceof MethodCall && $node->var instanceof MethodCall) {
return null;
}
$classReflection = $this->reflectionResolver->resolveClassReflectionSourceObject($node);
if ($classReflection instanceof ClassReflection && $classReflection->getName() !== 'PHPUnit\Framework\TestCase') {
return null;
}
if ($node->isFirstClassCallable()) {
return null;
}
// narrow args to one
if (count($node->args) > 1) {
$node->args = [$node->getArgs()[0]];
}
$node->name = new Identifier('createMock');
return $node;
}
}