Repository navigation
Expand file tree
/
Copy pathClosureCommand.php
More file actions
100 lines (81 loc) · 2.55 KB
/
Copy pathClosureCommand.php
File metadata and controls
100 lines (81 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Command;
use Closure;
use Hyperf\Crontab\Crontab;
use Hyperf\Crontab\Schedule;
use Hyperf\Stringable\Str;
use Psr\Container\ContainerInterface;
use ReflectionFunction;
use function Hyperf\Tappable\tap;
final class ClosureCommand extends Command
{
private ParameterParser $parameterParser;
public function __construct(
private ContainerInterface $container,
string $signature,
private Closure $closure
) {
$this->signature = $signature;
$this->parameterParser = $container->get(ParameterParser::class);
parent::__construct();
$options = $this->parameterParser->parseClosureOptions($closure);
$definition = $this->getDefinition();
foreach ($options as $option) {
$name = $option->getName();
$snakeName = Str::snake($option->getName(), '-');
if (
$definition->hasOption($name)
|| $definition->hasArgument($name)
|| $definition->hasOption($snakeName)
|| $definition->hasArgument($snakeName)
) {
continue;
}
$definition->addOption($option);
}
}
public function handle()
{
$inputs = array_merge($this->input->getArguments(), $this->input->getOptions());
$parameters = $this->parameterParser->parseClosureParameters($this->closure, $inputs);
$ref = new ReflectionFunction($this->closure);
if ($ref->isStatic()) {
($this->closure)(...$parameters);
return;
}
$this->closure->call($this, ...$parameters);
}
public function describe(string $description): self
{
$this->setDescription($description);
return $this;
}
public function coroutine(bool $coroutine): self
{
$this->coroutine = $coroutine;
return $this;
}
/**
* @param null|callable(Crontab $crontab):Crontab $callback
*/
public function cron(string $rule, array $arguments = [], ?callable $callback = null): self
{
tap(
Schedule::command($this->getName(), $arguments)
->setName($this->getName())
->setRule($rule)
->setMemo($this->getDescription()),
$callback
);
return $this;
}
}