SimpleCircularQueue::queueKey()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
/**
3
 * Created by solly [30.10.17 22:05]
4
 */
5
6
namespace insolita\cqueue;
7
8
use function array_map;
9
use insolita\cqueue\Contracts\EmptyQueueBehaviorInterface;
10
use insolita\cqueue\Contracts\PayloadConverterInterface;
11
use insolita\cqueue\Contracts\QueueInterface;
12
use insolita\cqueue\Contracts\StorageInterface;
13
14
class SimpleCircularQueue implements QueueInterface
15
{
16
    /**
17
     * @var string
18
     */
19
    protected $name;
20
    
21
    /**
22
     * @var \insolita\cqueue\Contracts\PayloadConverterInterface
23
     */
24
    protected $converter;
25
    
26
    /**
27
     * @var \insolita\cqueue\Contracts\EmptyQueueBehaviorInterface
28
     */
29
    protected $emptyQueueBehavior;
30
    
31
    /**
32
     * @var \insolita\cqueue\Contracts\StorageInterface
33
     */
34
    protected $storage;
35
    
36
    public function __construct(
37
        string $name,
38
        PayloadConverterInterface $converter,
39
        EmptyQueueBehaviorInterface $emptyQueueBehavior,
40
        StorageInterface $redis
41
    ) {
42
        $this->name = $name;
43
        $this->converter = $converter;
44
        $this->emptyQueueBehavior = $emptyQueueBehavior;
45
        $this->storage = $redis;
46
    }
47
    
48
    public function getName(): string
49
    {
50
        return $this->name;
51
    }
52
    
53
    public function fill(array $data)
54
    {
55
        $identities = array_map([$this->converter, 'toIdentity'], $data);
56
        $this->storage->listPush($this->queueKey(), $identities);
57
    }
58
    
59
    public function purgeQueued()
60
    {
61
        $this->storage->delete($this->queueKey());
62
    }
63
    
64
    public function countQueued(): int
65
    {
66
        return $this->storage->listCount($this->queueKey());
67
    }
68
    
69
    public function listQueued($converted = false): array
70
    {
71
        $list = $this->storage->listItems($this->queueKey());
72
        if ($converted === false || empty($list)) {
73
            return $list;
74
        } else {
75
            return array_map([$this->converter, 'toPayload'], $list);
76
        }
77
    }
78
    
79
    public function next()
80
    {
81
        $item = $this->storage->listPop($this->queueKey());
82
        if (!$item) {
83
            return $this->emptyQueueBehavior->resolve($this);
84
        } else {
85
            $this->storage->listPush($this->queueKey(), [$item]);
86
            return $this->converter->toPayload($item);
87
        }
88
    }
89
    
90
    protected function queueKey(): string
91
    {
92
        return $this->getName() . ':Queue';
93
    }
94
}
95