|
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
|
438 |
|
public function __construct( |
|
20
|
|
|
string $directory, |
|
21
|
|
|
private readonly FilesInterface $files |
|
22
|
|
|
) { |
|
23
|
438 |
|
$this->directory = \rtrim($directory, '/'); |
|
|
|
|
|
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* @param string $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
|
|
|
try { |
|
38
|
4 |
|
$fp = fopen($filename, 'r'); |
|
39
|
4 |
|
if (!flock($fp, LOCK_SH | LOCK_NB)) { |
|
40
|
|
|
return null; |
|
41
|
|
|
} |
|
42
|
4 |
|
$data = include($filename); |
|
43
|
3 |
|
flock($fp, LOCK_UN); |
|
44
|
3 |
|
fclose($fp); |
|
45
|
3 |
|
return $data; |
|
46
|
1 |
|
} catch (\Throwable) { |
|
47
|
1 |
|
return null; |
|
48
|
|
|
} |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
436 |
|
public function saveData(string $section, mixed $data): void |
|
52
|
|
|
{ |
|
53
|
436 |
|
$this->files->write( |
|
54
|
436 |
|
$this->getFilename($section), |
|
55
|
436 |
|
'<?php return ' . \var_export($data, true) . ';', |
|
56
|
436 |
|
FilesInterface::RUNTIME, |
|
57
|
436 |
|
true |
|
58
|
436 |
|
); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* Get extension to use for runtime data or configuration cache. |
|
63
|
|
|
* |
|
64
|
|
|
* @param string $name Runtime data file name (without extension). |
|
65
|
|
|
*/ |
|
66
|
437 |
|
private function getFilename(string $name): string |
|
67
|
|
|
{ |
|
68
|
|
|
//Runtime cache |
|
69
|
437 |
|
return \sprintf( |
|
70
|
437 |
|
'%s/%s.%s', |
|
71
|
437 |
|
$this->directory, |
|
72
|
437 |
|
\strtolower(\str_replace(['/', '\\'], '-', $name)), |
|
73
|
437 |
|
self::EXTENSION |
|
74
|
437 |
|
); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|