Debian Codegraph @

vendor/symfony/console/Command/InvokableCommand.php

raw
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Console\Command;
13
14 use Symfony\Component\Console\Application;
15 use Symfony\Component\Console\Attribute\Argument;
16 use Symfony\Component\Console\Attribute\Interact;
17 use Symfony\Component\Console\Attribute\MapInput;
18 use Symfony\Component\Console\Attribute\Option;
19 use Symfony\Component\Console\Cursor;
20 use Symfony\Component\Console\Exception\LogicException;
21 use Symfony\Component\Console\Exception\RuntimeException;
22 use Symfony\Component\Console\Input\InputArgument;
23 use Symfony\Component\Console\Input\InputDefinition;
24 use Symfony\Component\Console\Input\InputInterface;
25 use Symfony\Component\Console\Interaction\Interaction;
26 use Symfony\Component\Console\Output\OutputInterface;
27 use Symfony\Component\Console\Style\SymfonyStyle;
28
29 /**
30 * Represents an invokable command.
31 *
32 * @author Yonel Ceruto <[email protected]>
33 *
34 * @internal
35 */
36 class InvokableCommand implements SignalableCommandInterface
37 {
38 private readonly ?SignalableCommandInterface $signalableCommand;
39 private readonly \ReflectionFunction $invokable;
40 /**
41 * @var list<Interaction>|null
42 */
43 private ?array $interactions = null;
44 private bool $triggerDeprecations = false;
45 private $code;
46
47 public function __construct(
48 private readonly Command $command,
49 callable $code,
50 ) {
51 $this->code = $code;
52 $this->signalableCommand = $code instanceof SignalableCommandInterface ? $code : null;
53 $this->invokable = new \ReflectionFunction($this->getClosure($code));
54 }
55
56 /**
57 * Invokes a callable with parameters generated from the input interface.
58 */
59 public function __invoke(InputInterface $input, OutputInterface $output): int
60 {
61 $statusCode = $this->invokable->invoke(...$this->getParameters($this->invokable, $input, $output));
62
63 if (!\is_int($statusCode)) {
64 if ($this->triggerDeprecations) {
65 trigger_deprecation('symfony/console', '7.3', \sprintf('Returning a non-integer value from the command "%s" is deprecated and will throw an exception in Symfony 8.0.', $this->command->getName()));
66
67 return 0;
68 }
69
70 throw new \TypeError(\sprintf('The command "%s" must return an integer value in the "%s" method, but "%s" was returned.', $this->command->getName(), $this->invokable->getName(), get_debug_type($statusCode)));
71 }
72
73 return $statusCode;
74 }
75
76 /**
77 * Configures the input definition from an invokable-defined function.
78 *
79 * Processes the parameters of the reflection function to extract and
80 * add arguments or options to the provided input definition.
81 */
82 public function configure(InputDefinition $definition): void
83 {
84 foreach ($this->invokable->getParameters() as $parameter) {
85 if ($argument = Argument::tryFrom($parameter)) {
86 $definition->addArgument($argument->toInputArgument());
87 continue;
88 }
89
90 if ($option = Option::tryFrom($parameter)) {
91 $definition->addOption($option->toInputOption());
92 continue;
93 }
94
95 if ($input = MapInput::tryFrom($parameter)) {
96 $inputArguments = array_map(static fn (Argument $a) => $a->toInputArgument(), iterator_to_array($input->getArguments(), false));
97
98 // make sure optional arguments are defined after required ones
99 usort($inputArguments, static fn (InputArgument $a, InputArgument $b) => (int) $b->isRequired() - (int) $a->isRequired());
100
101 foreach ($inputArguments as $inputArgument) {
102 $definition->addArgument($inputArgument);
103 }
104
105 foreach ($input->getOptions() as $option) {
106 $definition->addOption($option->toInputOption());
107 }
108 }
109 }
110 }
111
112 public function getCode(): callable
113 {
114 return $this->code;
115 }
116
117 private function getClosure(callable $code): \Closure
118 {
119 if (!$code instanceof \Closure) {
120 return $code(...);
121 }
122
123 $this->triggerDeprecations = true;
124
125 if (null !== (new \ReflectionFunction($code))->getClosureThis()) {
126 return $code;
127 }
128
129 set_error_handler(static function () {});
130 try {
131 if ($c = \Closure::bind($code, $this->command)) {
132 $code = $c;
133 }
134 } finally {
135 restore_error_handler();
136 }
137
138 return $code;
139 }
140
141 private function getParameters(\ReflectionFunction $function, InputInterface $input, OutputInterface $output): array
142 {
143 $parameters = [];
144 foreach ($function->getParameters() as $parameter) {
145 if ($argument = Argument::tryFrom($parameter)) {
146 $parameters[] = $argument->resolveValue($input);
147
148 continue;
149 }
150
151 if ($option = Option::tryFrom($parameter)) {
152 $parameters[] = $option->resolveValue($input);
153
154 continue;
155 }
156
157 if ($in = MapInput::tryFrom($parameter)) {
158 $parameters[] = $in->resolveValue($input);
159
160 continue;
161 }
162
163 $type = $parameter->getType();
164
165 if (!$type instanceof \ReflectionNamedType) {
166 if ($this->triggerDeprecations) {
167 trigger_deprecation('symfony/console', '7.3', \sprintf('Omitting the type declaration for the parameter "$%s" is deprecated and will throw an exception in Symfony 8.0.', $parameter->getName()));
168
169 continue;
170 }
171
172 throw new LogicException(\sprintf('The parameter "$%s" must have a named type. Untyped, Union or Intersection types are not supported.', $parameter->getName()));
173 }
174
175 $parameters[] = match ($type->getName()) {
176 InputInterface::class => $input,
177 OutputInterface::class => $output,
178 Cursor::class => new Cursor($output),
179 SymfonyStyle::class => new SymfonyStyle($input, $output),
180 Application::class => $this->command->getApplication(),
181 default => throw new RuntimeException(\sprintf('Unsupported type "%s" for parameter "$%s".', $type->getName(), $parameter->getName())),
182 };
183 }
184
185 return $parameters ?: [$input, $output];
186 }
187
188 public function getSubscribedSignals(): array
189 {
190 return $this->signalableCommand?->getSubscribedSignals() ?? [];
191 }
192
193 public function handleSignal(int $signal, int|false $previousExitCode = 0): int|false
194 {
195 return $this->signalableCommand?->handleSignal($signal, $previousExitCode) ?? false;
196 }
197
198 public function isInteractive(): bool
199 {
200 if (null === $this->interactions) {
201 $this->collectInteractions();
202 }
203
204 return [] !== $this->interactions;
205 }
206
207 public function interact(InputInterface $input, OutputInterface $output): void
208 {
209 if (null === $this->interactions) {
210 $this->collectInteractions();
211 }
212
213 foreach ($this->interactions as $interaction) {
214 $interaction->interact($input, $output, $this->getParameters(...));
215 }
216 }
217
218 private function collectInteractions(): void
219 {
220 $invokableThis = $this->invokable->getClosureThis();
221
222 $this->interactions = [];
223 foreach ($this->invokable->getParameters() as $parameter) {
224 if ($spec = Argument::tryFrom($parameter)) {
225 if ($attribute = $spec->getInteractiveAttribute()) {
226 $this->interactions[] = new Interaction($invokableThis, $attribute);
227 }
228
229 continue;
230 }
231
232 if ($spec = MapInput::tryFrom($parameter)) {
233 $this->interactions = [...$this->interactions, ...$spec->getPropertyInteractions(), ...$spec->getMethodInteractions()];
234 }
235 }
236
237 if (!$class = $this->invokable->getClosureCalledClass()) {
238 return;
239 }
240
241 foreach ($class->getMethods() as $method) {
242 if ($attribute = Interact::tryFrom($method)) {
243 $this->interactions[] = new Interaction($invokableThis, $attribute);
244 }
245 }
246 }
247 }