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

CommandLoader::has()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
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() ?? $this->getCommandInstance($name)->getName() ?? '';
43
44 9
        return new LazyCommand(
45 9
            $name,
46 9
            [],
47
            $description,
48 9
            false,
49 9
            function () use ($name) {
50 8
                return $this->getCommandInstance($name);
51 9
            }
52
        );
53
    }
54
55 8
    private function getCommandInstance(string $name): Command
56
    {
57
        /** @var Command $command */
58 8
        $command = $this->container->get($this->commandMap[$name]);
59 8
        if ($command->getName() !== $name) {
60 1
            $command->setName($name);
61
        }
62
63 8
        return $command;
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69 9
    public function has(string $name)
70
    {
71 9
        return isset($this->commandMap[$name]) && $this->container->has($this->commandMap[$name]);
72
    }
73
74
    /**
75
     * {@inheritdoc}
76
     */
77
    public function getNames()
78
    {
79
        return array_keys($this->commandMap);
80
    }
81
}
82