Completed
Push — master ( 57f174...41d2b7 )
by Mike
02:38
created

QueueWorker::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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