|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Tonic\Component\ApiLayer\JsonRpc\Method; |
|
4
|
|
|
|
|
5
|
|
|
use Tonic\Component\ApiLayer\JsonRpc\Method\ArgumentMapper\ArgumentMapperInterface; |
|
6
|
|
|
use Tonic\Component\ApiLayer\JsonRpc\Method\Exception\MethodNotFoundException; |
|
7
|
|
|
use Tonic\Component\ApiLayer\JsonRpc\Method\Loader\LoaderInterface; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Dispatches method call. |
|
11
|
|
|
*/ |
|
12
|
|
|
class MethodDispatcher implements MethodDispatcherInterface |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* @var LoaderInterface |
|
16
|
|
|
*/ |
|
17
|
|
|
private $loader; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @var ArgumentMapperInterface |
|
21
|
|
|
*/ |
|
22
|
|
|
private $argumentMapper; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @var MethodInvokerInterface |
|
26
|
|
|
*/ |
|
27
|
|
|
private $methodInvoker; |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* @var MethodCollection|null |
|
31
|
|
|
*/ |
|
32
|
|
|
private $methodCollection = null; |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Constructor. |
|
36
|
|
|
* |
|
37
|
|
|
* @param LoaderInterface $loader |
|
38
|
|
|
* @param ArgumentMapperInterface $argumentMapper |
|
39
|
|
|
* @param MethodInvokerInterface $methodInvoker |
|
40
|
|
|
*/ |
|
41
|
|
|
public function __construct( |
|
42
|
|
|
LoaderInterface $loader, |
|
43
|
|
|
ArgumentMapperInterface $argumentMapper, |
|
44
|
|
|
MethodInvokerInterface $methodInvoker |
|
45
|
|
|
) { |
|
46
|
|
|
$this->loader = $loader; |
|
47
|
|
|
$this->argumentMapper = $argumentMapper; |
|
48
|
|
|
$this->methodInvoker = $methodInvoker; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* @return MethodCollection |
|
53
|
|
|
*/ |
|
54
|
|
|
public function getMethodCollection() |
|
55
|
|
|
{ |
|
56
|
|
|
if (null === $this->methodCollection) { |
|
57
|
|
|
$this->methodCollection = $this->loader->load(); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
return $this->methodCollection; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* @param string $methodName |
|
65
|
|
|
* @param array $arguments |
|
66
|
|
|
* |
|
67
|
|
|
* @return mixed |
|
68
|
|
|
* |
|
69
|
|
|
* @throws MethodNotFoundException |
|
70
|
|
|
*/ |
|
71
|
|
|
public function dispatch($methodName, array $arguments = []) |
|
72
|
|
|
{ |
|
73
|
|
|
$methodCollection = $this->getMethodCollection(); |
|
74
|
|
|
|
|
75
|
|
|
$callable = $methodCollection->get($methodName); |
|
76
|
|
|
if (! is_callable($callable)) { |
|
77
|
|
|
throw new MethodNotFoundException(sprintf('Method "%s" is not found', $methodName)); |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
$requestObject = $this->argumentMapper->mapToObject($callable, $arguments); |
|
81
|
|
|
|
|
82
|
|
|
return $this->methodInvoker->invoke($callable, $requestObject); |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|