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

SymfonyContainerCommandHandlerLocator::lazyLoad()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

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