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

ZendLocator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 8
Bugs 0 Features 0
Metric Value
wmc 7
c 8
b 0
f 0
lcom 1
cbo 2
dl 0
loc 56
ccs 14
cts 14
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getHandlerForCommand() 0 21 4
A commandExists() 0 8 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