1 | <?php |
||
9 | class Worker |
||
10 | { |
||
11 | /** |
||
12 | * @var DriverInterface |
||
13 | */ |
||
14 | private $driver; |
||
15 | |||
16 | /** |
||
17 | * @var Queue |
||
18 | */ |
||
19 | private $queue; |
||
20 | |||
21 | /** |
||
22 | * @var Event |
||
23 | */ |
||
24 | private $event; |
||
25 | |||
26 | /** |
||
27 | * @var CommandBus |
||
28 | */ |
||
29 | private $command_bus; |
||
30 | |||
31 | /** |
||
32 | * Will shutdown the worker on the next tick |
||
33 | * |
||
34 | * @var bool |
||
35 | */ |
||
36 | private $shutdown = false; |
||
37 | |||
38 | /** |
||
39 | * Will shutdown the worker when the queue is drained |
||
40 | * |
||
41 | * @var bool |
||
42 | */ |
||
43 | private $drain = false; |
||
44 | |||
45 | 7 | public function __construct( |
|
56 | |||
57 | /** |
||
58 | * Consumes messages off of the queue |
||
59 | * |
||
60 | * @codeCoverageIgnore |
||
61 | * |
||
62 | * @param string $queue |
||
63 | */ |
||
64 | public function consume($queue) |
||
72 | |||
73 | /** |
||
74 | * Handles fetching messages from the queue |
||
75 | * |
||
76 | * @param string $queue |
||
77 | * |
||
78 | * @return bool |
||
79 | */ |
||
80 | 5 | protected function tick($queue) |
|
81 | { |
||
82 | 5 | if ($this->shutdown) { |
|
83 | 1 | $this->event->shutdown(); |
|
84 | 1 | return false; |
|
85 | } |
||
86 | |||
87 | 4 | list($command, $job) = $this->driver->dequeue($queue); |
|
88 | 4 | if (empty($command) && $this->drain) { |
|
89 | 1 | $this->event->drained(); |
|
90 | 1 | return false; |
|
91 | } elseif (empty($command)) { |
||
92 | 1 | return true; |
|
93 | } |
||
94 | |||
95 | try { |
||
96 | 2 | $this->event->acknowledge($command); |
|
97 | 2 | $this->command_bus->handle($command); |
|
98 | 1 | $this->driver->processed($job); |
|
99 | 1 | $this->event->finish($command); |
|
100 | 1 | } catch (Exception $exception) { |
|
101 | 1 | $this->queue->add(sprintf('%s-failed', $queue), $command); |
|
102 | 1 | $this->event->reject($command, $exception); |
|
103 | } |
||
104 | |||
105 | 2 | return true; |
|
106 | } |
||
107 | |||
108 | /** |
||
109 | * Handles binding POSIX signals appropriately |
||
110 | * |
||
111 | * @codeCoverageIgnore |
||
112 | */ |
||
113 | private function bindSignals() |
||
127 | |||
128 | /** |
||
129 | * Set the worker to shutdown on the next tick |
||
130 | */ |
||
131 | 1 | private function shutdown() |
|
135 | |||
136 | /** |
||
137 | * Set the worker to shutdown when the queue is drained |
||
138 | */ |
||
139 | 1 | private function drain() |
|
143 | } |
||
144 |