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

DatabaseBatchWriter::__construct()   A

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\CacheDatabaseHelper;
6
7
/**
8
 * Handles chunked writes to the database cache store.
9
 */
10
final class DatabaseBatchWriter
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 array $items
25
     * @param string $namespace
26
     * @param callable $putItem Receives ($cacheKey, $cacheData, $namespace)
27
     * @return void
28
     */
29
    public function write(array $items, string $namespace, callable $putItem): void
30
    {
31
        $processedCount = 0;
32
        $itemCount = count($items);
33
34
        while ($processedCount < $itemCount) {
35
            $batchItems = array_slice($items, $processedCount, $this->batchSize);
36
            foreach ($batchItems as $item) {
37
                CacheDatabaseHelper::validateCacheItem($item);
38
                $cacheKey = $item['cacheKey'];
39
                $cacheData = $item['cacheData'];
40
                $mergedData = CacheDatabaseHelper::mergeCacheData($cacheData);
41
                $putItem($cacheKey, $mergedData, $namespace);
42
            }
43
            $processedCount += count($batchItems);
44
        }
45
    }
46
}
47