Passed
Pull Request — master (#124)
by Alexander
02:09
created

CommandLoader::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Console;
6
7
use Psr\Container\ContainerInterface;
8
use Symfony\Component\Console\Command\Command;
9
use Symfony\Component\Console\Command\LazyCommand;
10
use Symfony\Component\Console\CommandLoader\CommandLoaderInterface;
11
use Symfony\Component\Console\Exception\CommandNotFoundException;
12
13
final class CommandLoader implements CommandLoaderInterface
14
{
15
    private ContainerInterface $container;
16
17
    /**
18
     * @var array<string, string>
19
     */
20
    private array $commandMap;
21
22
    /**
23
     * @param array<string, string> $commandMap An array with command names as keys and service ids as values
24
     */
25 33
    public function __construct(ContainerInterface $container, array $commandMap)
26
    {
27 33
        $this->container = $container;
28 33
        $this->commandMap = $commandMap;
29 33
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34 9
    public function get(string $name)
35
    {
36 9
        if (!$this->has($name)) {
37
            throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name));
38
        }
39
40
        /** @var Command $commandClass */
41 9
        $commandClass = $this->commandMap[$name];
42 9
        $description = $commandClass::getDefaultDescription();
43
44 9
        if ($description === null) {
45 3
            return $this->getCommandInstance($name);
46
        }
47
48 6
        return new LazyCommand(
49 6
            $name,
50 6
            [],
51
            $description,
52 6
            false,
53 6
            function () use ($name) {
54 5
                return $this->getCommandInstance($name);
55 6
            }
56
        );
57
    }
58
59 8
    private function getCommandInstance(string $name): Command
60
    {
61
        /** @var Command $command */
62 8
        $command = $this->container->get($this->commandMap[$name]);
63 8
        if ($command->getName() !== $name) {
64 1
            $command->setName($name);
65
        }
66
67 8
        return $command;
68
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73 9
    public function has(string $name)
74
    {
75 9
        return isset($this->commandMap[$name]) && $this->container->has($this->commandMap[$name]);
76
    }
77
78
    /**
79
     * {@inheritdoc}
80
     */
81
    public function getNames()
82
    {
83
        return array_keys($this->commandMap);
84
    }
85
}
86