Completed
Pull Request — master (#9)
by Adam
05:57
created

Worker::jobStart()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 2
Metric Value
c 2
b 0
f 2
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Equip\Queue;
4
5
use Equip\Command\OptionsInterface;
6
use Equip\Queue\Driver\DriverInterface;
7
use Equip\Queue\Command\CommandFactoryInterface;
8
use Exception;
9
10
class Worker
11
{
12
    /**
13
     * @var DriverInterface
14
     */
15
    private $driver;
16
17
    /**
18
     * @var Event
19
     */
20
    private $event;
21
22
    /**
23
     * @var CommandFactoryInterface
24
     */
25
    private $commands;
26
27
    /**
28
     * @param DriverInterface $driver
29
     * @param Event $event
30
     * @param CommandFactoryInterface $commands
31
     */
32 6
    public function __construct(
33
        DriverInterface $driver,
34
        Event $event,
35
        CommandFactoryInterface $commands
36
    ) {
37 6
        $this->driver = $driver;
38 6
        $this->event = $event;
39 6
        $this->commands = $commands;
40 6
    }
41
42
    /**
43
     * Consumes messages off of the queue
44
     *
45
     * @param string $queue
46
     */
47 1
    public function consume($queue)
48
    {
49 1
        while ($this->tick($queue)) { /* NOOP */ }
50 1
    }
51
52
    /**
53
     * Handles fetching messages from the queue
54
     *
55
     * @param string $queue
56
     *
57
     * @return bool
58
     */
59 5
    protected function tick($queue)
60
    {
61 5
        $packet = $this->driver->dequeue($queue);
62 5
        if (empty($packet)) {
63 1
            return true;
64
        }
65
66
        try {
67 4
            list($command, $options) = array_values(unserialize($packet));
68
69 4
            if ($this->invoke($command, $options) === false) {
70 2
                $this->event->shutdown($command);
71 2
                return false;
72
            }
73 2
        } catch (Exception $exception) {
74 1
            $this->event->reject($command, $options, $exception);
75
        }
76
77 2
        return true;
78
    }
79
80
    /**
81
     * Invoke the command with the options
82
     *
83
     * @param string $command
84
     * @param OptionsInterface $options
85
     *
86
     * @return mixed
87
     */
88 5
    private function invoke($command, OptionsInterface $options)
89
    {
90 5
        $this->event->acknowledge($command, $options);
91
92 5
        $result = $this->commands
93 5
            ->make($command)
94 5
            ->withOptions($options)
95 5
            ->execute();
96
97 4
        $this->event->finish($command, $options);
98
99 4
        return $result;
100
    }
101
}
102