-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathInvokableCommandInputAttributeRector.php
More file actions
281 lines (231 loc) · 9.56 KB
/
InvokableCommandInputAttributeRector.php
File metadata and controls
281 lines (231 loc) · 9.56 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
<?php
declare(strict_types=1);
namespace Rector\Symfony\Symfony73\Rector\Class_;
use PhpParser\Modifiers;
use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Expression;
use Rector\Doctrine\NodeAnalyzer\AttributeFinder;
use Rector\Rector\AbstractRector;
use Rector\Symfony\Enum\CommandMethodName;
use Rector\Symfony\Enum\SymfonyAttribute;
use Rector\Symfony\Enum\SymfonyClass;
use Rector\Symfony\Symfony73\NodeAnalyzer\CommandArgumentsResolver;
use Rector\Symfony\Symfony73\NodeAnalyzer\CommandOptionsResolver;
use Rector\Symfony\Symfony73\NodeFactory\CommandInvokeParamsFactory;
use Rector\Symfony\Symfony73\NodeTransformer\CommandUnusedInputOutputRemover;
use Rector\Symfony\Symfony73\NodeTransformer\ConsoleOptionAndArgumentMethodCallVariableReplacer;
use Rector\Symfony\Symfony73\NodeTransformer\OutputInputSymfonyStyleReplacer;
use Rector\ValueObject\MethodName;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see https://symfony.com/blog/new-in-symfony-7-3-invokable-commands-and-input-attributes
*
* @see https://github.com/symfony/symfony-docs/issues/20553
* @see https://github.com/symfony/symfony/pull/59340
*
* @see \Rector\Symfony\Tests\Symfony73\Rector\Class_\InvokableCommandInputAttributeRector\InvokableCommandInputAttributeRectorTest
*/
final class InvokableCommandInputAttributeRector extends AbstractRector
{
private const MIGRATED_CONFIGURE_CALLS = ['addArgument', 'addOption'];
public function __construct(
private readonly AttributeFinder $attributeFinder,
private readonly CommandArgumentsResolver $commandArgumentsResolver,
private readonly CommandOptionsResolver $commandOptionsResolver,
private readonly CommandInvokeParamsFactory $commandInvokeParamsFactory,
private readonly ConsoleOptionAndArgumentMethodCallVariableReplacer $consoleOptionAndArgumentMethodCallVariableReplacer,
private readonly OutputInputSymfonyStyleReplacer $outputInputSymfonyStyleReplacer,
private readonly CommandUnusedInputOutputRemover $commandUnusedInputOutputRemover
) {
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Change Symfony Command with execute() + configure() to __invoke() with attributes', [
new CodeSample(
<<<'CODE_SAMPLE'
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
#[AsCommand(name: 'some_name')]
final class SomeCommand extends Command
{
public function configure()
{
$this->addArgument('argument', InputArgument::REQUIRED, 'Argument description');
$this->addOption('option', 'o', InputOption::VALUE_NONE, 'Option description');
}
public function execute(InputInterface $input, OutputInterface $output)
{
$someArgument = $input->getArgument('argument');
$someOption = $input->getOption('option');
// ...
return Command::SUCCESS;
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Argument;
use Symfony\Component\Console\Option;
#[AsCommand(name: 'some_name')]
final class SomeCommand
{
public function __invoke(
#[Argument(name: 'argument', description: 'Argument description')]
string $argument,
#[Option(name: 'option', shortcut: 'o', mode: Option::VALUE_NONE, description: 'Option description')]
bool $option = false,
) {
$someArgument = $argument;
$someOption = $option;
// ...
return Command::SUCCESS;
}
}
CODE_SAMPLE
),
]);
}
public function getNodeTypes(): array
{
return [Class_::class];
}
/**
* @param Class_ $node
*/
public function refactor(Node $node): ?Class_
{
if (! $node->extends instanceof Name) {
return null;
}
// handle only direct child classes, to keep safe
if (! $this->isName($node->extends, SymfonyClass::COMMAND)) {
return null;
}
if ($this->isComplexCommand($node)) {
return null;
}
// as command attribute is required, its handled by previous symfony versions
if (! $this->attributeFinder->hasAttributeByClasses($node, [SymfonyAttribute::AS_COMMAND])) {
return null;
}
foreach ($node->stmts as $key => $classStmt) {
if (! $classStmt instanceof ClassMethod) {
continue;
}
if (! $this->isName($classStmt, CommandMethodName::EXECUTE)) {
continue;
}
$executeClassMethod = $classStmt;
// 1. rename execute to __invoke
$invokeClassMethod = new ClassMethod(MethodName::INVOKE);
$invokeClassMethod->flags |= Modifiers::PUBLIC;
$invokeClassMethod->returnType = new Identifier('int');
$invokeClassMethod->stmts = $classStmt->stmts;
$invokeParams = $this->createInvokeParams($node);
$executeClassMethodParams = array_merge($invokeParams, [$executeClassMethod->params[1]]);
// Ensure that optional parameters are listed last in the argument list
$invokeClassMethod->params = array_merge(
array_filter($executeClassMethodParams, fn(Param $param) => is_null($param->default)),
array_filter($executeClassMethodParams, fn(Param $param) => !is_null($param->default)),
);
// 6. remove parent class
$node->extends = null;
// 7. replace input->getArgument() and input->getOption() calls with direct variable access
$this->consoleOptionAndArgumentMethodCallVariableReplacer->replace($invokeClassMethod);
$this->outputInputSymfonyStyleReplacer->replace($invokeClassMethod);
$this->commandUnusedInputOutputRemover->remove($invokeClassMethod);
$node->stmts[$key] = $invokeClassMethod;
return $node;
}
return null;
}
/**
* Skip commands with interact() or initialize() methods as modify the argument/option values
*/
private function isComplexCommand(Class_ $class): bool
{
if ($class->getMethod(CommandMethodName::INTERACT) instanceof ClassMethod) {
return true;
}
return $class->getMethod(CommandMethodName::INITIALIZE) instanceof ClassMethod;
}
private function removeConfigureClassMethodIfNotUseful(Class_ $class): void
{
foreach ($class->stmts as $key => $stmt) {
if (! $stmt instanceof ClassMethod) {
continue;
}
if (! $this->isName($stmt->name, CommandMethodName::CONFIGURE)) {
continue;
}
foreach ((array) $stmt->stmts as $innerKey => $innerStmt) {
if (! $innerStmt instanceof Expression) {
continue;
}
$expr = $innerStmt->expr;
if (! $expr instanceof MethodCall) {
continue;
}
if ($this->isFluentArgumentOptionChain($expr)) {
unset($stmt->stmts[$innerKey]);
continue;
}
if ($this->isName($expr->var, 'this')
&& $this->isNames($expr->name, self::MIGRATED_CONFIGURE_CALLS)) {
unset($stmt->stmts[$innerKey]);
}
}
// 2. if configure() has became empty → remove the method itself
if ($stmt->stmts === [] || $stmt->stmts === null) {
unset($class->stmts[$key]);
}
return;
}
}
private function isFluentArgumentOptionChain(MethodCall $methodCall): bool
{
$current = $methodCall;
while ($current instanceof MethodCall) {
// every link must be addArgument() or addOption()
if (! $this->isNames($current->name, self::MIGRATED_CONFIGURE_CALLS)) {
return false;
}
// go one step left
$current = $current->var;
}
// the left-most var must be $this
return $current instanceof Variable && $this->isName($current, 'this');
}
/**
* @return Param[]
*/
private function createInvokeParams(Class_ $class): array
{
// 1. fetch configure method to get arguments and options metadata
$configureClassMethod = $class->getMethod(CommandMethodName::CONFIGURE);
if ($configureClassMethod instanceof ClassMethod) {
// 2. create arguments and options parameters
$commandArguments = $this->commandArgumentsResolver->resolve($configureClassMethod);
$commandOptions = $this->commandOptionsResolver->resolve($configureClassMethod);
// 3. remove configure() method
$this->removeConfigureClassMethodIfNotUseful($class);
// 4. decorate __invoke method with attributes
return $this->commandInvokeParamsFactory->createParams($commandArguments, $commandOptions);
}
return [];
}
}