Repository navigation
Expand file tree
/
Copy pathAssertTrueFalseToSpecificMethodRector.php
More file actions
256 lines (215 loc) · 8.59 KB
/
Copy pathAssertTrueFalseToSpecificMethodRector.php
File metadata and controls
256 lines (215 loc) · 8.59 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
<?php
declare(strict_types=1);
namespace Rector\PHPUnit\CodeQuality\Rector\MethodCall;
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\Empty_;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Identifier;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Type\StringType;
use Rector\PHPUnit\Enum\PHPUnitClassName;
use Rector\PHPUnit\NodeAnalyzer\TestsNodeAnalyzer;
use Rector\PHPUnit\ValueObject\FunctionNameWithAssertMethods;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \Rector\PHPUnit\Tests\CodeQuality\Rector\MethodCall\AssertTrueFalseToSpecificMethodRector\AssertTrueFalseToSpecificMethodRectorTest
*/
final class AssertTrueFalseToSpecificMethodRector extends AbstractRector
{
/**
* @var array<string,array<array-key,string>>
*/
private const array FUNCTION_NAME_WITH_ASSERT_METHOD_NAMES = [
'is_readable' => ['is_readable', 'assertIsReadable', 'assertNotIsReadable'],
'array_key_exists' => ['array_key_exists', 'assertArrayHasKey', 'assertArrayNotHasKey'],
'array_search' => ['array_search', 'assertContains', 'assertNotContains'],
'in_array' => ['in_array', 'assertContains', 'assertNotContains'],
'empty' => ['empty', 'assertEmpty', 'assertNotEmpty'],
'file_exists' => ['file_exists', 'assertFileExists', 'assertFileNotExists'],
'is_dir' => ['is_dir', 'assertDirectoryExists', 'assertDirectoryNotExists'],
'is_infinite' => ['is_infinite', 'assertInfinite', 'assertFinite'],
'is_null' => ['is_null', 'assertNull', 'assertNotNull'],
'is_writable' => ['is_writable', 'assertIsWritable', 'assertNotIsWritable'],
'is_nan' => ['is_nan', 'assertNan', ''],
'is_a' => ['is_a', 'assertInstanceOf', 'assertNotInstanceOf'],
'str_contains' => ['str_contains', 'assertStringContainsString', 'assertStringNotContainsString'],
];
/**
* Some assert methods were renamed in newer PHPUnit versions
* @var array<string, string>
*/
private const array RENAMED_ASSERT_METHOD_NAMES = [
'assertFileNotExists' => 'assertFileDoesNotExist',
'assertDirectoryNotExists' => 'assertDirectoryDoesNotExist',
];
public function __construct(
private readonly TestsNodeAnalyzer $testsNodeAnalyzer,
private readonly ReflectionProvider $reflectionProvider
) {
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Turns true/false comparisons to their method name alternatives in PHPUnit TestCase when possible',
[
new CodeSample(
'$this->assertTrue(is_readable($readmeFile), "message");',
'$this->assertIsReadable($readmeFile, "message");'
),
]
);
}
/**
* @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,
['assertTrue', 'assertFalse', 'assertNotTrue', 'assertNotFalse']
)) {
return null;
}
if ($node->isFirstClassCallable()) {
return null;
}
$arguments = $node->getArgs();
if ($arguments === []) {
return null;
}
$firstArgumentValue = $arguments[0]->value;
if (! $firstArgumentValue instanceof FuncCall && ! $firstArgumentValue instanceof Empty_) {
return null;
}
$firstArgumentName = $this->resolveFirstArgument($firstArgumentValue);
if ($firstArgumentName === null || ! array_key_exists(
$firstArgumentName,
self::FUNCTION_NAME_WITH_ASSERT_METHOD_NAMES
)) {
return null;
}
if ($firstArgumentName === 'is_a') {
/** @var FuncCall $firstArgumentValue */
$args = $firstArgumentValue->getArgs();
/** @var array<Arg> $args */
if ($args === []) {
return null;
}
$firstArgumentType = $this->nodeTypeResolver->getType($args[0]->value);
if ($firstArgumentType instanceof StringType) {
return null;
}
}
[$functionName, $assetMethodName, $notAssertMethodName] = self::FUNCTION_NAME_WITH_ASSERT_METHOD_NAMES[$firstArgumentName];
$functionNameWithAssertMethods = new FunctionNameWithAssertMethods($assetMethodName, $notAssertMethodName);
$this->renameMethod($node, $functionNameWithAssertMethods);
$this->moveFunctionArgumentsUp($node);
return $node;
}
private function resolveFirstArgument(FuncCall|Empty_ $firstArgumentValue): ?string
{
return $firstArgumentValue instanceof Empty_
? 'empty'
: $this->getName($firstArgumentValue);
}
private function renameMethod(
MethodCall|StaticCall $node,
FunctionNameWithAssertMethods $functionNameWithAssertMethods
): void {
/** @var Identifier $identifierNode */
$identifierNode = $node->name;
$oldMethodName = $identifierNode->toString();
if (in_array($oldMethodName, ['assertTrue', 'assertNotFalse'], true)) {
$node->name = new Identifier(
$this->resolveExistingAssertMethodName($functionNameWithAssertMethods->getAssetMethodName())
);
}
if ($functionNameWithAssertMethods->getNotAssertMethodName() === '') {
return;
}
if (! in_array($oldMethodName, ['assertFalse', 'assertNotTrue'], true)) {
return;
}
$node->name = new Identifier(
$this->resolveExistingAssertMethodName($functionNameWithAssertMethods->getNotAssertMethodName())
);
}
/**
* Verify the assert method exists on the PHPUnit Assert class,
* as some methods were renamed in newer PHPUnit versions
*/
private function resolveExistingAssertMethodName(string $methodName): string
{
if (! $this->reflectionProvider->hasClass(PHPUnitClassName::ASSERT)) {
return $methodName;
}
$assertClassReflection = $this->reflectionProvider->getClass(PHPUnitClassName::ASSERT);
if ($assertClassReflection->hasNativeMethod($methodName)) {
return $methodName;
}
return self::RENAMED_ASSERT_METHOD_NAMES[$methodName] ?? $methodName;
}
/**
* Before:
* - $this->assertTrue(array_key_exists('...', ['...']), 'second argument');
*
* After:
* - $this->assertArrayHasKey('...', ['...'], 'second argument');
*/
private function moveFunctionArgumentsUp(MethodCall|StaticCall $node): void
{
$funcCallOrEmptyNode = $node->getArgs()[0]
->value;
if ($funcCallOrEmptyNode instanceof FuncCall) {
$funcCallOrEmptyNodeName = $this->getName($funcCallOrEmptyNode);
if ($funcCallOrEmptyNodeName === null) {
return;
}
$funcCallOrEmptyNodeArgs = $funcCallOrEmptyNode->getArgs();
$oldArguments = $node->getArgs();
unset($oldArguments[0]);
$node->args = $this->buildNewArguments(
$funcCallOrEmptyNodeName,
$funcCallOrEmptyNodeArgs,
$oldArguments
);
}
if ($funcCallOrEmptyNode instanceof Empty_) {
$node->args[0] = new Arg($funcCallOrEmptyNode->expr);
}
}
/**
* @param Arg[] $funcCallOrEmptyNodeArgs
* @param Arg[] $oldArguments
* @return mixed[]
*/
private function buildNewArguments(
string $funcCallOrEmptyNodeName,
array $funcCallOrEmptyNodeArgs,
array $oldArguments
): array {
if (in_array($funcCallOrEmptyNodeName, ['in_array', 'array_search'], true)
&& count($funcCallOrEmptyNodeArgs) === 3) {
unset($funcCallOrEmptyNodeArgs[2]);
return [...$funcCallOrEmptyNodeArgs, ...$oldArguments];
}
if (in_array($funcCallOrEmptyNodeName, ['is_a', 'str_contains'], true)) {
// flip arguments
$newArgs = [$funcCallOrEmptyNodeArgs[1], $funcCallOrEmptyNodeArgs[0]];
return [...$newArgs, ...$oldArguments];
}
return [...$funcCallOrEmptyNodeArgs, ...$oldArguments];
}
}