Completed
Push — master ( cfb02d...d520a3 )
by Mike
04:37 queued 04:19
created

ZendLocator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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