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