BulkService   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 57
rs 10
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A keys() 0 3 1
A prefixKey() 0 3 1
A insert() 0 3 1
A writeKey() 0 3 1
A chunkIterator() 0 15 4
1
<?php
2
3
namespace Bavix\Entry\Services;
4
5
use Bavix\Entry\Models\Entry;
6
use Illuminate\Support\Facades\Redis;
7
8
class BulkService
9
{
10
11
    /**
12
     * @param int $batchSize
13
     * @param string $key
14
     * @return \Generator
15
     */
16
    public function chunkIterator(int $batchSize, string $key): \Generator
17
    {
18
        $start = \strpos($key, $this->prefixKey());
19
        if ($start !== false) {
20
            $key = \substr($key, $start);
21
        }
22
23
        do {
24
            $bulk = Redis::lrange($key, 0, \max($batchSize - 1, 0));
25
            $count = \count($bulk);
26
            if ($count) {
27
                yield $bulk;
28
                Redis::ltrim($key, $count, -1);
29
            }
30
        } while ($count >= $batchSize);
31
    }
32
33
    /**
34
     * @return array
35
     */
36
    public function keys(): array
37
    {
38
        return Redis::keys($this->prefixKey() . '*');
39
    }
40
41
    /**
42
     * @param Entry $entry
43
     * @return int
44
     */
45
    public function insert(Entry $entry): int
46
    {
47
        return Redis::rpush($this->writeKey($entry), \json_encode($entry->toArray()));
48
    }
49
50
    /**
51
     * @param Entry $entry
52
     * @return string
53
     */
54
    public function writeKey(Entry $entry): string
55
    {
56
        return $this->prefixKey() . \get_class($entry);
57
    }
58
59
    /**
60
     * @return string
61
     */
62
    protected function prefixKey(): string
63
    {
64
        return 'bavixBulkWrite:';
65
    }
66
67
}
68