Passed
Pull Request — 0.4 (#35)
by jean
03:13
created

AmqpMessagePublisher::publish()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Darkilliant\MqProcessBundle\Message\Publisher;
6
7
use Darkilliant\MqProcessBundle\Message\Message;
8
use PhpAmqpLib\Channel\AMQPChannel;
9
use PhpAmqpLib\Message\AMQPMessage;
10
11
class AmqpMessagePublisher implements MessagePublisherInterface
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 4
    public function __construct(AMQPChannel $channel, string $queue, string $exchange, bool $persistant)
25
    {
26 4
        $this->channel = $channel;
27 4
        $this->queue = $queue;
28 4
        $this->exchange = $exchange;
29 4
        $this->persistant = $persistant;
30
31 4
        $this->channel->queue_declare($this->queue, false, $this->persistant, false, false);
32 4
        $this->channel->queue_bind($this->queue, $this->exchange, $this->queue);
33 4
    }
34
35 1
    public function publish(Message $message, int $batchCount)
36
    {
37 1
        ++$this->batch;
38 1
        $this->channel->batch_basic_publish($this->buildMessage($message), $this->exchange, $this->queue);
39
40 1
        if ($this->batch >= $batchCount) {
41 1
            $this->flush();
42
        }
43 1
    }
44
45 1
    public function finalize()
46
    {
47 1
        $this->flush();
48 1
    }
49
50 2
    public function flush()
51
    {
52 2
        $this->channel->publish_batch();
53 2
    }
54
55 1
    public function countMessages(): int
56
    {
57 1
        return $this->channel->queue_declare($this->queue, true)[1];
58
    }
59
60 1
    private function buildMessage(Message $message)
61
    {
62 1
        return new AMQPMessage($message->getBody());
63
    }
64
}
65