Completed
Push — master ( 2c00e3...367d56 )
by Peter
05:32
created

PredisCommandQueue::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 3
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;
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 LIST_KEY = 'commands';
21
    const FORMAT = 'predis';
22
23
    /**
24
     * @var Client
25
     */
26
    private $client;
27
28
    /**
29
     * @var SerializerInterface
30
     */
31
    private $serializer;
32
33
    /**
34
     * @var LoggerInterface
35
     */
36
    private $logger;
37
38
    /**
39
     * @param Client              $client
40
     * @param SerializerInterface $serializer
41
     * @param LoggerInterface     $logger
42
     */
43 3
    public function __construct(Client $client, SerializerInterface $serializer, LoggerInterface $logger)
44
    {
45 3
        $this->client = $client;
46 3
        $this->serializer = $serializer;
47 3
        $this->logger = $logger;
48 3
    }
49
50
    /**
51
     * Push command to queue.
52
     *
53
     * @param Command $command
54
     *
55
     * @return bool
56
     */
57 1
    public function push(Command $command)
58
    {
59 1
        $value = $this->serializer->serialize($command, self::FORMAT);
60
61 1
        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 2
    public function pop()
70
    {
71 2
        $value = $this->client->lpop(self::LIST_KEY);
72
73 2
        if (!$value) {
74 1
            return null;
75
        }
76
77
        try {
78 2
            return $this->serializer->deserialize($value, Command::class, self::FORMAT);
79 1
        } catch (\Exception $e) {
80
            // it's a critical error
81
            // it is necessary to react quickly to it
82 1
            $this->logger->critical('Failed denormalize a command in the Redis queue', [$value, $e->getMessage()]);
83
84
            // try denormalize in later
85 1
            $this->client->rpush(self::LIST_KEY, [$value]);
86
87 1
            return null;
88
        }
89
    }
90
}
91