File   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 93
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 4
Bugs 0 Features 1
Metric Value
wmc 11
c 4
b 0
f 1
lcom 1
cbo 0
dl 0
loc 93
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A save() 0 19 3
A load() 0 13 3
A clear() 0 6 1
A delKey() 0 10 3
1
<?php
2
3
namespace Benrowe\Laravel\Config\Storage;
4
5
/**
6
 * File storage for config
7
 *
8
 * @package Benrowe\Laravel\Config\Storage
9
 */
10
class File implements StorageInterface
11
{
12
    /**
13
     * @var string path to the config file
14
     */
15
    protected $filename;
16
17
    /**
18
     * @var string The state of the file as an md5 checksum
19
     * This is used to verify if the state of the file changed before it
20
     * is written back
21
     */
22
    private $fileState;
23
24
    /**
25
     * constructor
26
     *
27
     * @param string $file the file to persist the data two
28
     */
29
    public function __construct($file)
30
    {
31
        $this->filename = $file;
32
    }
33
34
    /**
35
     * @inheritdoc
36
     */
37
    public function save($key, $value)
38
    {
39
        $data = $this->load();
40
        $data = $this->delKey($data, $key);
41
        if (is_array($value)) {
42
            // remove all previous keys first
43
44
            foreach ($value as $i => $arrValue) {
45
                $data[$key.'['.$i.']'] = $arrValue;
46
            }
47
        } else {
48
            $data[$key] = $value;
49
        }
50
51
        $content = json_encode($data);
52
        $this->fileState = md5($content);
53
54
        file_put_contents($this->filename, $content);
55
    }
56
57
    /**
58
     * @inheritdoc
59
     */
60
    public function load()
61
    {
62
        if (!file_exists($this->filename)) {
63
            touch($this->filename);
64
        }
65
        $content = file_get_contents($this->filename);
66
        $this->fileState = md5($content);
67
68
        if (!empty($content)) {
69
            return json_decode($content, true);
70
        }
71
        return [];
72
    }
73
74
    /**
75
     * @inheritdoc
76
     */
77
    public function clear()
78
    {
79
        $clearState = '{}';
80
        file_put_contents($this->filename, $clearState);
81
        $this->fileState = md5($clearState);
82
    }
83
84
    /**
85
     * Remove the requested key from the data, reguardless if it's a single
86
     * value or an array of values
87
     *
88
     * @param  array  $data [description]
89
     * @param  string $key  the key to delete
90
     * @return array
91
     */
92
    private function delKey(array $data, $key)
93
    {
94
        $keys = array_keys($data);
95
        foreach ($keys as $dataKey) {
96
            if (strpos($dataKey, $key) === 0) {
97
                unset($data[$dataKey]);
98
            }
99
        }
100
        return $data;
101
    }
102
}
103