|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace MGDigital\BusQue; |
|
4
|
|
|
|
|
5
|
|
|
use MGDigital\BusQue\Exception\TimeoutException; |
|
6
|
|
|
use Psr\Log\LoggerInterface; |
|
7
|
|
|
use Psr\Log\LogLevel; |
|
8
|
|
|
|
|
9
|
|
|
class QueueWorker |
|
10
|
|
|
{ |
|
11
|
|
|
|
|
12
|
|
|
private $implementation; |
|
13
|
|
|
private $logger; |
|
14
|
|
|
|
|
15
|
3 |
|
public function __construct(Implementation $implementation, LoggerInterface $logger = null) |
|
16
|
|
|
{ |
|
17
|
3 |
|
$this->implementation = $implementation; |
|
18
|
3 |
|
$this->logger = $logger; |
|
19
|
3 |
|
} |
|
20
|
|
|
|
|
21
|
2 |
|
public function work(string $queueName, int $n = null, int $time = null) |
|
22
|
|
|
{ |
|
23
|
2 |
|
$stopwatchStart = time(); |
|
24
|
2 |
|
while ($n === null || $n > 0) { |
|
25
|
2 |
|
$this->iterate($queueName, $time); |
|
26
|
2 |
|
$n === null || $n--; |
|
27
|
2 |
|
if ($time !== null && (time() - $stopwatchStart >= $time)) { |
|
28
|
|
|
break; |
|
29
|
|
|
} |
|
30
|
|
|
} |
|
31
|
2 |
|
} |
|
32
|
|
|
|
|
33
|
2 |
|
private function iterate(string $queueName, int $time = null) |
|
34
|
|
|
{ |
|
35
|
|
|
try { |
|
36
|
2 |
|
$received = $this->implementation->getQueueDriver() |
|
37
|
2 |
|
->awaitCommand($queueName, $time); |
|
38
|
|
|
} catch (TimeoutException $e) { |
|
39
|
|
|
return; |
|
40
|
|
|
} |
|
41
|
2 |
|
$command = $this->implementation->getCommandSerializer() |
|
42
|
2 |
|
->unserialize($received->getSerialized()); |
|
43
|
2 |
|
$this->log(LogLevel::DEBUG, 'Command received', compact('command')); |
|
44
|
|
|
try { |
|
45
|
2 |
|
$this->implementation->getCommandBusAdapter() |
|
46
|
2 |
|
->handle($command, true); |
|
47
|
2 |
|
$this->log(LogLevel::INFO, 'Command handled', compact('command')); |
|
48
|
1 |
|
} catch (\Throwable $exception) { |
|
49
|
1 |
|
$this->log(LogLevel::ERROR, 'Command failed', compact('command', 'exception')); |
|
50
|
2 |
|
} finally { |
|
51
|
2 |
|
$this->implementation->getQueueDriver() |
|
52
|
2 |
|
->completeCommand($received->getQueueName(), $received->getId()); |
|
53
|
|
|
} |
|
54
|
2 |
|
} |
|
55
|
|
|
|
|
56
|
2 |
|
private function log(string $level, string $message, array $context) |
|
57
|
|
|
{ |
|
58
|
2 |
|
if ($this->logger !== null) { |
|
59
|
2 |
|
$this->logger->log($level, $message, $context); |
|
60
|
|
|
} |
|
61
|
2 |
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|