Completed
Pull Request — master (#2)
by lee
06:59
created

findHandler()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
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
    public function findHandler(Command $command)
33
    {
34
        return $this->lazyLoad(get_class($command));
35
    }
36
37
    /**
38
     * @param string $command_name
39
     * @param string $service
40
     * @param string $method
41
     */
42
    public function registerService($command_name, $service, $method = '__invoke')
43
    {
44
        $this->command_handler_ids[$command_name] = [$service, $method];
45
    }
46
47
    /**
48
     * @param string $command_name
49
     *
50
     * @return callable|null
51
     */
52
    private function lazyLoad($command_name)
53
    {
54
        if ($this->container instanceof ContainerInterface && isset($this->command_handler_ids[$command_name])) {
55
            list($service, $method) = $this->command_handler_ids[$command_name];
56
57
            return $this->resolve($this->container->get($service), $method);
58
        }
59
60
        return null;
61
    }
62
63
    /**
64
     * @param mixed  $service
65
     * @param string $method
66
     *
67
     * @return callable|null
68
     */
69
    private function resolve($service, $method)
70
    {
71
        if (is_callable($service)) {
72
            return $service;
73
        }
74
75
        if (is_callable([$service, $method])) {
76
            return [$service, $method];
77
        }
78
79
        return null;
80
    }
81
}
82