Total Complexity | 9 |
Total Lines | 91 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
1 | <?php |
||
13 | final class FileCache implements CacheInterface |
||
14 | { |
||
15 | /** @var string */ |
||
16 | private string $path; |
||
17 | |||
18 | /** @var array */ |
||
19 | private array $values = []; |
||
20 | |||
21 | /** |
||
22 | * FileCache constructor. |
||
23 | * |
||
24 | * @param string $path |
||
25 | */ |
||
26 | 9 | public function __construct(string $path) |
|
27 | { |
||
28 | 9 | $this->path = $path; |
|
29 | |||
30 | 9 | clearstatcache(); |
|
31 | 9 | if (!file_exists($path)) { |
|
32 | 9 | touch($path); |
|
33 | } else { |
||
34 | 1 | $this->values = (array)json_decode(file_get_contents($path)); |
|
35 | } |
||
36 | 9 | } |
|
37 | |||
38 | /** |
||
39 | * @param string $key |
||
40 | * @param mixed $value |
||
41 | * @return $this |
||
42 | */ |
||
43 | 8 | public function set(string $key, $value) : CacheInterface |
|
44 | { |
||
45 | 8 | $this->values[$key] = $value; |
|
46 | |||
47 | 8 | return $this; |
|
48 | } |
||
49 | |||
50 | /** |
||
51 | * @param string $key |
||
52 | * @return mixed |
||
53 | */ |
||
54 | 7 | public function get(string $key) |
|
55 | { |
||
56 | 7 | return $this->values[$key] ?? null; |
|
57 | } |
||
58 | |||
59 | /** |
||
60 | * @param string $key |
||
61 | * @return bool |
||
62 | */ |
||
63 | 5 | public function has(string $key) |
|
64 | { |
||
65 | 5 | return isset($this->values[$key]); |
|
66 | } |
||
67 | |||
68 | /** |
||
69 | * @param string $key |
||
70 | * @return $this |
||
71 | */ |
||
72 | 1 | public function delete(string $key) : CacheInterface |
|
73 | { |
||
74 | 1 | unset($this->values[$key]); |
|
75 | |||
76 | 1 | return $this; |
|
77 | } |
||
78 | |||
79 | /** |
||
80 | * @return $this |
||
81 | */ |
||
82 | 1 | public function clear() : CacheInterface |
|
83 | { |
||
84 | 1 | $this->values = []; |
|
85 | |||
86 | 1 | return $this; |
|
87 | } |
||
88 | |||
89 | /** |
||
90 | * Persists cache data to the file. |
||
91 | */ |
||
92 | 9 | public function persist() |
|
93 | { |
||
94 | 9 | file_put_contents($this->path, json_encode($this->values)); |
|
95 | 9 | } |
|
96 | |||
97 | /** |
||
98 | * Destruct magic method. |
||
99 | * Here is where the class persists the information in the file. |
||
100 | */ |
||
101 | 9 | public function __destruct() |
|
104 | 9 | } |
|
105 | } |
||
106 |