unset_path()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 3
nop 3
dl 0
loc 12
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt;
5
6
/**
7
 * @param array $haystack
8
 * @param string $path
9
 * @param $value
10
 * @param string $separator
11
 * @return void
12
 */
13
function set_path(array &$haystack, string $path, $value, string $separator = '.'): void
14
{
15
    $path = explode($separator, $path);
16
    $temp =& $haystack;
17
18
    foreach ($path as $key) {
19
        if (!is_array($temp)) {
20
            $temp = [];
21
        }
22
23
        $temp =& $temp[$key];
24
    }
25
26
    $temp = $value;
27
}
28
29
/**
30
 * @param array $haystack
31
 * @param string $path
32
 * @param $default
33
 * @param string $separator
34
 * @return mixed
35
 */
36
function get_path(array $haystack, string $path, $default = null, string $separator = '.')
37
{
38
    return
39
        array_reduce(
40
            explode($separator, $path),
41
            fn ($arr, $key) =>
42
            $default!== $arr && is_array($arr) && array_key_exists($key, $arr) ? $arr[$key] : $default,
43
            $haystack
44
        );
45
}
46
47
/**
48
 * @param array $haystack
49
 * @param string $path
50
 * @param string $separator
51
 * @return void
52
 */
53
function unset_path(array &$haystack, string $path, string $separator = '.')
54
{
55
    $keys = explode($separator, $path);
56
    $temp =& $haystack;
57
    while (count($keys) > 1) {
58
        $key = array_shift($keys);
59
        if (array_key_exists($key, $temp) && is_array($temp[$key])) {
60
            $temp =& $temp[$key];
61
        }
62
    }
63
64
    unset($temp[array_shift($keys)]);
65
}
66
67
/**
68
 * @param array $haystack
69
 * @param string $path
70
 * @param string $separator
71
 * @return bool
72
 */
73
function has_path(array $haystack, string $path, string $separator = '.'): bool
74
{
75
    $keys = explode($separator, $path);
76
    $temp = $haystack;
77
    foreach ($keys as $key) {
78
        if (! is_array($temp) || ! array_key_exists($key, $temp)) {
79
            return false;
80
        }
81
82
        $temp = $temp[$key];
83
    }
84
85
    return true;
86
}
87