CommandTask::getArguments()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
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
    /** @var string */
18
    private $name;
19
20
    /** @var string */
21
    private $arguments = '';
22
23 28
    /**
24
     * @param string $name Command class or name (my:command)
25 28
     */
26 28
    public function __construct(string $name, string ...$arguments)
27
    {
28 28
        $parts = \explode(' ', $name, 2);
29 8
        $name = $parts[0];
30
31
        if (2 === \count($parts)) {
32 28
            $arguments = \array_merge([$parts[1]], $arguments);
33
        }
34 28
35 11
        $this->name = $name;
36
37
        if (!empty($arguments)) {
38 28
            $this->arguments(...$arguments);
39 28
        }
40
41 12
        parent::__construct($this->name);
42
    }
43 12
44
    public function arguments(string $argument, string ...$arguments): self
45 12
    {
46
        $this->arguments = \implode(' ', \array_merge([$argument], $arguments));
47
48 9
        return $this;
49
    }
50 9
51
    public function getArguments(): string
52
    {
53 2
        return (string) $this->arguments;
54
    }
55
56 2
    public function getContext(): array
57 2
    {
58
        return [
59
            'Command Name' => $this->name,
60
            'Command Arguments' => $this->getArguments() ?: '(none)',
61 6
        ];
62
    }
63 6
64 6
    public function createCommandInput(Application $application): InputInterface
65 5
    {
66
        return new StringInput(\implode(' ', \array_filter([
67
            $this->createCommand($application)->getName(),
68
            $this->getArguments(),
69 10
        ])));
70
    }
71 10
72
    public function createCommand(Application $application): Command
73 10
    {
74 5
        $registeredCommands = $application->all();
75
76
        if (isset($registeredCommands[$this->name])) {
77 5
            return $registeredCommands[$this->name];
78 5
        }
79 1
80
        foreach ($registeredCommands as $command) {
81
            if ($this->name === \get_class($command)) {
82
                return $command;
83 4
            }
84
        }
85
86
        throw new CommandNotFoundException("Command \"{$this->name}\" not registered.");
87
    }
88
}
89