ClosureCommand.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 Closure;
  13. use Hyperf\Crontab\Crontab;
  14. use Hyperf\Crontab\Schedule;
  15. use Hyperf\Stringable\Str;
  16. use Psr\Container\ContainerInterface;
  17. use function Hyperf\Tappable\tap;
  18. final class ClosureCommand extends Command
  19. {
  20. private ParameterParser $parameterParser;
  21. public function __construct(
  22. private ContainerInterface $container,
  23. string $signature,
  24. private Closure $closure
  25. ) {
  26. $this->signature = $signature;
  27. $this->parameterParser = $container->get(ParameterParser::class);
  28. parent::__construct();
  29. $options = $this->parameterParser->parseClosureOptions($closure);
  30. $definition = $this->getDefinition();
  31. foreach ($options as $option) {
  32. $name = $option->getName();
  33. $snakeName = Str::snake($option->getName(), '-');
  34. if (
  35. $definition->hasOption($name)
  36. || $definition->hasArgument($name)
  37. || $definition->hasOption($snakeName)
  38. || $definition->hasArgument($snakeName)
  39. ) {
  40. continue;
  41. }
  42. $definition->addOption($option);
  43. }
  44. }
  45. public function handle()
  46. {
  47. $inputs = array_merge($this->input->getArguments(), $this->input->getOptions());
  48. $parameters = $this->parameterParser->parseClosureParameters($this->closure, $inputs);
  49. $this->closure->call($this, ...$parameters);
  50. }
  51. public function describe(string $description): self
  52. {
  53. $this->setDescription($description);
  54. return $this;
  55. }
  56. /**
  57. * @param null|callable(Crontab $crontab):Crontab $callback
  58. */
  59. public function cron(string $rule, array $arguments = [], ?callable $callback = null): self
  60. {
  61. tap(
  62. Schedule::command($this->getName(), $arguments)
  63. ->setName($this->getName())
  64. ->setRule($rule)
  65. ->setMemo($this->getDescription()),
  66. $callback
  67. );
  68. return $this;
  69. }
  70. }