Passed
Pull Request — master (#30)
by Dmitriy
145:02 queued 129:54
created

ConfigMergeHelper::mergeConfig()   C

Complexity

Conditions 13
Paths 3

Size

Total Lines 41
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 22
c 2
b 0
f 0
dl 0
loc 41
rs 6.6166
cc 13
nc 3
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Composer\Config\Util;
6
7
use Yiisoft\Arrays\ReplaceArrayValue;
8
use Yiisoft\Arrays\UnsetArrayValue;
9
10
use function in_array;
11
use function is_array;
12
use function is_int;
13
14
final class ConfigMergeHelper
15
{
16
    /**
17
     * Merges two or more arrays into one recursively.
18
     *
19
     * @param array[] $arrays
20
     * @return array the merged array
21
     */
22
    public static function mergeConfig(array ...$arrays): array
23
    {
24
        $result = array_shift($arrays) ?: [];
25
        foreach ($arrays as $items) {
26
            if (!is_array($items)) {
27
                continue;
28
            }
29
            foreach ($items as $key => $value) {
30
                if ($value instanceof UnsetArrayValue) {
31
                    unset($result[$key]);
32
                    continue;
33
                }
34
35
                if ($value instanceof ReplaceArrayValue) {
36
                    $result[$key] = $value->value;
37
                    continue;
38
                }
39
40
                if (is_int($key)) {
41
                    /// XXX skip repeated values
42
                    if (in_array($value, $result, true)) {
43
                        continue;
44
                    }
45
46
                    if (array_key_exists($key, $result)) {
47
                        $result[] = $value;
48
                    }
49
50
                    continue;
51
                }
52
53
                if (is_array($value) && array_key_exists($key, $result) && is_array($result[$key])) {
54
                    $result[$key] = self::mergeConfig($result[$key], $value);
55
                    continue;
56
                }
57
58
                $result[$key] = $value;
59
            }
60
        }
61
62
        return $result;
63
    }
64
}
65