Completed
Push — master ( 38797d...534d41 )
by Nate
03:48
created

Redis::fetchJob()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 12
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 2
nop 0
crap 6
1
<?php
2
3
/**
4
 * @author    Flipbox Factory
5
 * @copyright Copyright (c) 2017, Flipbox Digital
6
 * @link      https://github.com/flipbox/queue/releases/latest
7
 * @license   https://github.com/flipbox/queue/blob/master/LICENSE
8
 */
9
10
namespace flipbox\queue\queues;
11
12
use flipbox\queue\jobs\JobInterface;
13
use yii\di\Instance;
14
use yii\helpers\Json;
15
use yii\redis\Connection;
16
17
/**
18
 * @author Flipbox Factory <[email protected]>
19
 * @since 1.0.0
20
 */
21
class Redis extends AbstractQueue
22
{
23
    /**
24
     * Stores the redis connection.
25
     * @var string|array|Connection
26
     */
27
    public $db = 'redis';
28
29
    /**
30
     * The name of the key to store the queue.
31
     * @var string
32
     */
33
    public $key = 'queue';
34
35
    /**
36
     * @inheritdoc
37
     */
38
    public function init()
39
    {
40
        parent::init();
41
        $this->db = Instance::ensure($this->db, Connection::class);
42
    }
43
44
    /**
45
     * @inheritdoc
46
     */
47
    public function deleteJob(JobInterface $job): bool
48
    {
49
        return true;
50
    }
51
52
    /**
53
     * @inheritdoc
54
     */
55
    protected function fetchJob()
56
    {
57
        $json = $this->db->lpop($this->key);
58
        if ($json == false) {
59
            return false;
60
        }
61
        $data = Json::decode($json);
62
        $job = $this->deserialize($data['data']);
63
        $job->setId($data['id']);
64
        $job->setHeader('serialized', $data['data']);
65
        return $job;
66
    }
67
68
    /**
69
     * @inheritdoc
70
     */
71
    protected function postJob(JobInterface $job): bool
72
    {
73
        return $this->db->rpush($this->key, Json::encode([
74
            'id' => uniqid('queue_', true),
75
            'data' => $this->serialize($job),
76
        ]));
77
    }
78
79
    /**
80
     * @inheritdoc
81
     */
82
    protected function releaseJob(JobInterface $job): bool
83
    {
84
        return $this->db->rpush(
85
            $this->key,
86
            Json::encode([
87
                'id' => $job->getId(),
88
                'data' => $job->getHeader('serialized')
89
            ])
90
        );
91
    }
92
93
    /**
94
     * @inheritdoc
95
     */
96
    public function getSize(): int
97
    {
98
        return $this->db->llen($this->key);
99
    }
100
101
    /**
102
     * @inheritdoc
103
     */
104
    public function purge(): bool
105
    {
106
        return $this->db->del($this->key);
107
    }
108
}
109