Passed
Push — master ( 81662d...79e5c8 )
by Kevin
02:02
created

CommandTask::createCommand()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 15
rs 10
ccs 8
cts 8
cp 1
cc 4
nc 4
nop 1
crap 4
1
<?php
2
3
namespace Zenstruck\ScheduleBundle\Schedule\Task;
4
5
use Symfony\Component\Console\Application;
6
use Symfony\Component\Console\Command\Command;
7
use Symfony\Component\Console\Exception\CommandNotFoundException;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Input\StringInput;
10
use Zenstruck\ScheduleBundle\Schedule\Task;
11
12
/**
13
 * @author Kevin Bond <[email protected]>
14
 */
15
final class CommandTask extends Task
16
{
17
    private $name;
18
    private $arguments;
19
20 19
    public function __construct(string $name, string ...$arguments)
21
    {
22 19
        $parts = \explode(' ', $name, 2);
23 19
        $name = $parts[0];
24
25 19
        if (2 === \count($parts)) {
26 4
            $arguments = \array_merge([$parts[1]], $arguments);
27
        }
28
29 19
        $this->name = $name;
30
31 19
        $this->arguments(...$arguments);
32
33 19
        parent::__construct($this->name);
34 19
    }
35
36 19
    public function arguments(string ...$arguments): self
37
    {
38 19
        $this->arguments = \implode(' ', $arguments);
39
40 19
        return $this;
41
    }
42
43 8
    public function getArguments(): string
44
    {
45 8
        return $this->arguments;
46
    }
47
48 6
    public function createCommandInput(Application $application): InputInterface
49
    {
50 6
        return new StringInput(\implode(' ', \array_filter([
51 6
            $this->createCommand($application)->getName(),
52 5
            $this->getArguments(),
53
        ])));
54
    }
55
56 10
    public function createCommand(Application $application): Command
57
    {
58 10
        $registeredCommands = $application->all();
59
60 10
        if (isset($registeredCommands[$this->name])) {
61 5
            return $registeredCommands[$this->name];
62
        }
63
64 5
        foreach ($registeredCommands as $command) {
65 5
            if ($this->name === \get_class($command)) {
66 1
                return $command;
67
            }
68
        }
69
70 4
        throw new CommandNotFoundException("Command \"{$this->name}\" not registered.");
71
    }
72
}
73