Completed
Pull Request — master (#2)
by lee
06:59
created

PredisUniquePullCommandQueue::publish()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 0
cts 4
cp 0
rs 9.9666
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
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\Pull;
12
13
use GpsLab\Component\Command\Command;
14
use GpsLab\Component\Command\Queue\Serializer\Serializer;
15
use Predis\Client;
16
use Psr\Log\LoggerInterface;
17
18
class PredisUniquePullCommandQueue implements PullCommandQueue
19
{
20
    /**
21
     * @var Client
22
     */
23
    private $client;
24
25
    /**
26
     * @var Serializer
27
     */
28
    private $serializer;
29
30
    /**
31
     * @var LoggerInterface
32
     */
33
    private $logger;
34
35
    /**
36
     * @var string
37
     */
38
    private $queue_name = '';
39
40
    /**
41
     * @param Client          $client
42
     * @param Serializer      $serializer
43
     * @param LoggerInterface $logger
44
     * @param string          $queue_name
45
     */
46
    public function __construct(Client $client, Serializer $serializer, LoggerInterface $logger, $queue_name)
47
    {
48
        $this->client = $client;
49
        $this->serializer = $serializer;
50
        $this->logger = $logger;
51
        $this->queue_name = $queue_name;
52
    }
53
54
    /**
55
     * Publish command to queue.
56
     *
57
     * @param Command $command
58
     *
59
     * @return bool
60
     */
61
    public function publish(Command $command)
62
    {
63
        $value = $this->serializer->serialize($command);
64
65
        // remove exists command and publish it again
66
        $this->client->lrem($this->queue_name, 0, $value);
67
68
        return (bool) $this->client->rpush($this->queue_name, [$value]);
69
    }
70
71
    /**
72
     * Pop command from queue. Return NULL if queue is empty.
73
     *
74
     * @return Command|null
75
     */
76
    public function pull()
77
    {
78
        $value = $this->client->lpop($this->queue_name);
79
80
        if (!$value) {
81
            return null;
82
        }
83
84
        try {
85
            return $this->serializer->deserialize($value);
86
        } catch (\Exception $e) {
87
            // it's a critical error
88
            // it is necessary to react quickly to it
89
            $this->logger->critical('Failed denormalize a command in the Redis queue', [$value, $e->getMessage()]);
90
91
            // try denormalize in later
92
            $this->client->rpush($this->queue_name, [$value]);
93
94
            return null;
95
        }
96
    }
97
}
98