Completed
Push — master ( e9a852...6de009 )
by Mike
03:07
created

QueueWorker::iterate()   A

Complexity

Conditions 3
Paths 6

Size

Total Lines 22
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 3.0146

Importance

Changes 3
Bugs 0 Features 1
Metric Value
dl 0
loc 22
ccs 15
cts 17
cp 0.8824
rs 9.2
c 3
b 0
f 1
cc 3
eloc 18
nc 6
nop 2
crap 3.0146
1
<?php
2
3
namespace MGDigital\BusQue;
4
5
use MGDigital\BusQue\Exception\TimeoutException;
6
use Psr\Log\LoggerInterface;
7
use Psr\Log\LogLevel;
8
9
class QueueWorker
10
{
11
12
    private $implementation;
13
    private $logger;
14
15 3
    public function __construct(Implementation $implementation, LoggerInterface $logger = null)
16
    {
17 3
        $this->implementation = $implementation;
18 3
        $this->logger = $logger;
19 3
    }
20
21 2
    public function work(string $queueName, int $n = null, int $time = null)
22
    {
23 2
        $stopwatchStart = time();
24 2
        while ($n === null || $n > 0) {
25 2
            $this->iterate($queueName, $time);
26 2
            $n === null || $n--;
27 2
            if ($time !== null && (time() - $stopwatchStart >= $time)) {
28
                break;
29
            }
30
        }
31 2
    }
32
33 2
    private function iterate(string $queueName, int $time = null)
34
    {
35
        try {
36 2
            $received = $this->implementation->getQueueDriver()
37 2
                ->awaitCommand($queueName, $time);
38
        } catch (TimeoutException $e) {
39
            return;
40
        }
41 2
        $command = $this->implementation->getCommandSerializer()
42 2
            ->unserialize($received->getSerialized());
43 2
        $this->log(LogLevel::DEBUG, 'Command received', compact('command'));
44
        try {
45 2
            $this->implementation->getCommandBusAdapter()
46 2
                ->handle($command, true);
47 2
            $this->log(LogLevel::INFO, 'Command handled', compact('command'));
48 1
        } catch (\Throwable $exception) {
49 1
            $this->log(LogLevel::ERROR, 'Command failed', compact('command', 'exception'));
50 2
        } finally {
51 2
            $this->implementation->getQueueDriver()
52 2
                ->completeCommand($received->getQueueName(), $received->getId());
53
        }
54 2
    }
55
56 2
    private function log(string $level, string $message, array $context)
57
    {
58 2
        if ($this->logger !== null) {
59 2
            $this->logger->log($level, $message, $context);
60
        }
61 2
    }
62
}
63