Completed
Push — master ( f61059...fbff81 )
by Peter
05:40
created

PredisCommandQueue::push()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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