Passed
Branch php8 (4b68f8)
by Mike
06:45
created

LaminasLocator::getHandlerForCommand()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 9
cts 9
cp 1
rs 9.6666
c 0
b 0
f 0
cc 4
nc 4
nop 1
crap 4
1
<?php
2
namespace TacticianModule\Locator;
3
4
use League\Tactician\Exception\MissingHandlerException;
5
use League\Tactician\Handler\Locator\HandlerLocator;
6
use Psr\Container\ContainerInterface;
7
8
class LaminasLocator implements HandlerLocator
9
{
10
    /** @var array */
11
    protected $handlerMap;
12
13
    private $container;
14
15 5
    public function __construct(ContainerInterface $container)
16
    {
17 5
        $this->container = $container;
18 5
    }
19
20
    /**
21
     * Retrieves the handler for a specified command
22
     *
23
     * @param string $commandName
24
     *
25
     * @return mixed
26
     *
27
     * @throws MissingHandlerException
28
     */
29 4
    public function getHandlerForCommand($commandName)
30
    {
31 4
        if (!$this->commandExists($commandName)) {
32 1
            throw MissingHandlerException::forCommand($commandName);
33
        }
34
35 3
        $serviceNameOrFQCN = $this->handlerMap[$commandName];
36
37 3
        if ($this->container->has($serviceNameOrFQCN)) {
38 1
            return $this->container->get($serviceNameOrFQCN);
39
        }
40
41 2
        if (class_exists($serviceNameOrFQCN)) {
42 1
            return new $serviceNameOrFQCN();
43
        }
44
45 1
        throw MissingHandlerException::forCommand($commandName);
46
    }
47
48
    /**
49
     * @param string $commandName
50
     * @return bool
51
     */
52 4
    protected function commandExists($commandName)
53
    {
54 4
        if (!$this->handlerMap) {
55 4
            $this->handlerMap = $this->container->get('config')['tactician']['handler-map'];
56
        }
57
58 4
        return isset($this->handlerMap[$commandName]);
59
    }
60
}
61