Completed
Push — master ( 1fd03a...66da5b )
by Peter
03:41
created

PredisUniqueEventQueue::pop()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 10

Duplication

Lines 21
Ratio 100 %

Code Coverage

Tests 2
CRAP Score 7.2349

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 21
loc 21
ccs 2
cts 9
cp 0.2222
rs 9.3142
cc 3
eloc 10
nc 3
nop 0
crap 7.2349
1
<?php
2
/**
3
 * GpsLab component.
4
 *
5
 * @author    Peter Gribanov <[email protected]>
6
 * @copyright Copyright (c) 2016, Peter Gribanov
7
 * @license   http://opensource.org/licenses/MIT
8
 */
9
10
namespace GpsLab\Domain\Event\Queue;
11
12
use GpsLab\Domain\Event\EventInterface;
13
use Predis\Client;
14
use Psr\Log\LoggerInterface;
15
use Symfony\Component\Serializer\Serializer;
16
17 View Code Duplication
class PredisUniqueEventQueue implements EventQueueInterface
18
{
19
    const LIST_KEY = 'unique_events';
20
    const FORMAT = 'predis';
21
22
    /**
23
     * @var Client
24
     */
25
    private $client;
26
27
    /**
28
     * @var Serializer
29
     */
30
    private $serializer;
31
32
    /**
33
     * @var LoggerInterface
34
     */
35
    private $logger;
36
37
    /**
38
     * @param Client $client
39
     * @param Serializer $serializer
40
     * @param LoggerInterface $logger
41
     */
42 4
    public function __construct(Client $client, Serializer $serializer, LoggerInterface $logger)
43
    {
44 4
        $this->client = $client;
45 4
        $this->serializer = $serializer;
46 4
        $this->logger = $logger;
47 4
    }
48
49
    /**
50
     * Push event to queue.
51
     *
52
     * @param EventInterface $event
53
     *
54
     * @return bool
55
     */
56 1
    public function push(EventInterface $event)
57
    {
58 1
        $value = $this->serializer->normalize($event, self::FORMAT);
59
60
        // remove already exists value to remove duplication
61 1
        $this->client->lrem(self::LIST_KEY, 0, $value);
62
63
        return (bool) $this->client->rpush(self::LIST_KEY, [$value]);
64
    }
65
66
    /**
67
     * Pop event from queue. Return NULL if queue is empty.
68
     *
69
     * @return EventInterface|null
70
     */
71 3
    public function pop()
72
    {
73 3
        $value = $this->client->lpop(self::LIST_KEY);
74
75
        if (!$value) {
76
            return null;
77
        }
78
79
        try {
80
            return $this->serializer->denormalize($value, EventInterface::class, self::FORMAT);
81
        } catch (\Exception $e) {
82
            // it's a critical error
83
            // it is necessary to react quickly to it
84
            $this->logger->critical('Failed denormalize a event in the Redis queue', [$value, $e->getMessage()]);
85
86
            // try denormalize in later
87
            $this->client->rpush(self::LIST_KEY, [$value]);
88
89
            return null;
90
        }
91
    }
92
}
93