1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Spiral Framework. |
4
|
|
|
* |
5
|
|
|
* @license MIT |
6
|
|
|
* @author Anton Titov (Wolfy-J) |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Spiral\Framework; |
10
|
|
|
|
11
|
|
|
use Spiral\Core\MemoryInterface; |
12
|
|
|
use Spiral\Files\FilesInterface; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* File based memory storage. |
16
|
|
|
*/ |
17
|
|
|
final class Memory implements MemoryInterface |
18
|
|
|
{ |
19
|
|
|
// data file extension |
20
|
|
|
private const EXTENSION = 'php'; |
21
|
|
|
|
22
|
|
|
/** @var string */ |
23
|
|
|
private $directory; |
24
|
|
|
|
25
|
|
|
/** @var FilesInterface */ |
26
|
|
|
private $files = null; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param string $directory |
30
|
|
|
* @param FilesInterface $files |
31
|
|
|
*/ |
32
|
|
|
public function __construct(string $directory, FilesInterface $files) |
33
|
|
|
{ |
34
|
|
|
$this->directory = rtrim($directory, '/'); |
35
|
|
|
$this->files = $files; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* {@inheritdoc} |
40
|
|
|
* |
41
|
|
|
* @param string $filename Cache filename. |
42
|
|
|
*/ |
43
|
|
|
public function loadData(string $section, string &$filename = null) |
44
|
|
|
{ |
45
|
|
|
$filename = $this->getFilename($section); |
46
|
|
|
|
47
|
|
|
if (!file_exists($filename)) { |
48
|
|
|
return null; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
try { |
52
|
|
|
return include($filename); |
53
|
|
|
} catch (\Throwable $e) { |
54
|
|
|
return null; |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* {@inheritdoc} |
60
|
|
|
*/ |
61
|
|
|
public function saveData(string $section, $data) |
62
|
|
|
{ |
63
|
|
|
$this->files->write( |
64
|
|
|
$this->getFilename($section), |
65
|
|
|
'<?php return ' . var_export($data, true) . ';', |
66
|
|
|
FilesInterface::RUNTIME, |
67
|
|
|
true |
68
|
|
|
); |
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
|
|
|
* @return string |
77
|
|
|
*/ |
78
|
|
|
private function getFilename(string $name): string |
79
|
|
|
{ |
80
|
|
|
//Runtime cache |
81
|
|
|
return sprintf( |
82
|
|
|
"%s/%s.%s", |
83
|
|
|
$this->directory, |
84
|
|
|
strtolower(str_replace(['/', '\\'], '-', $name)), |
85
|
|
|
self::EXTENSION |
86
|
|
|
); |
87
|
|
|
} |
88
|
|
|
} |