Completed
Push — master ( 3717b7...9044e9 )
by Mike
02:46
created

QueueWorker   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 82.35%

Importance

Changes 6
Bugs 0 Features 1
Metric Value
wmc 11
c 6
b 0
f 1
lcom 1
cbo 7
dl 0
loc 51
ccs 28
cts 34
cp 0.8235
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B work() 0 18 8
A iterate() 0 21 2
1
<?php
2
3
namespace MGDigital\BusQue;
4
5
use MGDigital\BusQue\Exception\DriverException;
6
use MGDigital\BusQue\Exception\TimeoutException;
7
8
class QueueWorker
9
{
10
11
    private $implementation;
12
13 3
    public function __construct(Implementation $implementation)
14
    {
15 3
        $this->implementation = $implementation;
16 3
    }
17
18 2
    public function work(string $queueName, int $n = null, int $time = null)
19
    {
20 2
        $stopwatchStart = time();
21 2
        while ($n === null || $n > 0) {
22
            try {
23 2
                $this->iterate($queueName, $time);
24 2
                $n === null || $n--;
25
            } catch (DriverException $exception) {
26
                $this->implementation->getLogger()
27
                    ->error($exception->getMessage(), compact('exception'));
28
            } catch (TimeoutException $e) {
29
                break;
30
            }
31 2
            if ($time !== null && (time() - $stopwatchStart >= $time)) {
32
                break;
33
            }
34
        }
35 2
    }
36
37 2
    private function iterate(string $queueName, int $time = null)
38
    {
39 2
        $received = $this->implementation->getQueueDriver()
40 2
            ->awaitCommand($queueName, $time);
41 2
        $command = $this->implementation->getCommandSerializer()
42 2
            ->unserialize($received->getSerialized());
43 2
        $this->implementation->getLogger()
44 2
            ->debug('Command received', compact('command'));
45
        try {
46 2
            $this->implementation->getCommandBusAdapter()
47 2
                ->handle($command, true);
48 2
            $this->implementation->getLogger()
49 2
                ->info('Command handled', compact('command'));
50 1
        } catch (\Throwable $exception) {
51 1
            $this->implementation->getLogger()
52 1
                ->error('Command failed', compact('command', 'exception'));
53 2
        } finally {
54 2
            $this->implementation->getQueueDriver()
55 2
                ->completeCommand($received->getQueueName(), $received->getId());
56
        }
57 2
    }
58
}
59