1 | <?php |
||
2 | |||
3 | namespace Kunnu\RabbitMQ; |
||
4 | |||
5 | use Illuminate\Support\Collection; |
||
6 | use PhpAmqpLib\Channel\AMQPChannel; |
||
7 | |||
8 | class RabbitMQDelivery |
||
9 | { |
||
10 | protected Collection $config; |
||
11 | |||
12 | public function __construct(array $config = []) |
||
13 | { |
||
14 | $this->setConfig($config); |
||
15 | } |
||
16 | |||
17 | /** |
||
18 | * @return Collection |
||
19 | */ |
||
20 | public function getConfig(): Collection |
||
21 | { |
||
22 | return $this->config; |
||
23 | } |
||
24 | |||
25 | /** |
||
26 | * @param array $config |
||
27 | * @return RabbitMQDelivery |
||
28 | */ |
||
29 | public function setConfig(array $config): self |
||
30 | { |
||
31 | $this->config = new Collection($config); |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
32 | |||
33 | return $this; |
||
34 | } |
||
35 | |||
36 | /** |
||
37 | * Acknowledge a message. |
||
38 | * |
||
39 | * @return bool |
||
40 | * |
||
41 | * @throws RabbitMQException |
||
42 | */ |
||
43 | public function acknowledge(): bool |
||
44 | { |
||
45 | $config = $this->getConfig(); |
||
46 | $info = $config->get('delivery_info', []); |
||
47 | /** |
||
48 | * @var AMQPChannel |
||
49 | */ |
||
50 | $channel = $info['channel'] ?? null; |
||
51 | |||
52 | if (!$channel) { |
||
53 | throw new RabbitMQException('Delivery info or channel is not set'); |
||
54 | } |
||
55 | |||
56 | $channel->basic_ack( |
||
57 | $info['delivery_tag'] ?? null |
||
58 | ); |
||
59 | |||
60 | if ($config->get('body') === 'quit') { |
||
61 | $channel->basic_cancel( |
||
62 | $info['consumer_tag'] ?? null |
||
63 | ); |
||
64 | } |
||
65 | |||
66 | return true; |
||
67 | } |
||
68 | |||
69 | /** |
||
70 | * Rejects message w/ requeue. |
||
71 | * |
||
72 | * @param bool $requeue |
||
73 | * @return bool |
||
74 | * |
||
75 | * @throws RabbitMQException |
||
76 | */ |
||
77 | public function reject($requeue = false): bool |
||
78 | { |
||
79 | $config = $this->getConfig(); |
||
80 | $info = $config->get('delivery_info'); |
||
81 | /** |
||
82 | * @var AMQPChannel |
||
83 | */ |
||
84 | $channel = $info['channel'] ?? null; |
||
85 | |||
86 | if (!$channel) { |
||
87 | throw new RabbitMQException('Delivery info or channel is not set'); |
||
88 | } |
||
89 | |||
90 | $channel->basic_reject( |
||
91 | $info['delivery_tag'] ?? null, |
||
92 | $requeue |
||
93 | ); |
||
94 | |||
95 | return true; |
||
96 | } |
||
97 | } |
||
98 |