Passed
Push — master ( 12b4e1...e176ef )
by Lynh
13:05
created

array_merge_recursive_distinct()   B

Complexity

Conditions 10
Paths 8

Size

Total Lines 30
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 18
c 0
b 0
f 0
nc 8
nop 1
dl 0
loc 30
rs 7.6666

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
namespace Jenky\Hermes;
4
5
/**
6
 * Create new lazy evaluation middleware.
7
 *
8
 * @param  callable $callable
9
 * @return \Jenky\Hermes\LazyEvaluation
10
 */
11
function lazy(callable $callable)
12
{
13
    return new LazyEvaluation($callable);
14
}
15
16
/**
17
 * Merges any number of arrays / parameters recursively, using the left array as base, giving priority to the right array. Replacing entries with string keys with values from latter arrays.
18
 *
19
 * @param  array[] $arrays
20
 * @return array
21
 */
22
function array_merge_recursive_distinct(...$arrays)
23
{
24
    if (count($arrays) < 2) {
25
        if ($arrays === []) {
26
            return [];
27
        } else {
28
            return $arrays[0];
29
        }
30
    }
31
32
    $merged = array_shift($arrays);
33
34
    foreach ($arrays as $array) {
35
        foreach ($array as $key => $value) {
36
            if (is_array($value) && (isset($merged[$key]) && is_array($merged[$key]))) {
37
                $merged[$key] = array_merge_recursive_distinct($merged[$key], $value);
38
            } else {
39
                if (is_numeric($key)) {
40
                    if (! in_array($value, $merged)) {
41
                        $merged[] = $value;
42
                    }
43
                } else {
44
                    $merged[$key] = $value;
45
                }
46
            }
47
        }
48
        unset($key, $value);
49
    }
50
51
    return $merged;
52
}
53