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