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

PredisPullCommandQueue   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 2
dl 0
loc 77
ccs 0
cts 18
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A publish() 0 6 1
A pull() 0 21 3
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 PredisPullCommandQueue 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
        return (bool) $this->client->rpush($this->queue_name, [$value]);
66
    }
67
68
    /**
69
     * Pop command from queue. Return NULL if queue is empty.
70
     *
71
     * @return Command|null
72
     */
73
    public function pull()
74
    {
75
        $value = $this->client->lpop($this->queue_name);
76
77
        if (!$value) {
78
            return null;
79
        }
80
81
        try {
82
            return $this->serializer->deserialize($value);
83
        } catch (\Exception $e) {
84
            // it's a critical error
85
            // it is necessary to react quickly to it
86
            $this->logger->critical('Failed denormalize a command in the Redis queue', [$value, $e->getMessage()]);
87
88
            // try denormalize in later
89
            $this->client->rpush($this->queue_name, [$value]);
90
91
            return null;
92
        }
93
    }
94
}
95