Completed
Push — master ( 8c1053...9934c8 )
by Woody
07:00
created

functions.php ➔ array_path()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 1
nop 3
dl 0
loc 11
ccs 5
cts 5
cp 1
crap 2
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