FileStorage   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 0
dl 0
loc 64
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getFilename() 0 4 1
A save() 0 5 1
A get() 0 5 1
A delete() 0 7 2
A all() 0 10 2
A putFile() 0 7 2
A getFile() 0 8 2
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
}