1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Resourceful\Stores; |
4
|
|
|
|
5
|
|
|
use Doctrine\Common\Cache\Cache; |
6
|
|
|
use Symfony\Component\Filesystem\Exception\IOException; |
7
|
|
|
use Symfony\Component\Filesystem\Filesystem; |
8
|
|
|
|
9
|
|
|
class FileCache implements Cache |
10
|
|
|
{ |
11
|
|
|
protected $filesystem; |
12
|
|
|
protected $location; |
13
|
|
|
|
14
|
6 |
|
public function __construct($location) |
15
|
|
|
{ |
16
|
6 |
|
$this->filesystem = new Filesystem(); |
17
|
6 |
|
$this->location = $location; |
18
|
|
|
|
19
|
6 |
|
if (!$this->filesystem->exists($this->location)) { |
20
|
6 |
|
$this->filesystem->mkdir($this->location); |
21
|
|
|
} |
22
|
6 |
|
} |
23
|
|
|
|
24
|
4 |
|
public function fetch($id) |
25
|
|
|
{ |
26
|
4 |
|
if (!$this->contains($id)) { |
27
|
2 |
|
return false; |
28
|
|
|
} |
29
|
|
|
|
30
|
2 |
|
$json = file_get_contents($this->filename($id)); |
31
|
2 |
|
if ($json === false) { |
32
|
|
|
return false; |
33
|
|
|
} |
34
|
|
|
|
35
|
2 |
|
$data = json_decode($json); |
36
|
2 |
|
if ($data === null && json_last_error() !== JSON_ERROR_NONE) { |
37
|
|
|
return false; |
38
|
|
|
} |
39
|
|
|
|
40
|
2 |
|
return $data; |
41
|
|
|
} |
42
|
|
|
|
43
|
4 |
|
public function contains($id) |
44
|
|
|
{ |
45
|
4 |
|
return $this->filesystem->exists($this->filename($id)); |
46
|
|
|
} |
47
|
|
|
|
48
|
3 |
|
public function save($id, $data, $lifeTime = null) |
49
|
|
|
{ |
50
|
3 |
|
$json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); |
51
|
3 |
|
if ($json === false) { |
52
|
|
|
return false; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
try { |
56
|
3 |
|
$this->filesystem->dumpFile($this->filename($id), $json); |
57
|
|
|
} catch (IOException $ioe) { |
58
|
|
|
return false; |
59
|
|
|
} |
60
|
|
|
|
61
|
3 |
|
return true; |
62
|
|
|
} |
63
|
|
|
|
64
|
2 |
|
public function delete($id) |
65
|
|
|
{ |
66
|
|
|
try { |
67
|
2 |
|
$this->filesystem->remove($this->filename($id)); |
68
|
|
|
} catch (IOException $ioe) { |
69
|
|
|
return false; |
70
|
|
|
} |
71
|
|
|
|
72
|
2 |
|
return true; |
73
|
|
|
} |
74
|
|
|
|
75
|
1 |
|
public function getStats() |
76
|
|
|
{ |
77
|
1 |
|
return null; |
78
|
|
|
} |
79
|
|
|
|
80
|
5 |
|
protected function filename($id) |
81
|
|
|
{ |
82
|
5 |
|
if (is_dir("$this->location/$id")) { |
83
|
|
|
$id .= "index"; |
84
|
|
|
} |
85
|
|
|
|
86
|
5 |
|
return "$this->location/$id.json"; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|