Completed
Push — master ( 987339...3717b7 )
by Mike
02:45
created

QueueWorker::log()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 9.4285
c 1
b 0
f 0
cc 2
eloc 3
nc 2
nop 3
crap 2
1
<?php
2
3
namespace MGDigital\BusQue;
4
5
use MGDigital\BusQue\Exception\TimeoutException;
6
use Psr\Log\LogLevel;
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 2
            $this->iterate($queueName, $time);
23 2
            $n === null || $n--;
24 2
            if ($time !== null && (time() - $stopwatchStart >= $time)) {
25
                break;
26
            }
27
        }
28 2
    }
29
30 2
    private function iterate(string $queueName, int $time = null)
31
    {
32
        try {
33 2
            $received = $this->implementation->getQueueDriver()
34 2
                ->awaitCommand($queueName, $time);
35
        } catch (TimeoutException $e) {
36
            return;
37
        }
38 2
        $command = $this->implementation->getCommandSerializer()
39 2
            ->unserialize($received->getSerialized());
40 2
        $this->implementation->getLogger()->debug('Command received', compact('command'));
41
        try {
42 2
            $this->implementation->getCommandBusAdapter()
43 2
                ->handle($command, true);
44 2
            $this->implementation->getLogger()->info('Command handled', compact('command'));
45 1
        } catch (\Throwable $exception) {
46 1
            $this->implementation->getLogger()->error('Command failed', compact('command', 'exception'));
47 2
        } finally {
48 2
            $this->implementation->getQueueDriver()
49 2
                ->completeCommand($received->getQueueName(), $received->getId());
50
        }
51 2
    }
52
}
53