InvokableCommand.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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 bool $triggerDeprecations = false;
  41. private $code;
  42. public function __construct(
  43. private readonly Command $command,
  44. callable $code,
  45. ) {
  46. $this->code = $code;
  47. $this->signalableCommand = $code instanceof SignalableCommandInterface ? $code : null;
  48. $this->invokable = new \ReflectionFunction($this->getClosure($code));
  49. }
  50. /**
  51. * Invokes a callable with parameters generated from the input interface.
  52. */
  53. public function __invoke(InputInterface $input, OutputInterface $output): int
  54. {
  55. $statusCode = $this->invokable->invoke(...$this->getParameters($this->invokable, $input, $output));
  56. if (!\is_int($statusCode)) {
  57. if ($this->triggerDeprecations) {
  58. 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()));
  59. return 0;
  60. }
  61. 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)));
  62. }
  63. return $statusCode;
  64. }
  65. /**
  66. * Configures the input definition from an invokable-defined function.
  67. *
  68. * Processes the parameters of the reflection function to extract and
  69. * add arguments or options to the provided input definition.
  70. */
  71. public function configure(InputDefinition $definition): void
  72. {
  73. foreach ($this->invokable->getParameters() as $parameter) {
  74. if ($argument = Argument::tryFrom($parameter)) {
  75. $definition->addArgument($argument->toInputArgument());
  76. continue;
  77. }
  78. if ($option = Option::tryFrom($parameter)) {
  79. $definition->addOption($option->toInputOption());
  80. continue;
  81. }
  82. if ($input = MapInput::tryFrom($parameter)) {
  83. $inputArguments = array_map(fn (Argument $a) => $a->toInputArgument(), iterator_to_array($input->getArguments(), false));
  84. // make sure optional arguments are defined after required ones
  85. usort($inputArguments, fn (InputArgument $a, InputArgument $b) => (int) $b->isRequired() - (int) $a->isRequired());
  86. foreach ($inputArguments as $inputArgument) {
  87. $definition->addArgument($inputArgument);
  88. }
  89. foreach ($input->getOptions() as $option) {
  90. $definition->addOption($option->toInputOption());
  91. }
  92. }
  93. }
  94. }
  95. public function getCode(): callable
  96. {
  97. return $this->code;
  98. }
  99. private function getClosure(callable $code): \Closure
  100. {
  101. if (!$code instanceof \Closure) {
  102. return $code(...);
  103. }
  104. $this->triggerDeprecations = true;
  105. if (null !== (new \ReflectionFunction($code))->getClosureThis()) {
  106. return $code;
  107. }
  108. set_error_handler(static function () {});
  109. try {
  110. if ($c = \Closure::bind($code, $this->command)) {
  111. $code = $c;
  112. }
  113. } finally {
  114. restore_error_handler();
  115. }
  116. return $code;
  117. }
  118. private function getParameters(\ReflectionFunction $function, InputInterface $input, OutputInterface $output): array
  119. {
  120. $parameters = [];
  121. foreach ($function->getParameters() as $parameter) {
  122. if ($argument = Argument::tryFrom($parameter)) {
  123. $parameters[] = $argument->resolveValue($input);
  124. continue;
  125. }
  126. if ($option = Option::tryFrom($parameter)) {
  127. $parameters[] = $option->resolveValue($input);
  128. continue;
  129. }
  130. if ($in = MapInput::tryFrom($parameter)) {
  131. $parameters[] = $in->resolveValue($input);
  132. continue;
  133. }
  134. $type = $parameter->getType();
  135. if (!$type instanceof \ReflectionNamedType) {
  136. if ($this->triggerDeprecations) {
  137. 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()));
  138. continue;
  139. }
  140. throw new LogicException(\sprintf('The parameter "$%s" must have a named type. Untyped, Union or Intersection types are not supported.', $parameter->getName()));
  141. }
  142. $parameters[] = match ($type->getName()) {
  143. InputInterface::class => $input,
  144. OutputInterface::class => $output,
  145. Cursor::class => new Cursor($output),
  146. SymfonyStyle::class => new SymfonyStyle($input, $output),
  147. Application::class => $this->command->getApplication(),
  148. default => throw new RuntimeException(\sprintf('Unsupported type "%s" for parameter "$%s".', $type->getName(), $parameter->getName())),
  149. };
  150. }
  151. return $parameters ?: [$input, $output];
  152. }
  153. public function getSubscribedSignals(): array
  154. {
  155. return $this->signalableCommand?->getSubscribedSignals() ?? [];
  156. }
  157. public function handleSignal(int $signal, int|false $previousExitCode = 0): int|false
  158. {
  159. return $this->signalableCommand?->handleSignal($signal, $previousExitCode) ?? false;
  160. }
  161. public function isInteractive(): bool
  162. {
  163. if (null === $this->interactions) {
  164. $this->collectInteractions();
  165. }
  166. return [] !== $this->interactions;
  167. }
  168. public function interact(InputInterface $input, OutputInterface $output): void
  169. {
  170. if (null === $this->interactions) {
  171. $this->collectInteractions();
  172. }
  173. foreach ($this->interactions as $interaction) {
  174. $interaction->interact($input, $output, $this->getParameters(...));
  175. }
  176. }
  177. private function collectInteractions(): void
  178. {
  179. $invokableThis = $this->invokable->getClosureThis();
  180. $this->interactions = [];
  181. foreach ($this->invokable->getParameters() as $parameter) {
  182. if ($spec = Argument::tryFrom($parameter)) {
  183. if ($attribute = $spec->getInteractiveAttribute()) {
  184. $this->interactions[] = new Interaction($invokableThis, $attribute);
  185. }
  186. continue;
  187. }
  188. if ($spec = MapInput::tryFrom($parameter)) {
  189. $this->interactions = [...$this->interactions, ...$spec->getPropertyInteractions(), ...$spec->getMethodInteractions()];
  190. }
  191. }
  192. if (!$class = $this->invokable->getClosureCalledClass()) {
  193. return;
  194. }
  195. foreach ($class->getMethods() as $method) {
  196. if ($attribute = Interact::tryFrom($method)) {
  197. $this->interactions[] = new Interaction($invokableThis, $attribute);
  198. }
  199. }
  200. }
  201. }