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

AmqpMessagePublisher::publish()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 7
ccs 0
cts 6
cp 0
crap 6
rs 10
c 0
b 0
f 0
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