1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Silviooosilva\CacheerPhp\CacheStore\CacheManager; |
4
|
|
|
|
5
|
|
|
use Silviooosilva\CacheerPhp\Helpers\CacheFileHelper; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Class FileCacheFlusher |
9
|
|
|
* @author Sílvio Silva <https://github.com/silviooosilva> |
10
|
|
|
* @package Silviooosilva\CacheerPhp |
11
|
|
|
*/ |
12
|
|
|
class FileCacheFlusher |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var FileCacheManager |
16
|
|
|
*/ |
17
|
|
|
private FileCacheManager $fileManager; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var string $cacheDir |
21
|
|
|
*/ |
22
|
|
|
private string $cacheDir; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var string $lastFlushTimeFile |
26
|
|
|
*/ |
27
|
|
|
private string $lastFlushTimeFile; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* FileCacheFlusher constructor. |
31
|
|
|
* |
32
|
|
|
* @param FileCacheManager $fileManager |
33
|
|
|
* @param string $cacheDir |
34
|
|
|
*/ |
35
|
|
|
public function __construct(FileCacheManager $fileManager, string $cacheDir) |
36
|
|
|
{ |
37
|
|
|
$this->fileManager = $fileManager; |
38
|
|
|
$this->cacheDir = $cacheDir; |
39
|
|
|
$this->lastFlushTimeFile = "$cacheDir/last_flush_time"; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Flushes all cache items and updates the last flush timestamp. |
44
|
|
|
* |
45
|
|
|
* @return void |
46
|
|
|
*/ |
47
|
|
|
public function flushCache() |
48
|
|
|
{ |
49
|
|
|
$this->fileManager->clearDirectory($this->cacheDir); |
50
|
|
|
file_put_contents($this->lastFlushTimeFile, time()); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Handles the auto-flush functionality based on options. |
55
|
|
|
* |
56
|
|
|
* @param array $options |
57
|
|
|
* @return void |
58
|
|
|
*/ |
59
|
|
|
public function handleAutoFlush(array $options) |
60
|
|
|
{ |
61
|
|
|
if (isset($options['flushAfter'])) { |
62
|
|
|
$this->scheduleFlush($options['flushAfter']); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Schedules a flush operation based on the provided interval. |
68
|
|
|
* |
69
|
|
|
* @param string $flushAfter |
70
|
|
|
* @return void |
71
|
|
|
*/ |
72
|
|
|
private function scheduleFlush(string $flushAfter) |
73
|
|
|
{ |
74
|
|
|
$flushAfterSeconds = CacheFileHelper::convertExpirationToSeconds($flushAfter); |
75
|
|
|
|
76
|
|
|
if (!$this->fileManager->fileExists($this->lastFlushTimeFile)) { |
77
|
|
|
$this->fileManager->writeFile($this->lastFlushTimeFile, time()); |
78
|
|
|
return; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
$lastFlushTime = (int) $this->fileManager->readFile($this->lastFlushTimeFile); |
82
|
|
|
|
83
|
|
|
if ((time() - $lastFlushTime) >= $flushAfterSeconds) { |
84
|
|
|
$this->flushCache(); |
85
|
|
|
$this->fileManager->writeFile($this->lastFlushTimeFile, time()); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|