NestedArray   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 9
lcom 0
cbo 0
dl 0
loc 58
ccs 12
cts 12
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A mergeDeep() 0 4 1
B mergeDeepArray() 0 24 8
1
<?php namespace Arcanedev\Composer\Utilities;
2
3
/**
4
 * Class     NestedArray
5
 *
6
 * @package  Arcanedev\Composer\Utilities
7
 * @author   ARCANEDEV <[email protected]>
8
 */
9
class NestedArray
10
{
11
    /**
12
     * Merges multiple arrays, recursively, and returns the merged array.
13
     *
14
     * This function is similar to PHP's array_merge_recursive() function, but it handles non-array values differently.
15
     * When merging values that are not both arrays, the latter value replaces the former rather than merging with it.
16
     *
17
     *
18
     * @param  array  $arrays
19
     *
20
     * @return array
21
     *
22
     * @see NestedArray::mergeDeepArray()
23
     */
24 9
    public static function mergeDeep(...$arrays)
25
    {
26 9
        return self::mergeDeepArray($arrays);
27
    }
28
29
    /**
30
     * Merges multiple arrays, recursively, and returns the merged array.
31
     *
32
     * This function is equivalent to NestedArray::mergeDeep(), except the input arrays are passed as a single array
33
     * parameter rather than a variable parameter list.
34
     *
35
     * @param  array  $arrays
36
     * @param  bool   $preserveIntegerKeys
37
     *
38
     * @return array
39
     *
40
     * @see NestedArray::mergeDeep()
41
     */
42 18
    public static function mergeDeepArray(array $arrays, $preserveIntegerKeys = false)
43
    {
44 18
        $result = [];
45
46 18
        foreach ($arrays as $array) {
47 18
            foreach ($array as $key => $value) {
48
                // Renumber integer keys as array_merge_recursive() does unless $preserve_integer_keys is set to TRUE.
49
                // Note that PHP automatically converts array keys that are integer strings (e.g., '1') to integers.
50 18
                if (is_integer($key) && ! $preserveIntegerKeys) {
51 18
                    $result[] = $value;
52
                }
53 18
                elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
54
                    // Recurse when both values are arrays.
55 18
                    $result[$key] = self::mergeDeepArray([$result[$key], $value], $preserveIntegerKeys);
56
                }
57
                else {
58
                    // Otherwise, use the latter value, overriding any previous value.
59 18
                    $result[$key] = $value;
60
                }
61
            }
62
        }
63
64 18
        return $result;
65
    }
66
}
67