Completed
Push — master ( f81cf6...7fbbb0 )
by Oleg
03:40
created

ArrayUtils::merge()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 10.5

Importance

Changes 0
Metric Value
cc 6
eloc 13
nc 6
nop 2
dl 0
loc 22
rs 9.2222
c 0
b 0
f 0
ccs 6
cts 12
cp 0.5
crap 10.5
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DFCodeGeneration\Util;
5
6
final class ArrayUtils
7
{
8 2
    public static function isSequential(array $list): bool
9
    {
10 2
        $i = 0;
11 2
        $count = count($list);
12 2
        while (isset($list[$i])) {
13 2
            $i += 1;
14 2
            if ($i === $count) {
15 2
                return true;
16
            }
17
        }
18
19 2
        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 2
    public static function merge(array $a, array $b): array
33
    {
34 2
        if (self::isSequential($b)) {
35
            foreach ($b as $value) {
36
                $a[] = $value;
37
            }
38
            return array_unique($a);
39
        }
40
41 2
        foreach ($b as $key => $value) {
42 2
            if (array_key_exists($key, $a)) {
43
                if (is_array($value)) {
44
                    $a[$key] = self::merge($a[$key], $value);
45
                } else {
46
                    $a[$key] = $value;
47
                }
48
            } else {
49 2
                $a[$key] = $value;
50
            }
51
        }
52
53 2
        return $a;
54
    }
55
}
56