1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace OldSound\RabbitMqBundle\ReceiverExecutor; |
4
|
|
|
|
5
|
|
|
use OldSound\RabbitMqBundle\Declarations\RpcConsumeOptions; |
6
|
|
|
use OldSound\RabbitMqBundle\Receiver\ReceiverException; |
7
|
|
|
use OldSound\RabbitMqBundle\Receiver\ReceiverInterface; |
8
|
|
|
use OldSound\RabbitMqBundle\Receiver\ReplyReceiverInterface; |
9
|
|
|
|
10
|
|
|
class ReplyReceiverExecutor implements ReceiverExecutorInterface |
11
|
|
|
{ |
12
|
|
|
/** @var RpcConsumeOptions */ |
13
|
|
|
protected $options; |
14
|
|
|
|
15
|
|
|
public function __construct(RpcConsumeOptions $options) |
16
|
|
|
{ |
17
|
|
|
$this->options = $options; |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param $receiver ReplyReceiverInterface |
22
|
|
|
*/ |
23
|
|
|
public function execute(array $messages, $receiver): array |
24
|
|
|
{ |
25
|
|
|
if (!$this->support($receiver)) { |
26
|
|
|
throw new \InvalidArgumentException('TOOD'); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
if (count($messages) !== 1) { |
30
|
|
|
throw new \InvalidArgumentException('todo'); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
$message = $messages[0]; |
34
|
|
|
|
35
|
|
|
if (!($message->get($this->options->replayToProperty) && $message->get($this->options->correlationIdProperty))) { |
36
|
|
|
throw new \InvalidArgumentException('todo'); // TODO |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
try { |
40
|
|
|
$reply = $receiver->execute($message); |
41
|
|
|
} catch (ReceiverException $exception) { |
42
|
|
|
return [$exception->getCode()]; |
43
|
|
|
} |
44
|
|
|
$this->sendReply($message->getChannel(), $reply, $message->get($this->options->replayToProperty), $message->get($this->options->correlationIdProperty)); |
45
|
|
|
|
46
|
|
|
return [ReceiverInterface::MSG_ACK]; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
protected function sendReply(\AMQPChannel $channel, $reply, $replyTo, $correlationId) |
50
|
|
|
{ |
51
|
|
|
$body = $this->serializer->serialize($reply); |
|
|
|
|
52
|
|
|
$message = new AMQPMessage($body, ['content_type' => 'text/plain'] + $this->options->replayMessageProperties + [ |
|
|
|
|
53
|
|
|
$this->options->correlationIdProperty => $correlationId, |
54
|
|
|
]); |
55
|
|
|
$channel->basic_publish($message , '', $replyTo); |
|
|
|
|
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
public function support($receiver): bool |
59
|
|
|
{ |
60
|
|
|
return $receiver instanceof ReplyReceiverInterface; |
61
|
|
|
} |
62
|
|
|
} |