Passed
Branch main (6fd149)
by Sílvio
02:57
created

ArrayCacheBatchWriter::write()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
c 1
b 0
f 0
nc 4
nop 3
dl 0
loc 14
rs 9.9666
1
<?php
2
3
namespace Silviooosilva\CacheerPhp\CacheStore\Support;
4
5
/**
6
 * Handles chunked writes to the array store.
7
 */
8
final class ArrayCacheBatchWriter
9
{
10
    /** @var int */
11
    private int $batchSize;
12
13
    /**
14
     * @param int $batchSize
15
     */
16
    public function __construct(int $batchSize = 100)
17
    {
18
        $this->batchSize = $batchSize;
19
    }
20
21
    /**
22
     * @param array $items
23
     * @param string $namespace
24
     * @param callable $putItem Receives ($cacheKey, $cacheData, $namespace)
25
     * @return void
26
     */
27
    public function write(array $items, string $namespace, callable $putItem): void
28
    {
29
        $processedCount = 0;
30
        $itemCount = count($items);
31
32
        while ($processedCount < $itemCount) {
33
            $batchItems = array_slice($items, $processedCount, $this->batchSize);
34
            foreach ($batchItems as $item) {
35
                if (!isset($item['cacheKey'], $item['cacheData'])) {
36
                    continue;
37
                }
38
                $putItem($item['cacheKey'], $item['cacheData'], $namespace);
39
            }
40
            $processedCount += count($batchItems);
41
        }
42
    }
43
}
44