Configuration::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace CSSPrites;
4
5
/**
6
 * Configuration with dot notation for access multidimensional arrays.
7
 *
8
 * $config = new Configuration(['bar'=>['baz'=>['foo'=>true]]]);
9
 *
10
 * $value = $config->get('bar.baz.foo'); // $value == true
11
 *
12
 * $config->set('bar.baz.foo', false); // ['foo'=>false]
13
 *
14
 * $config->add('bar.baz', ['boo'=>true]); // ['foo'=>false,'boo'=>true]
15
 *
16
 * Source : https://gist.github.com/elfet/4713488
17
 *
18
 * @author Anton Medvedev <anton (at) elfet (dot) ru>
19
 * @author Luc Vancrayelynghe
20
 *
21
 * @version 1.1
22
 *
23
 * @license MIT
24
 */
25
class Configuration
26
{
27
    const SEPARATOR = '/[:\.]/';
28
29
    /**
30
     * @type array
31
     */
32
    protected $values = [];
33
34
    /**
35
     * Create a new configuration and set the default values.
36
     *
37
     * @param mixed $values The values
38
     */
39 69
    public function __construct(array $values = [])
40
    {
41 69
        $this->values = $values;
42 69
    }
43
44
    /**
45
     * Get a value by its "dot-noted" path.
46
     *
47
     * @param string $path    The dot notation path (or empty for all values)
48
     * @param mixed  $default A default value
49
     *
50
     * @return mixed The value if found, else default
51
     */
52 39
    public function get($path = '', $default = null)
53
    {
54 39
        if (empty($path)) {
55 21
            return $this->values;
56
        }
57
58 33
        $array = $this->values;
59 33
        $keys  = $this->explode($path);
60 33 View Code Duplication
        foreach ($keys as $key) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
61 33
            if (!isset($array[$key])) {
62 15
                return $default;
63
            }
64 27
            $array = $array[$key];
65 27
        }
66
67 27
        return $array;
68
    }
69
70
    /**
71
     * Set a value by its "dot-noted" path.
72
     *
73
     * @param string $path  The dot notation path (or empty for all values)
74
     * @param mixed  $value The value(s)
75
     *
76
     * @return bool Success
77
     */
78 45
    public function set($path = '', $value)
79
    {
80 45
        if (empty($path)) {
81 3
            $this->values = $value;
0 ignored issues
show
Documentation Bug introduced by
It seems like $value of type * is incompatible with the declared type array of property $values.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
82
83 3
            return true;
84
        }
85
86 42
        $at   = &$this->values;
87 42
        $keys = $this->explode($path);
88
89 42
        while (count($keys) > 0) {
90 42
            if (count($keys) === 1) {
91 42
                if (!is_array($at)) {
92 3
                    throw new \RuntimeException("Can not set value at this path ($path) because is not array.");
93
                }
94 42
                $at[array_shift($keys)] = $value;
95 42
            } else {
96 24
                $key = array_shift($keys);
97
98 24
                if (!isset($at[$key])) {
99 15
                    $at[$key] = [];
100 15
                }
101
102 24
                $at = &$at[$key];
103
            }
104 42
        }
105
106 42
        return true;
107
    }
108
109
    /**
110
     * Add new configurations to existing conf.
111
     *
112
     * @param string $path
113
     * @param array  $values
114
     *
115
     * @return bool
116
     */
117 12
    public function add($path, array $values)
118
    {
119 12
        $get = (array) $this->get($path);
120
121 12
        return $this->set($path, $this->arrayMergeRecursiveDistinct($get, $values));
122
    }
123
124
    /**
125
     * Check if a configuration exists.
126
     *
127
     * @param string $path
128
     *
129
     * @return bool
130
     */
131 3
    public function have($path)
132
    {
133 3
        $keys  = $this->explode($path);
134 3
        $array = $this->values;
135 3 View Code Duplication
        foreach ($keys as $key) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
136 3
            if (!isset($array[$key])) {
137 3
                return false;
138
            }
139 3
            $array = $array[$key];
140 3
        }
141
142 3
        return true;
143
    }
144
145
    /**
146
     * Set all the configs.
147
     *
148
     * @param array $values
149
     *
150
     * @return bool
151
     */
152 9
    public function setValues($values)
153
    {
154 9
        $this->values = $values;
155
156 9
        return true;
157
    }
158
159
    /**
160
     * Get all the configs.
161
     *
162
     * @return array
163
     */
164 30
    public function getValues()
165
    {
166 30
        return $this->values;
167
    }
168
169
    /**
170
     * [explode description].
171
     *
172
     * @param string $path [description]
173
     *
174
     * @return array
175
     */
176 66
    protected function explode($path)
177
    {
178
        // Faster than explode() ?
179 66
        return preg_split(self::SEPARATOR, $path);
180
    }
181
182
    /**
183
     * array_merge_recursive does indeed merge arrays, but it converts values with duplicate
184
     * keys to arrays rather than overwriting the value in the first array with the duplicate
185
     * value in the second array, as array_merge does. I.e., with array_merge_recursive,
186
     * this happens (documented behavior):.
187
     *
188
     * array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
189
     *     => array('key' => array('org value', 'new value'));
190
     *
191
     * arrayMergeRecursiveDistinct does not change the datatypes of the values in the arrays.
192
     * Matching keys' values in the second array overwrite those in the first array, as is the
193
     * case with array_merge, i.e.:
194
     *
195
     * arrayMergeRecursiveDistinct(array('key' => 'org value'), array('key' => 'new value'));
196
     *     => array('key' => array('new value'));
197
     *
198
     * Parameters are passed by reference, though only for performance reasons. They're not
199
     * altered by this function.
200
     *
201
     * If key is integer, it will be merged like array_merge do:
202
     * arrayMergeRecursiveDistinct(array(0 => 'org value'), array(0 => 'new value'));
203
     *     => array(0 => 'org value', 1 => 'new value');
204
     *
205
     * @param array $array1
206
     * @param array $array2
207
     *
208
     * @return array
209
     *
210
     * @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
211
     * @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
212
     * @author Anton Medvedev <anton (at) elfet (dot) ru>
213
     */
214 12
    protected function arrayMergeRecursiveDistinct(array &$array1, array &$array2)
215
    {
216 12
        $merged = $array1;
217
218 12
        foreach ($array2 as $key => &$value) {
219 12
            if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
220 6
                if (is_int($key)) {
221 3
                    $merged[] = $this->arrayMergeRecursiveDistinct($merged[$key], $value);
222 3
                } else {
223 3
                    $merged[$key] = $this->arrayMergeRecursiveDistinct($merged[$key], $value);
224
                }
225 6
            } else {
226 12
                if (is_int($key)) {
227 6
                    $merged[] = $value;
228 6
                } else {
229 9
                    $merged[$key] = $value;
230
                }
231
            }
232 12
        }
233
234 12
        return $merged;
235
    }
236
237
    /**
238
     * Loads config from a JSON file.
239
     *
240
     * @param string $filepath Path to the file where to read the config
241
     *
242
     * @return bool
243
     */
244 15
    public function load($filepath)
245
    {
246 15
        if (!file_exists($filepath)) {
247 3
            return false;
248
        }
249
250 12
        $datas = file_get_contents($filepath);
251 12
        if (!$datas) {
252 3
            return false;
253
        }
254
255 9
        $datas = json_decode($datas, true);
256 9
        if (!$datas) {
257 3
            return false;
258
        }
259
260 6
        $this->setValues($datas);
261
262 6
        return true;
263
    }
264
265
    /**
266
     * Saves config to a JSON file.
267
     *
268
     * @param string $filepath Path to the file where to write the config
269
     *
270
     * @return bool
271
     */
272 3
    public function save($filepath)
273
    {
274 3
        return file_put_contents($filepath, json_encode($this->getValues(), JSON_PRETTY_PRINT)) > 0;
275
    }
276
}
277