1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* GpsLab component. |
5
|
|
|
* |
6
|
|
|
* @author Peter Gribanov <[email protected]> |
7
|
|
|
* @copyright Copyright (c) 2011, Peter Gribanov |
8
|
|
|
* @license http://opensource.org/licenses/MIT |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace GpsLab\Component\Command\Queue; |
12
|
|
|
|
13
|
|
|
use GpsLab\Component\Command\Command; |
14
|
|
|
use Predis\Client; |
15
|
|
|
use Psr\Log\LoggerInterface; |
16
|
|
|
use Symfony\Component\Serializer\Serializer; |
17
|
|
|
|
18
|
|
|
class PredisCommandQueue implements CommandQueue |
19
|
|
|
{ |
20
|
|
|
const LIST_KEY = 'commands'; |
21
|
|
|
const FORMAT = 'predis'; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var Client |
25
|
|
|
*/ |
26
|
|
|
private $client; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @var Serializer |
30
|
|
|
*/ |
31
|
|
|
private $serializer; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @var LoggerInterface |
35
|
|
|
*/ |
36
|
|
|
private $logger; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @param Client $client |
40
|
|
|
* @param Serializer $serializer |
41
|
|
|
* @param LoggerInterface $logger |
42
|
|
|
*/ |
43
|
|
|
public function __construct(Client $client, Serializer $serializer, LoggerInterface $logger) |
44
|
|
|
{ |
45
|
|
|
$this->client = $client; |
46
|
|
|
$this->serializer = $serializer; |
47
|
|
|
$this->logger = $logger; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Push command to queue. |
52
|
|
|
* |
53
|
|
|
* @param Command $command |
54
|
|
|
* |
55
|
|
|
* @return bool |
56
|
|
|
*/ |
57
|
|
|
public function push(Command $command) |
58
|
|
|
{ |
59
|
|
|
$value = $this->serializer->normalize($command, self::FORMAT); |
60
|
|
|
|
61
|
|
|
return (bool) $this->client->rpush(self::LIST_KEY, [$value]); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* Pop command from queue. Return NULL if queue is empty. |
66
|
|
|
* |
67
|
|
|
* @return Command|null |
68
|
|
|
*/ |
69
|
|
View Code Duplication |
public function pop() |
|
|
|
|
70
|
|
|
{ |
71
|
|
|
$value = $this->client->lpop(self::LIST_KEY); |
72
|
|
|
|
73
|
|
|
if (!$value) { |
74
|
|
|
return null; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
try { |
78
|
|
|
return $this->serializer->denormalize($value, Command::class, self::FORMAT); |
79
|
|
|
} catch (\Exception $e) { |
80
|
|
|
// it's a critical error |
81
|
|
|
// it is necessary to react quickly to it |
82
|
|
|
$this->logger->critical('Failed denormalize a command in the Redis queue', [$value, $e->getMessage()]); |
83
|
|
|
|
84
|
|
|
// try denormalize in later |
85
|
|
|
$this->client->rpush(self::LIST_KEY, [$value]); |
86
|
|
|
|
87
|
|
|
return null; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.