ArrayUtils::merge()   B
last analyzed

Complexity

Conditions 7
Paths 8

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 16
nc 8
nop 2
dl 0
loc 26
rs 8.8333
c 0
b 0
f 0
ccs 15
cts 15
cp 1
crap 7
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DFCodeGeneration\Util;
5
6
final class ArrayUtils
7
{
8 29
    public static function isSequential(array $list): bool
9
    {
10 29
        $i = 0;
11 29
        $count = count($list);
12 29
        while (array_key_exists($i, $list)) {
13 26
            $i += 1;
14 26
            if ($i === $count) {
15 26
                return true;
16
            }
17
        }
18
19 19
        return false;
20
    }
21
22
    /**
23
     * Recursively merges/replaces array $a and array $b.
24
     *
25
     * If determined that $b is list, it is appended to $a and the resulting array is made unique
26
     * Otherwise values from $b replaces values from $a with the same keys
27
     *
28
     * @param array $a
29
     * @param array $b
30
     * @return array
31
     */
32 18
    public static function merge(array $a, array $b): array
33
    {
34 18
        if (self::isSequential($b)) {
35 7
            foreach ($b as $value) {
36 7
                $a[] = $value;
37
            }
38 7
            $unique = array_unique($a, SORT_REGULAR);
39 7
            if (self::isSequential($a)) {
40 4
                return array_values($unique);
41
            }
42 3
            return $unique;
43
        }
44
45 13
        foreach ($b as $key => $value) {
46 13
            if (array_key_exists($key, $a)) {
47 3
                if (is_array($value)) {
48 2
                    $a[$key] = self::merge($a[$key], $value);
49
                } else {
50 3
                    $a[$key] = $value;
51
                }
52
            } else {
53 11
                $a[$key] = $value;
54
            }
55
        }
56
57 13
        return $a;
58
    }
59
}
60