Completed
Pull Request — 0.4 (#35)
by jean
03:28
created

AmqpMessagePublisher   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 47
ccs 0
cts 28
cp 0
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
namespace Darkilliant\MqProcessBundle\Message\Publisher;
4
5
use PhpAmqpLib\Channel\AMQPChannel;
6
use PhpAmqpLib\Message\AMQPMessage;
7
8
class AmqpMessagePublisher
9
{
10
    /** @var AMQPChannel */
11
    private $channel;
12
    /** @var string */
13
    private $queue;
14
    /** @var string */
15
    private $exchange;
16
    /** @var int */
17
    private $batch = 0;
18
    /** @var bool */
19
    private $persistant;
20
21
    public function __construct(AMQPChannel $channel, string $queue, string $exchange, bool $persistant)
22
    {
23
        $this->channel = $channel;
24
        $this->queue = $queue;
25
        $this->exchange = $exchange;
26
        $this->persistant = $persistant;
27
28
        $this->channel->queue_declare($this->queue, false, $this->persistant);
29
        $this->channel->queue_bind($this->queue, $this->exchange, $this->queue);
30
    }
31
32
    public function publish(string $message, int $batchCount)
33
    {
34
        ++$this->batch;
35
        $this->channel->batch_basic_publish(new AMQPMessage($message), $this->exchange, $this->queue);
36
37
        if ($this->batch >= $batchCount) {
38
            $this->flush();
39
        }
40
    }
41
42
    public function finalize()
43
    {
44
        $this->flush();
45
    }
46
47
    public function flush()
48
    {
49
        $this->channel->publish_batch();
50
    }
51
52
    public function countMessages(): int
53
    {
54
        return $this->channel->queue_declare($this->queue, true)->messageCount;
55
    }
56
}
57