Passed
Pull Request — main (#45)
by Sílvio
03:07
created

FileCacheFlusher::handleAutoFlush()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 4
rs 10
1
<?php
2
3
namespace Silviooosilva\CacheerPhp\CacheStore\CacheManager;
4
5
use Silviooosilva\CacheerPhp\Helpers\CacheFileHelper;
6
7
/**
8
 * Class FileCacheFlusher
9
 * Manages flushing and auto-flush scheduling for file cache.
10
 */
11
class FileCacheFlusher
12
{
13
    private FileCacheManager $fileManager;
14
    private string $cacheDir;
15
    private string $lastFlushTimeFile;
16
17
    public function __construct(FileCacheManager $fileManager, string $cacheDir)
18
    {
19
        $this->fileManager = $fileManager;
20
        $this->cacheDir = $cacheDir;
21
        $this->lastFlushTimeFile = "$cacheDir/last_flush_time";
22
    }
23
24
    /**
25
     * Flushes all cache items and updates the last flush timestamp.
26
     */
27
    public function flushCache(): void
28
    {
29
        $this->fileManager->clearDirectory($this->cacheDir);
30
        file_put_contents($this->lastFlushTimeFile, time());
31
    }
32
33
    /**
34
     * Handles the auto-flush functionality based on options.
35
     */
36
    public function handleAutoFlush(array $options): void
37
    {
38
        if (isset($options['flushAfter'])) {
39
            $this->scheduleFlush($options['flushAfter']);
40
        }
41
    }
42
43
    /**
44
     * Schedules a flush operation based on the provided interval.
45
     */
46
    private function scheduleFlush(string $flushAfter): void
47
    {
48
        $flushAfterSeconds = CacheFileHelper::convertExpirationToSeconds($flushAfter);
49
50
        if (!$this->fileManager->fileExists($this->lastFlushTimeFile)) {
51
            $this->fileManager->writeFile($this->lastFlushTimeFile, time());
52
            return;
53
        }
54
55
        $lastFlushTime = (int) $this->fileManager->readFile($this->lastFlushTimeFile);
56
57
        if ((time() - $lastFlushTime) >= $flushAfterSeconds) {
58
            $this->flushCache();
59
            $this->fileManager->writeFile($this->lastFlushTimeFile, time());
60
        }
61
    }
62
}
63