Failed Conditions
Push — feature/support-callable-updat... ( d5b96d )
by Bas
13:45
created

mapObjectToArray()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 3
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 7
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
use Illuminate\Support\Arr;
6
7
if (!function_exists('associativeFlatten')) {
8
    /**
9
     * Flatten a multi-dimensional associative array with dots.
10
     * List arrays are left untouched.
11
     *
12
     * @param array<mixed> $array
13
     * @param string $prepend
14
     * @return array<mixed>
15
     */
16
    function associativeFlatten(array $array, string $prepend = ''): array
17
    {
18
        $results = [];
19
20
        if (Arr::isAssoc((array) $array)) {
21
            foreach ($array as $key => $value) {
22
                if (is_array($value) && !empty($value)) {
23
                    $dot = '';
24
                    if (Arr::isAssoc($value)) {
25
                        $dot = '.';
26
                    }
27
                    $results = array_merge($results, associativeFlatten($value, $prepend . $key . $dot));
28
29
                    continue;
30
                }
31
                $results[$prepend . $key] = $value;
32
            }
33
34
            return $results;
35
        }
36
        $results[$prepend] = $array;
37
38
        return $results;
39
    }
40
}
41
42
if (!function_exists('isDotString')) {
43
    function isDotString(string $string): bool
44
    {
45
        return (bool) strpos($string, '.');
46
    }
47
}
48
49
if (!function_exists('mapObjectToArray')) {
50
    function mapObjectToArray(mixed $value): mixed
51
    {
52
        if(!is_object($value) && !is_array($value)) {
53
            return $value;
54
        }
55
56
        return array_map('mapObjectToArray', (array) $value);
57
    }
58
}
59
60
if (!function_exists('renameArrayKey')) {
61
    /**
62
     * @param  array<mixed>  $array
63
     * @return array<mixed>
64
     */
65
    function renameArrayKey(array &$array, string|int $oldKey, string|int $newKey): array
66
    {
67
        if (array_key_exists($oldKey, $array)) {
68
            $keys = array_keys($array);
69
            $keys[array_search($oldKey, $keys)] = $newKey;
70
            $array = array_combine($keys, $array);
71
        }
72
73
        return $array;
74
    }
75
}
76