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

DatabaseBatchWriter   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 34
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A write() 0 15 3
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