1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Service dispatcher |
4
|
|
|
* User: moyo |
5
|
|
|
* Date: 20/09/2017 |
6
|
|
|
* Time: 4:13 PM |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Carno\RPC\Service; |
10
|
|
|
|
11
|
|
|
use Carno\RPC\Chips\DInstances; |
12
|
|
|
use Carno\RPC\Exception\InvalidExecutingResultException; |
13
|
|
|
use Carno\RPC\Exception\RequestMethodNotFoundException; |
14
|
|
|
use Carno\RPC\Exception\RequestServiceNotFoundException; |
15
|
|
|
use Carno\RPC\Protocol\Request; |
16
|
|
|
use Carno\RPC\Protocol\Response; |
17
|
|
|
use Google\Protobuf\Internal\Message; |
18
|
|
|
|
19
|
|
|
class Dispatcher |
20
|
|
|
{ |
21
|
|
|
use DInstances; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var Router |
25
|
|
|
*/ |
26
|
|
|
private $router = null; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @var Instances |
30
|
|
|
*/ |
31
|
|
|
private $instances = null; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Dispatcher constructor. |
35
|
|
|
* @param Router $router |
36
|
|
|
* @param Instances $instances |
37
|
|
|
*/ |
38
|
|
|
public function __construct(Router $router, Instances $instances) |
39
|
|
|
{ |
40
|
|
|
$this->router = $router; |
41
|
|
|
$this->instances = $instances; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param Request $request |
46
|
|
|
* @return Response |
47
|
|
|
*/ |
48
|
|
|
public function invoke(Request $request) |
49
|
|
|
{ |
50
|
|
|
if (empty($route = $this->router->get($request->server(), $request->service()))) { |
51
|
|
|
throw new RequestServiceNotFoundException("{$request->server()}.{$request->service()}"); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @var Specification $spec |
56
|
|
|
* @var string $impl |
57
|
|
|
*/ |
58
|
|
|
list($spec, $impl) = $route; |
59
|
|
|
|
60
|
|
|
if (empty($requestC = $spec->getMethodRequest($request->method()))) { |
61
|
|
|
throw new RequestMethodNotFoundException($request->method()); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
$program = $this->instances->get($impl); |
65
|
|
|
$method = $request->method(); |
66
|
|
|
|
67
|
|
|
$result = yield $program->$method($request->struct(new $requestC)); |
|
|
|
|
68
|
|
|
|
69
|
|
|
if ($result instanceof Message) { |
70
|
|
|
return new Response($request, $result); |
71
|
|
|
} else { |
72
|
|
|
throw new InvalidExecutingResultException; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|