1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Spiral\Boot; |
6
|
|
|
|
7
|
|
|
use Spiral\Files\FilesInterface; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* File based memory storage. |
11
|
|
|
*/ |
12
|
|
|
final class Memory implements MemoryInterface |
13
|
|
|
{ |
14
|
|
|
// data file extension |
15
|
|
|
private const EXTENSION = 'php'; |
16
|
|
|
|
17
|
|
|
private readonly string $directory; |
18
|
|
|
|
19
|
437 |
|
public function __construct( |
20
|
|
|
string $directory, |
21
|
|
|
private readonly FilesInterface $files |
22
|
|
|
) { |
23
|
437 |
|
$this->directory = \rtrim($directory, '/'); |
|
|
|
|
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param non-empty-string|null $filename Cache filename. |
|
|
|
|
28
|
|
|
*/ |
29
|
25 |
|
public function loadData(string $section, ?string &$filename = null): mixed |
30
|
|
|
{ |
31
|
25 |
|
$filename = $this->getFilename($section); |
32
|
|
|
|
33
|
25 |
|
if (!\file_exists($filename)) { |
34
|
25 |
|
return null; |
35
|
|
|
} |
36
|
|
|
|
37
|
4 |
|
$fp = false; |
|
|
|
|
38
|
4 |
|
$lock = false; |
39
|
|
|
|
40
|
|
|
try { |
41
|
4 |
|
$fp = \fopen($filename, 'r'); |
42
|
4 |
|
if ($fp === false) { |
43
|
|
|
return null; |
44
|
|
|
} |
45
|
|
|
|
46
|
4 |
|
$lock = \flock($fp, \LOCK_SH | \LOCK_NB); |
47
|
|
|
|
48
|
4 |
|
if ($lock === false) { |
49
|
|
|
return null; |
50
|
|
|
} |
51
|
|
|
|
52
|
4 |
|
return include($filename); |
53
|
1 |
|
} catch (\Throwable) { |
54
|
1 |
|
return null; |
55
|
|
|
} finally { |
56
|
4 |
|
$lock === false or \flock($fp, \LOCK_UN); |
57
|
4 |
|
$fp === false or \fclose($fp); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
61
|
435 |
|
public function saveData(string $section, mixed $data): void |
62
|
|
|
{ |
63
|
435 |
|
$this->files->write( |
64
|
435 |
|
$this->getFilename($section), |
65
|
435 |
|
'<?php return ' . \var_export($data, true) . ';', |
66
|
435 |
|
FilesInterface::RUNTIME, |
67
|
435 |
|
true |
68
|
435 |
|
); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* Get extension to use for runtime data or configuration cache. |
73
|
|
|
* |
74
|
|
|
* @param string $name Runtime data file name (without extension). |
75
|
|
|
*/ |
76
|
436 |
|
private function getFilename(string $name): string |
77
|
|
|
{ |
78
|
|
|
//Runtime cache |
79
|
436 |
|
return \sprintf( |
80
|
436 |
|
'%s/%s.%s', |
81
|
436 |
|
$this->directory, |
82
|
436 |
|
\strtolower(\str_replace(['/', '\\'], '-', $name)), |
83
|
436 |
|
self::EXTENSION |
84
|
436 |
|
); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|