Completed
Pull Request — master (#10)
by Adam
02:42
created

Worker::consume()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
cc 2
eloc 2
nc 2
nop 1
crap 6
1
<?php
2
3
namespace Equip\Queue;
4
5
use Equip\Queue\Driver\DriverInterface;
6
use Exception;
7
use League\Tactician\CommandBus;
8
9
class Worker
10
{
11
    /**
12
     * @var DriverInterface
13
     */
14
    private $driver;
15
16
    /**
17
     * @var Event
18
     */
19
    private $event;
20
21
    /**
22
     * @var CommandBus
23
     */
24
    private $command_bus;
25
26 3
    public function __construct(
27
        DriverInterface $driver,
28
        Event $event,
29
        CommandBus $command_bus
30
    ) {
31 3
        $this->driver = $driver;
32 3
        $this->event = $event;
33 3
        $this->command_bus = $command_bus;
34 3
    }
35
36
    /**
37
     * Consumes messages off of the queue
38
     *
39
     * @param string $queue
40
     */
41
    public function consume($queue)
42
    {
43
        while ($this->tick($queue)) { /* NOOP */ }
44
    }
45
46
    /**
47
     * Handles fetching messages from the queue
48
     *
49
     * @param string $queue
50
     *
51
     * @return bool
52
     */
53 3
    protected function tick($queue)
54
    {
55 3
        $message = $this->driver->dequeue($queue);
56 3
        if (empty($message)) {
57 1
            return true;
58
        }
59
60 2
        $command = unserialize($message);
61
        try {
62 2
            $this->event->acknowledge($command);
63 2
            $this->command_bus->handle($command);
64 1
            $this->event->finish($command);
65 2
        } catch (Exception $exception) {
66 1
            $this->event->reject($command, $exception);
67
        }
68
69 2
        return true;
70
    }
71
}
72