Passed
Pull Request — next (#142)
by Bas
05:34 queued 02:15
created

mapObjectToArray()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 3
nc 2
nop 1
dl 0
loc 7
ccs 3
cts 3
cp 1
crap 3
rs 10
c 0
b 0
f 0
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 24
        $results = [];
19
20 24
        if (Arr::isAssoc((array) $array)) {
21 24
            foreach ($array as $key => $value) {
22 24
                if (is_array($value) && !empty($value)) {
23 6
                    $dot = '';
24 6
                    if (Arr::isAssoc($value)) {
25 5
                        $dot = '.';
26
                    }
27 6
                    $results = array_merge($results, associativeFlatten($value, $prepend . $key . $dot));
28
29 6
                    continue;
30
                }
31 24
                $results[$prepend . $key] = $value;
32
            }
33
34 24
            return $results;
35
        }
36 6
        $results[$prepend] = $array;
37
38 6
        return $results;
39
    }
40
}
41
42
if (!function_exists('isDotString')) {
43
    function isDotString(string $string): bool
44
    {
45 1
        return (bool) strpos($string, '.');
46
    }
47
}
48
49
if (!function_exists('mapObjectToArray')) {
50
    function mapObjectToArray(mixed $value): mixed
51
    {
52 5
        if(!is_object($value) && !is_array($value)) {
53 5
            return $value;
54
        }
55
56 5
        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 200
        if (array_key_exists($oldKey, $array)) {
68 200
            $keys = array_keys($array);
69 200
            $keys[array_search($oldKey, $keys)] = $newKey;
70 200
            $array = array_combine($keys, $array);
71
        }
72
73 200
        return $array;
74
    }
75
}
76