FileCache::persist()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
namespace SimpleAnnotation\Concerns\Cache;
4
5
use SimpleAnnotation\Concerns\CacheInterface;
6
7
/**
8
 * Cache abstraction concrete implementation.
9
 * Implements a file handling approach.
10
 *
11
 * @package SimpleAnnotation\Concerns\Cache
12
 */
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()
102
    {
103 9
        $this->persist();
104 9
    }
105
}
106