1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace App\Reuse\Controllers\Api; |
6
|
|
|
|
7
|
|
|
trait TFileCache |
8
|
|
|
{ |
9
|
|
|
|
10
|
|
|
protected $cacheTtl = 60 * 5; |
11
|
|
|
protected $cacheFilename = ''; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* return true if cache is expired |
15
|
|
|
* |
16
|
|
|
* @return boolean |
17
|
|
|
*/ |
18
|
2 |
|
protected function cacheFileExpired(): bool |
19
|
|
|
{ |
20
|
2 |
|
$this->cacheFilename = $this->getCacheFilename(); |
21
|
2 |
|
return (file_exists($this->cacheFilename) === false) |
22
|
2 |
|
? true |
23
|
2 |
|
: filemtime($this->cacheFilename) < (time() - $this->cacheTtl); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* returns cache content |
28
|
|
|
* |
29
|
|
|
* @return string |
30
|
|
|
*/ |
31
|
2 |
|
protected function getFileCache(): string |
32
|
|
|
{ |
33
|
2 |
|
return file_get_contents($this->getCacheFilename()); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* set cache content |
38
|
|
|
* |
39
|
|
|
* @param string $content |
40
|
|
|
* @return integer |
41
|
|
|
*/ |
42
|
3 |
|
protected function setFileCache(string $content): int |
43
|
|
|
{ |
44
|
3 |
|
return file_put_contents( |
45
|
3 |
|
$this->getCacheFilename(), |
46
|
|
|
$content, |
47
|
3 |
|
LOCK_EX |
48
|
|
|
); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* clear cache dir |
53
|
|
|
* |
54
|
|
|
* @param bool $fromRequest |
55
|
|
|
* @return void |
56
|
|
|
*/ |
57
|
2 |
|
protected function clearFileCache(bool $fromRequest = false) |
58
|
|
|
{ |
59
|
2 |
|
if ($fromRequest) { |
60
|
1 |
|
$filename = $this->getCacheFilename(); |
61
|
1 |
|
if (is_writable($filename)) { |
62
|
1 |
|
@unlink($filename); |
|
|
|
|
63
|
|
|
} |
64
|
|
|
} else { |
65
|
2 |
|
$files = glob($this->getFileCachePath() . '*'); |
66
|
2 |
|
$fileList = is_array($files) |
67
|
2 |
|
? array_filter($files, 'is_file') |
68
|
2 |
|
: []; |
69
|
2 |
|
$counter = count($fileList); |
70
|
2 |
|
for ($c = 0; $c < $counter; $c++) { |
71
|
2 |
|
unlink($fileList[$c]); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* returns cache filename from request uri |
78
|
|
|
* |
79
|
|
|
* @return string |
80
|
|
|
*/ |
81
|
2 |
|
protected function getCacheFilename(): string |
82
|
|
|
{ |
83
|
2 |
|
$path = $this->getFileCachePath(); |
84
|
2 |
|
if (!file_exists($path)) { |
85
|
|
|
mkdir($path); |
86
|
|
|
} |
87
|
2 |
|
$filename = md5($this->request->getUri()); |
88
|
2 |
|
return $path . $filename; |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
/** |
92
|
|
|
* returns cache path from request script filename |
93
|
|
|
* |
94
|
|
|
* @return string |
95
|
|
|
*/ |
96
|
2 |
|
protected function getFileCachePath(): string |
97
|
|
|
{ |
98
|
2 |
|
return dirname($this->request->getFilename()) . '/../cache/'; |
99
|
|
|
} |
100
|
|
|
} |
101
|
|
|
|
If you suppress an error, we recommend checking for the error condition explicitly: