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\Query\Handler\Locator; |
12
|
|
|
|
13
|
|
|
use GpsLab\Component\Query\Query; |
14
|
|
|
use Psr\Container\ContainerInterface; |
15
|
|
|
|
16
|
|
|
class ContainerQueryHandlerLocator implements QueryHandlerLocator |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* @var ContainerInterface |
20
|
|
|
*/ |
21
|
|
|
private $container; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var array |
25
|
|
|
*/ |
26
|
|
|
private $query_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 Query $query |
38
|
|
|
* |
39
|
|
|
* @return callable|null |
40
|
|
|
*/ |
41
|
4 |
|
public function findHandler(Query $query) |
42
|
|
|
{ |
43
|
4 |
|
return $this->lazyLoad(get_class($query)); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @param string $query_name |
48
|
|
|
* @param string $service |
49
|
|
|
* @param string $method |
50
|
|
|
*/ |
51
|
4 |
|
public function registerService($query_name, $service, $method = '__invoke') |
52
|
|
|
{ |
53
|
4 |
|
$this->query_handler_ids[$query_name] = [$service, $method]; |
54
|
4 |
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param $query_name |
58
|
|
|
* |
59
|
|
|
* @return callable |
60
|
|
|
*/ |
61
|
4 |
|
private function lazyLoad($query_name) |
62
|
|
|
{ |
63
|
4 |
|
if (isset($this->query_handler_ids[$query_name])) { |
64
|
4 |
|
list($service, $method) = $this->query_handler_ids[$query_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
|
|
|
|