forked from rectorphp/rector-symfony
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathControllerMethodInjectionToConstructorRector.php
More file actions
290 lines (246 loc) · 9.31 KB
/
ControllerMethodInjectionToConstructorRector.php
File metadata and controls
290 lines (246 loc) · 9.31 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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
<?php
declare(strict_types=1);
namespace Rector\Symfony\CodeQuality\Rector\Class_;
use Exception;
use PhpParser\Node;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PHPStan\Type\ObjectType;
use Rector\Contract\Rector\ConfigurableRectorInterface;
use Rector\NodeManipulator\ClassDependencyManipulator;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\PostRector\ValueObject\PropertyMetadata;
use Rector\Rector\AbstractRector;
use Rector\StaticTypeMapper\StaticTypeMapper;
use Rector\Symfony\Bridge\NodeAnalyzer\ControllerMethodAnalyzer;
use Rector\Symfony\CodeQuality\NodeAnalyzer\ParamConverterClassesResolver;
use Rector\Symfony\Enum\FosClass;
use Rector\Symfony\Enum\SymfonyClass;
use Rector\Symfony\TypeAnalyzer\ControllerAnalyzer;
use Rector\ValueObject\MethodName;
use Rector\VendorLocker\ParentClassMethodTypeOverrideGuard;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use Throwable;
/**
* @see \Rector\Symfony\Tests\CodeQuality\Rector\Class_\ControllerMethodInjectionToConstructorRector\ControllerMethodInjectionToConstructorRectorTest
*/
final class ControllerMethodInjectionToConstructorRector extends AbstractRector implements ConfigurableRectorInterface
{
/**
* @var string[]
*/
private const COMMON_ENTITY_CONTAINS_SUBNAMESPACES = ["\\Entity", "\\Document", "\\Model"];
/**
* @var string[]
*/
private array $skipAllowedKnownObjects = [];
public function __construct(
private readonly ControllerAnalyzer $controllerAnalyzer,
private readonly ControllerMethodAnalyzer $controllerMethodAnalyzer,
private readonly ClassDependencyManipulator $classDependencyManipulator,
private readonly StaticTypeMapper $staticTypeMapper,
private readonly ParamConverterClassesResolver $paramConverterClassesResolver,
private readonly ParentClassMethodTypeOverrideGuard $parentClassMethodTypeOverrideGuard
) {
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Change Symfony controller method injection to direct constructor dependency, to separate params and services clearly',
[
new CodeSample(
<<<'CODE_SAMPLE'
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
final class SomeController extends AbstractController
{
#[Route('/some-path', name: 'some_name')]
public function someAction(
Request $request,
SomeService $someService
) {
$data = $someService->getData();
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
final class SomeController extends AbstractController
{
public function __construct(
private readonly SomeService $someService
) {
}
#[Route('/some-path', name: 'some_name')]
public function someAction(
Request $request
) {
$data = $this->someService->getData();
}
}
CODE_SAMPLE
),
]
);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Class_::class];
}
/**
* @param Class_ $node
*/
public function refactor(Node $node): ?Node
{
if (! $this->controllerAnalyzer->isController($node)) {
return null;
}
if ($node->isAbstract()) {
return null;
}
$propertyMetadatas = [];
$constructParamVariables = [];
$constructClassMethod = $node->getMethod(MethodName::CONSTRUCT);
if ($constructClassMethod instanceof ClassMethod) {
foreach ($constructClassMethod->params as $param) {
if ($param->type instanceof FullyQualified) {
$constructParamVariables[$param->type->toString()] = $this->getName($param->var);
}
}
}
foreach ($node->getMethods() as $classMethod) {
if ($this->shouldSkipClassMethod($classMethod)) {
continue;
}
$entityClasses = $this->paramConverterClassesResolver->resolveEntityClasses($classMethod);
foreach ($classMethod->getParams() as $key => $param) {
// skip scalar and empty values, as not services
if ($param->type === null || ! $param->type instanceof FullyQualified) {
continue;
}
// most likely mapped by attribute or autowired with specific type
if ($param->attrGroups !== []) {
continue;
}
// skip allowed known objects
if ($this->isNames(
$param->type,
[
SymfonyClass::USER_INTERFACE,
SymfonyClass::REQUEST,
FosClass::PARAM_FETCHER,
SymfonyClass::UUID,
Throwable::class,
Exception::class,
...$entityClasses,
...$this->skipAllowedKnownObjects,
]
)) {
continue;
}
if ($this->isObjectType($param->type, new ObjectType(SymfonyClass::USER_INTERFACE))) {
continue;
}
foreach (self::COMMON_ENTITY_CONTAINS_SUBNAMESPACES as $commonEntityContainsNamespace) {
if (str_contains($this->getName($param->type), $commonEntityContainsNamespace)) {
continue 2;
}
}
$paramType = $this->staticTypeMapper->mapPhpParserNodePHPStanType($param->type);
if (! $paramType instanceof ObjectType) {
continue;
}
if ($paramType->isEnum()->yes()) {
continue;
}
if (
$constructParamVariables !== []
&& in_array($this->getName($param->var), $constructParamVariables, true)
&&
! in_array($this->getName($param->type), array_keys($constructParamVariables), true)
) {
continue;
}
unset($classMethod->params[$key]);
$propertyMetadatas[] = new PropertyMetadata($this->getName($param->var), $paramType);
}
}
// nothing to move
if ($propertyMetadatas === []) {
return null;
}
$paramNamesToReplace = [];
foreach ($propertyMetadatas as $propertyMetadata) {
$paramNamesToReplace[] = $propertyMetadata->getName();
}
// 1. update constructor
foreach ($propertyMetadatas as $propertyMetadata) {
$this->classDependencyManipulator->addConstructorDependency($node, $propertyMetadata);
}
foreach ($node->getMethods() as $classMethod) {
if ($this->shouldSkipClassMethod($classMethod)) {
continue;
}
$this->replaceParamUseWithPropertyFetch($classMethod, $paramNamesToReplace);
}
return $node;
}
private function shouldSkipClassMethod(ClassMethod $classMethod): bool
{
if ($classMethod->isMagic() && ! $this->isName($classMethod->name, MethodName::INVOKE)) {
return true;
}
if (! $this->controllerMethodAnalyzer->isAction($classMethod)) {
return true;
}
return $this->parentClassMethodTypeOverrideGuard->hasParentClassMethod($classMethod);
}
/**
* @param string[] $paramNamesToReplace
*/
private function replaceParamUseWithPropertyFetch(ClassMethod $classMethod, array $paramNamesToReplace): void
{
if ($classMethod->stmts === null) {
return;
}
$this->traverseNodesWithCallable($classMethod->stmts, function (Node $node) use (
$paramNamesToReplace
): Closure|null|PropertyFetch {
if ($node instanceof Closure) {
foreach ($node->uses as $key => $closureUse) {
if ($this->isNames($closureUse->var, $paramNamesToReplace)) {
unset($node->uses[$key]);
}
}
return $node;
}
if (! $node instanceof Variable) {
return null;
}
if (! $this->isNames($node, $paramNamesToReplace)) {
return null;
}
if ($node->getAttribute(AttributeKey::IS_BEING_ASSIGNED) === true) {
return null;
}
$propertyName = $this->getName($node);
return new PropertyFetch(new Variable('this'), $propertyName);
});
}
public function configure(array $configuration): void
{
$this->skipAllowedKnownObjects = $configuration;
}
}