|
1
|
|
|
<?php |
|
2
|
|
|
namespace Nopolabs\Yabot\Storage; |
|
3
|
|
|
|
|
4
|
|
|
class FileStorage implements StorageInterface |
|
5
|
|
|
{ |
|
6
|
|
|
private $path; |
|
7
|
|
|
private $jsonEncodeOptions; |
|
8
|
|
|
|
|
9
|
|
|
public function __construct($path = '', $jsonEncodeOptions = JSON_PRETTY_PRINT) |
|
10
|
|
|
{ |
|
11
|
|
|
$this->path = $path; |
|
12
|
|
|
$this->jsonEncodeOptions = $jsonEncodeOptions; |
|
13
|
|
|
} |
|
14
|
|
|
|
|
15
|
|
|
protected function getFilename($key) |
|
16
|
|
|
{ |
|
17
|
|
|
return $this->path.DIRECTORY_SEPARATOR.$key.'.json'; |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
|
|
public function save($key, $data) |
|
21
|
|
|
{ |
|
22
|
|
|
$file = $this->getFilename($key); |
|
23
|
|
|
$this->putFile($file, $data); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
public function get($key) |
|
27
|
|
|
{ |
|
28
|
|
|
$file = $this->getFilename($key); |
|
29
|
|
|
return $this->getFile($file); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public function delete($key) |
|
33
|
|
|
{ |
|
34
|
|
|
$file = $this->getFilename($key); |
|
35
|
|
|
if (file_exists($file)) { |
|
36
|
|
|
unlink($file); |
|
37
|
|
|
} |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
public function all() |
|
41
|
|
|
{ |
|
42
|
|
|
$files = glob($this->path.'/*.json'); |
|
43
|
|
|
$data = []; |
|
44
|
|
|
foreach ($files as $file) { |
|
45
|
|
|
$data[] = $this->getFile($file); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
return $data; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
protected function putFile($file, $data) |
|
52
|
|
|
{ |
|
53
|
|
|
if (!is_dir(dirname($file))) { |
|
54
|
|
|
mkdir(dirname($file), 0777, true); |
|
55
|
|
|
} |
|
56
|
|
|
file_put_contents($file, json_encode($data, $this->jsonEncodeOptions)); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
protected function getFile($file) |
|
60
|
|
|
{ |
|
61
|
|
|
if (file_exists($file)) { |
|
62
|
|
|
return json_decode(file_get_contents($file), true); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
return []; |
|
66
|
|
|
} |
|
67
|
|
|
} |