Completed
Pull Request — dev (#24)
by Ben
01:58
created

File::delKey()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 3
eloc 6
nc 3
nop 2
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
        $content = file_get_contents($this->filename);
63
        $this->fileState = md5($content);
64
65
66
        return json_decode($content, true);
67
    }
68
69
    /**
70
     * @inheritdoc
71
     */
72
    public function clear()
73
    {
74
        $clearState = '{}';
75
        file_put_contents($this->filename, $clearState);
76
        $this->fileState = md5($clearState);
77
    }
78
79
    /**
80
     * Remove the requested key from the data, reguardless if it's a single
81
     * value or an array of values
82
     *
83
     * @param  array  $data [description]
84
     * @param  string $key  the key to delete
85
     * @return array
86
     */
87
    private function delKey(array $data, $key)
88
    {
89
        $keys = array_keys($data);
90
        foreach ($keys as $dataKey) {
91
            if (strpos($dataKey, $key) === 0) {
92
                unset($data[$dataKey]);
93
            }
94
        }
95
        return $data;
96
    }
97
}
98