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
|
|
|
|