Completed
Push — master ( bf1c9e...8c1053 )
by Woody
13s
created

functions.php ➔ array_path_set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 3
dl 0
loc 14
ccs 6
cts 6
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Northwoods\Config;
4
5
/**
6
 * @param array $config
7
 * @param string $dotPath
8
 * @param mixed $default
9
 * @return mixed
10
 */
11
function array_path(array $config, $dotPath, $default = null)
12
{
13
    // Working from the first key, descend into the array until nothing is found
14 3
    return array_reduce(
15 3
        explode('.', $dotPath),
16
        function ($config, $key) use ($default) {
17 3
            return isset($config[$key]) ? $config[$key] : $default;
18 3
        },
19
        $config
20 3
    );
21
}
22
23
/**
24
 * @param array $config
25
 * @param string $dotPath
26
 * @param mixed $value
27
 * @return array
28
 */
29
function array_path_set(array $config, $dotPath, $value)
30
{
31
    // Work backward from the last key, wrapping each key in an array
32 3
    $replace = array_reduce(
33 3
        array_reverse(explode('.', $dotPath)),
34
        function ($value, $key) {
35 3
            return [$key => $value];
36 3
        },
37
        $value
38 3
    );
39
40
    // Overwrite the array with the replacement
41 3
    return array_replace_recursive($config, $replace);
42
}
43