RedisBatchWriter::__construct()   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
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Silviooosilva\CacheerPhp\CacheStore\Support;
4
5
use Silviooosilva\CacheerPhp\Helpers\CacheRedisHelper;
6
7
/**
8
 * Handles chunked writes to Redis for large batches.
9
 */
10
final class RedisBatchWriter
11
{   
12
    /** @var int */
13
    private int $batchSize;
14
15
    /**
16
     * @param int $batchSize
17
     */
18
    public function __construct(int $batchSize = 100)
19
    {
20
        $this->batchSize = $batchSize;
21
    }
22
23
    /**
24
     * @param callable $putItem
25
     * @param array $items
26
     * @param string $namespace
27
     * 
28
     * @return void
29
     */
30
    public function write(array $items, string $namespace, callable $putItem): void
31
    {
32
        $processedCount = 0;
33
        $itemCount = count($items);
34
35
        while ($processedCount < $itemCount) {
36
            $batchItems = array_slice($items, $processedCount, $this->batchSize);
37
            foreach ($batchItems as $item) {
38
                $this->processItem($item, $namespace, $putItem);
39
            }
40
            $processedCount += count($batchItems);
41
        }
42
    }
43
44
    /**
45
     * @param array $item
46
     * @param string $namespace
47
     * @param callable $putItem
48
     * 
49
     * @return void
50
     */
51
    private function processItem(array $item, string $namespace, callable $putItem): void
52
    {
53
        CacheRedisHelper::validateCacheItem($item);
54
        $cacheKey = $item['cacheKey'];
55
        $cacheData = $item['cacheData'];
56
        $mergedData = CacheRedisHelper::mergeCacheData($cacheData);
57
58
        $putItem($cacheKey, $mergedData, $namespace);
59
    }
60
}
61