Completed
Pull Request — 0.4 (#35)
by jean
11:34
created

AmqpMessagePublisher   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 47
rs 10
c 0
b 0
f 0
wmc 6

5 Methods

Rating   Name   Duplication   Size   Complexity  
A publish() 0 7 2
A countMessages() 0 3 1
A flush() 0 3 1
A __construct() 0 9 1
A finalize() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Darkilliant\MqProcessBundle\Message\Publisher;
6
7
use PhpAmqpLib\Channel\AMQPChannel;
8
use PhpAmqpLib\Message\AMQPMessage;
9
10
11
class AmqpMessagePublisher
12
{
13
    /** @var AMQPChannel */
14
    private $channel;
15
    /** @var string */
16
    private $queue;
17
    /** @var string */
18
    private $exchange;
19
    /** @var int */
20
    private $batch = 0;
21
    /** @var bool */
22
    private $persistant;
23
24
    public function __construct(AMQPChannel $channel, string $queue, string $exchange, bool $persistant)
25
    {
26
        $this->channel = $channel;
27
        $this->queue = $queue;
28
        $this->exchange = $exchange;
29
        $this->persistant = $persistant;
30
31
        $this->channel->queue_declare($this->queue, false, $this->persistant, false, false);
32
        $this->channel->queue_bind($this->queue, $this->exchange, $this->queue);
33
    }
34
35
    public function publish(string $message, int $batchCount)
36
    {
37
        ++$this->batch;
38
        $this->channel->batch_basic_publish(new AMQPMessage($message), $this->exchange, $this->queue);
39
40
        if ($this->batch >= $batchCount) {
41
            $this->flush();
42
        }
43
    }
44
45
    public function finalize()
46
    {
47
        $this->flush();
48
    }
49
50
    public function flush()
51
    {
52
        $this->channel->publish_batch();
53
    }
54
55
    public function countMessages(): int
56
    {
57
        return $this->channel->queue_declare($this->queue, true)->messageCount;
58
    }
59
}
60