AsCommand.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Command;
  12. use Hyperf\Command\Concerns\InteractsWithIO;
  13. use Hyperf\Stringable\Str;
  14. use Psr\Container\ContainerInterface;
  15. use function Hyperf\Support\class_uses_recursive;
  16. final class AsCommand extends Command
  17. {
  18. private ParameterParser $parameterParser;
  19. public function __construct(
  20. private ContainerInterface $container,
  21. string $signature,
  22. private string $class,
  23. private string $method,
  24. ) {
  25. $this->signature = $signature;
  26. $this->parameterParser = $container->get(ParameterParser::class);
  27. parent::__construct();
  28. $options = $this->parameterParser->parseMethodOptions($class, $method);
  29. $definition = $this->getDefinition();
  30. foreach ($options as $option) {
  31. $name = $option->getName();
  32. $snakeName = Str::snake($option->getName(), '-');
  33. if (
  34. $definition->hasOption($name)
  35. || $definition->hasArgument($name)
  36. || $definition->hasOption($snakeName)
  37. || $definition->hasArgument($snakeName)
  38. ) {
  39. continue;
  40. }
  41. $definition->addOption($option);
  42. }
  43. }
  44. public function handle()
  45. {
  46. $inputs = array_merge($this->input->getArguments(), $this->input->getOptions());
  47. $parameters = $this->parameterParser->parseMethodParameters($this->class, $this->method, $inputs);
  48. $instance = $this->container->get($this->class);
  49. if (in_array(InteractsWithIO::class, class_uses_recursive($this->class))) {
  50. $instance->setInput($this->input);
  51. $instance->setOutput($this->output);
  52. }
  53. (fn ($method) => $this->{$method}(...$parameters))->call($instance, $this->method);
  54. }
  55. }