1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ccovey\RabbitMQ\Consumer; |
4
|
|
|
|
5
|
|
|
use Ccovey\RabbitMQ\ChannelInterface; |
6
|
|
|
use Ccovey\RabbitMQ\Connection\ConnectionInterface; |
7
|
|
|
use Ccovey\RabbitMQ\Queue; |
8
|
|
|
use Ccovey\RabbitMQ\QueuedMessage; |
9
|
|
|
use Ccovey\RabbitMQ\QueuedMessageInterface; |
10
|
|
|
use PhpAmqpLib\Message\AMQPMessage; |
11
|
|
|
|
12
|
|
|
class Consumer implements ConsumerInterface |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var ConnectionInterface |
16
|
|
|
*/ |
17
|
|
|
private $connection; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var ChannelInterface |
21
|
|
|
*/ |
22
|
|
|
private $channel; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var callable |
26
|
|
|
*/ |
27
|
|
|
private $callback; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var callable |
31
|
|
|
*/ |
32
|
|
|
private $restartCheckCallable; |
33
|
|
|
|
34
|
3 |
|
public function __construct(ConnectionInterface $connection, string $channelId = '') |
35
|
|
|
{ |
36
|
3 |
|
$this->connection = $connection; |
37
|
3 |
|
$this->channel = $this->connection->getChannel($channelId); |
38
|
3 |
|
} |
39
|
|
|
|
40
|
1 |
|
public function setCallback(callable $callback = null) |
41
|
|
|
{ |
42
|
1 |
|
$this->callback = $callback; |
43
|
1 |
|
} |
44
|
|
|
|
45
|
1 |
|
public function setRestartCheckCallable(callable $callable) |
46
|
|
|
{ |
47
|
1 |
|
$this->restartCheckCallable = $callable; |
48
|
1 |
|
} |
49
|
|
|
|
50
|
2 |
|
public function consume(Consumable $consumable) |
51
|
|
|
{ |
52
|
2 |
|
$consumable->setCallback([$this, 'process']); |
53
|
2 |
|
$this->channel->consume($consumable); |
54
|
|
|
|
55
|
2 |
|
while (count($this->channel->getCallbacks())) { |
56
|
2 |
|
$this->channel->wait(); |
57
|
|
|
} |
58
|
1 |
|
} |
59
|
|
|
|
60
|
1 |
|
public function getMessage(Consumable $consumable) : QueuedMessage |
61
|
|
|
{ |
62
|
1 |
|
return new QueuedMessage($this->channel->getMessage($consumable)); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function getChannel() : ChannelInterface |
66
|
|
|
{ |
67
|
|
|
return $this->channel; |
68
|
|
|
} |
69
|
|
|
|
70
|
1 |
|
public function process(AMQPMessage $message) |
71
|
|
|
{ |
72
|
1 |
|
$queuedMessage = new QueuedMessage($message); |
73
|
|
|
|
74
|
1 |
|
call_user_func($this->callback, $queuedMessage); |
75
|
|
|
|
76
|
1 |
|
$this->checkRestart($queuedMessage); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
public function getSize($queue) : int |
80
|
|
|
{ |
81
|
|
|
$queueParams = new Queue( |
82
|
|
|
$queue, |
83
|
|
|
'', |
84
|
|
|
null, |
85
|
|
|
true |
86
|
|
|
); |
87
|
|
|
|
88
|
|
|
return $this->channel->getQueueSize($queueParams); |
89
|
|
|
} |
90
|
|
|
|
91
|
1 |
|
private function checkRestart(QueuedMessageInterface $queuedMessage) |
92
|
|
|
{ |
93
|
1 |
|
if ($this->restartCheckCallable) { |
94
|
1 |
|
($this->restartCheckCallable)($queuedMessage); |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|