1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* GpsLab component. |
4
|
|
|
* |
5
|
|
|
* @author Peter Gribanov <[email protected]> |
6
|
|
|
* @copyright Copyright (c) 2016, Peter Gribanov |
7
|
|
|
* @license http://opensource.org/licenses/MIT |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace GpsLab\Domain\Event\Queue; |
11
|
|
|
|
12
|
|
|
use GpsLab\Domain\Event\EventInterface; |
13
|
|
|
use Predis\Client; |
14
|
|
|
use Psr\Log\LoggerInterface; |
15
|
|
|
use Symfony\Component\Serializer\Serializer; |
16
|
|
|
|
17
|
|
View Code Duplication |
class PredisUniqueEventQueue implements EventQueueInterface |
18
|
|
|
{ |
19
|
|
|
const LIST_KEY = 'unique_events'; |
20
|
|
|
const FORMAT = 'predis'; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var Client |
24
|
|
|
*/ |
25
|
|
|
private $client; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var Serializer |
29
|
|
|
*/ |
30
|
|
|
private $serializer; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @var LoggerInterface |
34
|
|
|
*/ |
35
|
|
|
private $logger; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param Client $client |
39
|
|
|
* @param Serializer $serializer |
40
|
|
|
* @param LoggerInterface $logger |
41
|
|
|
*/ |
42
|
4 |
|
public function __construct(Client $client, Serializer $serializer, LoggerInterface $logger) |
43
|
|
|
{ |
44
|
4 |
|
$this->client = $client; |
45
|
4 |
|
$this->serializer = $serializer; |
46
|
4 |
|
$this->logger = $logger; |
47
|
4 |
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Push event to queue. |
51
|
|
|
* |
52
|
|
|
* @param EventInterface $event |
53
|
|
|
* |
54
|
|
|
* @return bool |
55
|
|
|
*/ |
56
|
1 |
|
public function push(EventInterface $event) |
57
|
|
|
{ |
58
|
1 |
|
$value = $this->serializer->normalize($event, self::FORMAT); |
59
|
|
|
|
60
|
|
|
// remove already exists value to remove duplication |
61
|
1 |
|
$this->client->lrem(self::LIST_KEY, 0, $value); |
62
|
|
|
|
63
|
1 |
|
return (bool) $this->client->rpush(self::LIST_KEY, [$value]); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Pop event from queue. Return NULL if queue is empty. |
68
|
|
|
* |
69
|
|
|
* @return EventInterface|null |
70
|
|
|
*/ |
71
|
3 |
|
public function pop() |
72
|
|
|
{ |
73
|
3 |
|
$value = $this->client->lpop(self::LIST_KEY); |
74
|
|
|
|
75
|
3 |
|
if (!$value) { |
76
|
1 |
|
return null; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
try { |
80
|
2 |
|
return $this->serializer->denormalize($value, EventInterface::class, self::FORMAT); |
81
|
1 |
|
} catch (\Exception $e) { |
82
|
|
|
// it's a critical error |
83
|
|
|
// it is necessary to react quickly to it |
84
|
1 |
|
$this->logger->critical('Failed denormalize a event in the Redis queue', [$value, $e->getMessage()]); |
85
|
|
|
|
86
|
|
|
// try denormalize in later |
87
|
1 |
|
$this->client->rpush(self::LIST_KEY, [$value]); |
88
|
|
|
|
89
|
1 |
|
return null; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|