Completed
Push — master ( aa8aa9...a51ad4 )
by Peter
02:05
created

ContainerCommandHandlerLocator::findHandler()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
/**
4
 * GpsLab component.
5
 *
6
 * @author    Peter Gribanov <[email protected]>
7
 * @copyright Copyright (c) 2011, Peter Gribanov
8
 * @license   http://opensource.org/licenses/MIT
9
 */
10
11
namespace GpsLab\Component\Command\Handler\Locator;
12
13
use GpsLab\Component\Command\Command;
14
use GpsLab\Component\Command\Handler\CommandHandler;
15
use Psr\Container\ContainerInterface;
16
17
class ContainerCommandHandlerLocator implements CommandHandlerLocator
18
{
19
    /**
20
     * @var ContainerInterface
21
     */
22
    private $container;
23
24
    /**
25
     * @var string[]
26
     */
27
    private $command_handler_ids = [];
28
29
    /**
30
     * @param ContainerInterface $container
31
     */
32 3
    public function __construct(ContainerInterface $container)
33
    {
34 3
        $this->container = $container;
35 3
    }
36
37
    /**
38
     * @param Command $command
39
     *
40
     * @return CommandHandler|null
41
     */
42 3
    public function findHandler(Command $command)
43
    {
44 3
        return $this->lazyLoad(get_class($command));
45
    }
46
47
    /**
48
     * @param string $command_name
49
     * @param string $service
50
     */
51 3
    public function registerService($command_name, $service)
52
    {
53 3
        $this->command_handler_ids[$command_name] = $service;
54 3
    }
55
56
    /**
57
     * @param $command_name
58
     *
59
     * @return CommandHandler
60
     */
61 3
    private function lazyLoad($command_name)
62
    {
63 3
        if (isset($this->command_handler_ids[$command_name])) {
64 3
            $handler = $this->container->get($this->command_handler_ids[$command_name]);
65
66 3
            if ($handler instanceof CommandHandler) {
67 1
                return $handler;
68
            }
69 2
        }
70
71 2
        return null;
72
    }
73
}
74