Passed
Push — master ( d4f709...8319cd )
by Mike
07:40 queued 01:16
created

QueueWorker::work()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 6.0702

Importance

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