Test Failed
Pull Request — master (#39)
by Aleksandr
08:25
created

BatchExecuteCallbackStrategy   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 15
c 0
b 0
f 0
dl 0
loc 56
rs 10
wmc 11

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A onCatchTimeout() 0 4 2
A consumeCallback() 0 6 2
A isBatchEmpty() 0 3 1
A canPrecessMultiMessages() 0 3 1
A onStopConsuming() 0 4 2
A onMessageProcessed() 0 3 1
A isBatchCompleted() 0 3 1
1
<?php
2
3
namespace OldSound\RabbitMqBundle\ExecuteCallbackStrategy;
4
5
use OldSound\RabbitMqBundle\Declarations\QueueConsuming;
6
use PhpAmqpLib\Exception\AMQPTimeoutException;
7
use PhpAmqpLib\Message\AMQPMessage;
8
9
class BatchExecuteCallbackStrategy extends AbstractExecuteCallbackStrategy
10
{
11
    /** @var int */
12
    private $batchCount;
13
    /** @var AMQPMessage[] */
14
    protected $messagesBatch = [];
15
16
    public function __construct(int $batchCount)
17
    {
18
        $this->batchCount = $batchCount;
19
    }
20
21
    public function canPrecessMultiMessages(): bool
22
    {
23
        return true;
24
    }
25
26
    public function consumeCallback(AMQPMessage $message)
27
    {
28
        $this->messagesBatch[$message->getDeliveryTag()] = $message;
29
30
        if ($this->isBatchCompleted()) {
31
            $this->proccessMessages($this->messagesBatch);
32
        }
33
    }
34
35
    public function onMessageProcessed(AMQPMessage $message)
36
    {
37
        unset($this->messagesBatch[array_search($message, $this->messagesBatch, true)]);
38
    }
39
40
    public function onCatchTimeout(AMQPTimeoutException $e)
41
    {
42
        if (!$this->isBatchEmpty()) {
43
            $this->proccessMessages($this->messagesBatch);
44
        }
45
    }
46
47
    public function onStopConsuming()
48
    {
49
        if (!$this->isBatchEmpty()) {
50
            $this->proccessMessages($this->messagesBatch);
51
        }
52
    }
53
54
    protected function isBatchCompleted(): bool
55
    {
56
        return count($this->messagesBatch) === $this->batchCount;
57
    }
58
59
    /**
60
     * @return  bool
61
     */
62
    protected function isBatchEmpty()
63
    {
64
        return count($this->messagesBatch) === 0;
65
    }
66
}