Passed
Push — refactor/improve-static-analys... ( ed4ce4 )
by Bas
15:29
created

renameArrayKey()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 10
c 1
b 0
f 0
cc 2
nc 2
nop 3
crap 2
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  iterable  $array
13
     * @param  string  $prepend
14
     * @return array
15
     */
16
    function associativeFlatten(iterable $array, string $prepend = ''): iterable
17
    {
18 22
        $results = [];
19
20 22
        if (Arr::isAssoc((array) $array)) {
21 22
            foreach ($array as $key => $value) {
22 22
                if (is_iterable($value) && ! empty($value)) {
23 6
                    $dot = '';
24 6
                    if (Arr::isAssoc($value)) {
25 2
                        $dot = '.';
26
                    }
27 6
                    $results = array_merge($results, associativeFlatten($value, $prepend . $key . $dot));
28
29 6
                    continue;
30
                }
31 22
                $results[$prepend . $key] = $value;
32
            }
33 22
            return $results;
34
        }
35 6
        $results[$prepend] = $array;
36 6
        return $results;
37
    }
38
}
39
40
if (! function_exists('renameArrayKey')) {
41
    /**
42
     * @param array<mixed> $array
43
     * @param string|int $oldKey
44
     * @param string|int $newKey
45
     * @return array<mixed>
46
     */
47
    function renameArrayKey(array &$array, string|int $oldKey, string|int $newKey): array
48
    {
49 81
        if (array_key_exists($oldKey, $array)) {
50 81
            $keys = array_keys($array);
51 81
            $keys[array_search($oldKey, $keys)] = $newKey;
52 81
            $array = array_combine($keys, $array);
53
        }
54
55 81
        return $array;
56
    }
57
}
58