|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace JDesrosiers\Resourceful\FileCache; |
|
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
|
|
|
private $filesystem; |
|
12
|
|
|
private $location; |
|
13
|
|
|
|
|
14
|
16 |
|
public function __construct($location) |
|
15
|
|
|
{ |
|
16
|
16 |
|
$this->filesystem = new Filesystem(); |
|
17
|
16 |
|
$this->location = $location; |
|
18
|
|
|
|
|
19
|
16 |
|
if (!$this->filesystem->exists($this->location)) { |
|
20
|
6 |
|
$this->filesystem->mkdir($this->location); |
|
21
|
|
|
} |
|
22
|
16 |
|
} |
|
23
|
|
|
|
|
24
|
14 |
|
public function fetch($id) |
|
25
|
|
|
{ |
|
26
|
14 |
|
if (!$this->contains($id)) { |
|
27
|
2 |
|
return false; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
12 |
|
$json = file_get_contents($this->filename($id)); |
|
31
|
12 |
|
if ($json === false) { |
|
32
|
|
|
return false; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
12 |
|
$data = json_decode($json); |
|
36
|
12 |
|
if ($data === null && json_last_error() !== JSON_ERROR_NONE) { |
|
37
|
|
|
return false; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
12 |
|
return $data; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
14 |
|
public function contains($id) |
|
44
|
|
|
{ |
|
45
|
14 |
|
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
|
15 |
|
protected function filename($id) |
|
81
|
|
|
{ |
|
82
|
15 |
|
if (is_dir("$this->location/$id")) { |
|
83
|
|
|
$id .= "/index"; |
|
84
|
|
|
} |
|
85
|
|
|
|
|
86
|
15 |
|
return "$this->location/$id.json"; |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|