InvokableCommand.php 7.7 KB

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