1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Cmobi\RabbitmqBundle\Rpc; |
4
|
|
|
|
5
|
|
|
use Cmobi\RabbitmqBundle\Routing\MethodRouter; |
6
|
|
|
use Cmobi\RabbitmqBundle\Rpc\Exception\RpcGenericErrorException; |
7
|
|
|
use Cmobi\RabbitmqBundle\Rpc\Exception\RpcInvalidRequestException; |
8
|
|
|
use Cmobi\RabbitmqBundle\Rpc\Exception\RpcParserErrorException; |
9
|
|
|
use Cmobi\RabbitmqBundle\Rpc\Request\RpcRequest; |
10
|
|
|
use Cmobi\RabbitmqBundle\Rpc\Request\RpcRequestCollection; |
11
|
|
|
use PhpAmqpLib\Message\AMQPMessage; |
12
|
|
|
|
13
|
|
|
class RpcMessager |
14
|
|
|
{ |
15
|
|
|
private $router; |
16
|
|
|
|
17
|
|
|
public function __construct(MethodRouter $router) |
18
|
|
|
{ |
19
|
|
|
$this->router = $router; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param AMQPMessage $message |
24
|
|
|
* @return RpcRequestCollection |
25
|
|
|
* @throws RpcParserErrorException |
26
|
|
|
*/ |
27
|
|
|
public function parseAMQPMessage(AMQPMessage $message) |
28
|
|
|
{ |
29
|
|
|
$body = $message->body; |
30
|
|
|
$requestCollection = new RpcRequestCollection(); |
31
|
|
|
|
32
|
|
|
try { |
33
|
|
|
/** |
34
|
|
|
* @var RpcRequestCollection $requests |
35
|
|
|
*/ |
36
|
|
|
$requests = json_decode($body, true); |
37
|
|
|
|
38
|
|
|
foreach ($requests as $requestArr) { |
39
|
|
|
|
40
|
|
|
if (!is_array($requestArr)) { |
41
|
|
|
throw new RpcInvalidRequestException(); |
42
|
|
|
} |
43
|
|
|
$request = new RpcRequest(); |
44
|
|
|
$request->fromArray($requestArr); |
45
|
|
|
$this->buildRequest($request); |
46
|
|
|
$requestCollection->add($request); |
47
|
|
|
} |
48
|
|
|
} catch (\Exception $e) { |
49
|
|
|
throw new RpcParserErrorException(); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return $requestCollection; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param $request |
57
|
|
|
* @return RpcRequest |
58
|
|
|
*/ |
59
|
|
|
private function buildRequest($request) |
60
|
|
|
{ |
61
|
|
|
try { |
62
|
|
|
$this->router->setContext($request); |
63
|
|
|
|
64
|
|
|
if (!$request->attributes->has('_controller')) { |
65
|
|
|
$parameters = $this->router->match($request->getMethod()); |
66
|
|
|
$request->attributes->add($parameters); |
67
|
|
|
} |
68
|
|
|
} catch (RpcGenericErrorException $e) { |
69
|
|
|
$request->attributes->add(['error' => $e]); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
return $request; |
73
|
|
|
} |
74
|
|
|
} |