Completed
Push — master ( 244682...2c753b )
by Peter
04:25
created

ContainerCommandHandlerLocator::lazyLoad()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 4
cts 5
cp 0.8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 2.032
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 Psr\Container\ContainerInterface;
15
16
class ContainerCommandHandlerLocator implements CommandHandlerLocator
17
{
18
    /**
19
     * @var ContainerInterface
20
     */
21
    private $container;
22
23
    /**
24
     * @var array
25
     */
26
    private $command_handler_ids = [];
27
28
    /**
29
     * @param ContainerInterface $container
30
     */
31 4
    public function __construct(ContainerInterface $container)
32
    {
33 4
        $this->container = $container;
34 4
    }
35
36
    /**
37
     * @param Command $command
38
     *
39
     * @return callable|null
40
     */
41 4
    public function findHandler(Command $command)
42
    {
43 4
        return $this->lazyLoad(get_class($command));
44
    }
45
46
    /**
47
     * @param string $command_name
48
     * @param string $service
49
     * @param string $method
50
     */
51 4
    public function registerService($command_name, $service, $method = '__invoke')
52
    {
53 4
        $this->command_handler_ids[$command_name] = [$service, $method];
54 4
    }
55
56
    /**
57
     * @param string $command_name
58
     *
59
     * @return callable|null
60
     */
61 4
    private function lazyLoad($command_name)
62
    {
63 4
        if (isset($this->command_handler_ids[$command_name])) {
64 4
            list($service, $method) = $this->command_handler_ids[$command_name];
65
66 4
            return $this->resolve($this->container->get($service), $method);
67
        }
68
69
        return null;
70
    }
71
72
    /**
73
     * @param mixed  $service
74
     * @param string $method
75
     *
76
     * @return callable|null
77
     */
78 4
    private function resolve($service, $method)
79
    {
80 4
        if (is_callable($service)) {
81 1
            return $service;
82
        }
83
84 3
        if (is_callable([$service, $method])) {
85 1
            return [$service, $method];
86
        }
87
88 2
        return null;
89
    }
90
}
91