1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Silviooosilva\CacheerPhp\CacheStore\CacheManager; |
4
|
|
|
|
5
|
|
|
use RecursiveDirectoryIterator; |
6
|
|
|
use RecursiveIteratorIterator; |
7
|
|
|
use Silviooosilva\CacheerPhp\Exceptions\CacheFileException; |
8
|
|
|
|
9
|
|
|
class FileCacheManager |
10
|
|
|
{ |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* @param string $dir |
14
|
|
|
* @return void |
15
|
|
|
*/ |
16
|
|
|
public function createDirectory(string $dir) |
17
|
|
|
{ |
18
|
|
|
if ((!file_exists($dir) || !is_dir($dir)) && !mkdir($dir, 0777, true)) { |
19
|
|
|
throw CacheFileException::create("Could not create directory: {$dir}"); |
20
|
|
|
} |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param string $filename |
25
|
|
|
* @param string $data |
26
|
|
|
* @return void |
27
|
|
|
*/ |
28
|
|
|
public function writeFile(string $filename, string $data) |
29
|
|
|
{ |
30
|
|
|
if (!@file_put_contents($filename, $data, LOCK_EX)) { |
31
|
|
|
throw CacheFileException::create("Could not write file: {$filename}"); |
32
|
|
|
} |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param string $filename |
37
|
|
|
* @return string |
38
|
|
|
*/ |
39
|
|
|
public function readFile(string $filename) |
40
|
|
|
{ |
41
|
|
|
if (!$this->fileExists($filename)) { |
42
|
|
|
throw CacheFileException::create("File not found: {$filename}"); |
43
|
|
|
} |
44
|
|
|
return file_get_contents($filename); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param string $filename |
49
|
|
|
* @return bool |
50
|
|
|
*/ |
51
|
|
|
public function fileExists(string $filename) |
52
|
|
|
{ |
53
|
|
|
return file_exists($filename); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param string $filename |
58
|
|
|
* @return void |
59
|
|
|
*/ |
60
|
|
|
public function removeFile(string $filename) |
61
|
|
|
{ |
62
|
|
|
if (file_exists($filename)) { |
63
|
|
|
unlink($filename); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @param string $dir |
69
|
|
|
* @return void |
70
|
|
|
*/ |
71
|
|
|
public function clearDirectory(string $dir) |
72
|
|
|
{ |
73
|
|
|
$iterator = new RecursiveIteratorIterator( |
74
|
|
|
new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS), |
75
|
|
|
RecursiveIteratorIterator::CHILD_FIRST |
76
|
|
|
); |
77
|
|
|
foreach ($iterator as $file) { |
78
|
|
|
$path = $file->getPathname(); |
79
|
|
|
$file->isDir() ? rmdir($path) : unlink($path); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* @param mixed $data |
85
|
|
|
* @param bool $serealize |
86
|
|
|
*/ |
87
|
|
|
public function serialize(mixed $data, bool $serealize = true) |
88
|
|
|
{ |
89
|
|
|
if($serealize) { |
90
|
|
|
return serialize($data); |
91
|
|
|
} |
92
|
|
|
return unserialize($data); |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|