|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Silviooosilva\CacheerPhp\CacheStore\CacheManager; |
|
4
|
|
|
|
|
5
|
|
|
use Silviooosilva\CacheerPhp\Helpers\CacheFileHelper; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Class GenericFlusher |
|
9
|
|
|
* Lightweight flusher that stores last flush timestamp in a file and invokes a provided callback. |
|
10
|
|
|
*/ |
|
11
|
|
|
class GenericFlusher |
|
12
|
|
|
{ |
|
13
|
|
|
/** @var string */ |
|
14
|
|
|
private string $lastFlushTimeFile; |
|
15
|
|
|
|
|
16
|
|
|
/** @var callable */ |
|
17
|
|
|
private $flushCallback; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @param string $lastFlushTimeFile |
|
21
|
|
|
* @param callable $flushCallback Callback that performs the actual flush |
|
22
|
|
|
*/ |
|
23
|
|
|
public function __construct(string $lastFlushTimeFile, callable $flushCallback) |
|
24
|
|
|
{ |
|
25
|
|
|
$this->lastFlushTimeFile = $lastFlushTimeFile; |
|
26
|
|
|
$this->flushCallback = $flushCallback; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* Performs a flush and records the time. |
|
31
|
|
|
* @return void |
|
32
|
|
|
*/ |
|
33
|
|
|
public function flushCache(): void |
|
34
|
|
|
{ |
|
35
|
|
|
($this->flushCallback)(); |
|
36
|
|
|
@file_put_contents($this->lastFlushTimeFile, (string) time()); |
|
|
|
|
|
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* Handles auto-flush if 'flushAfter' is present in options. |
|
41
|
|
|
* @param array $options |
|
42
|
|
|
* @return void |
|
43
|
|
|
*/ |
|
44
|
|
|
public function handleAutoFlush(array $options): void |
|
45
|
|
|
{ |
|
46
|
|
|
if (!isset($options['flushAfter'])) { |
|
47
|
|
|
return; |
|
48
|
|
|
} |
|
49
|
|
|
$this->scheduleFlush((string) $options['flushAfter']); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* @param string $flushAfter |
|
54
|
|
|
* @return void |
|
55
|
|
|
*/ |
|
56
|
|
|
private function scheduleFlush(string $flushAfter): void |
|
57
|
|
|
{ |
|
58
|
|
|
$flushAfterSeconds = (int) CacheFileHelper::convertExpirationToSeconds($flushAfter); |
|
59
|
|
|
|
|
60
|
|
|
if (!file_exists($this->lastFlushTimeFile)) { |
|
61
|
|
|
@file_put_contents($this->lastFlushTimeFile, (string) time()); |
|
|
|
|
|
|
62
|
|
|
return; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
$lastFlushTime = (int) @file_get_contents($this->lastFlushTimeFile); |
|
66
|
|
|
|
|
67
|
|
|
if ((time() - $lastFlushTime) >= $flushAfterSeconds) { |
|
68
|
|
|
$this->flushCache(); |
|
69
|
|
|
@file_put_contents($this->lastFlushTimeFile, (string) time()); |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
|
If you suppress an error, we recommend checking for the error condition explicitly: