1
|
|
|
<?php |
2
|
|
|
namespace Consolidation\Config\Util; |
3
|
|
|
|
4
|
|
|
/** |
5
|
|
|
* Useful array utilities. |
6
|
|
|
*/ |
7
|
|
|
class ArrayUtil |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* Merges arrays recursively while preserving. |
11
|
|
|
* |
12
|
|
|
* @param array $array1 |
13
|
|
|
* @param array $array2 |
14
|
|
|
* |
15
|
|
|
* @return array |
16
|
|
|
* |
17
|
|
|
* @see http://php.net/manual/en/function.array-merge-recursive.php#92195 |
18
|
|
|
* @see https://github.com/grasmash/bolt/blob/robo-rebase/src/Robo/Common/ArrayManipulator.php#L22 |
19
|
|
|
*/ |
20
|
|
|
public static function mergeRecursiveDistinct( |
21
|
|
|
array &$array1, |
22
|
|
|
array &$array2 |
23
|
|
|
) { |
24
|
|
|
$merged = $array1; |
25
|
|
|
foreach ($array2 as $key => &$value) { |
26
|
|
|
$merged[$key] = self::mergeRecursiveValue($merged, $key, $value); |
27
|
|
|
} |
28
|
|
|
return $merged; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Process the value in an mergeRecursiveDistinct - make a recursive |
33
|
|
|
* call if needed. |
34
|
|
|
*/ |
35
|
|
|
protected static function mergeRecursiveValue(&$merged, $key, $value) |
36
|
|
|
{ |
37
|
|
|
if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) { |
38
|
|
|
return self::mergeRecursiveDistinct($merged[$key], $value); |
39
|
|
|
} |
40
|
|
|
return $value; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Fills all of the leaf-node values of a nested array with the |
45
|
|
|
* provided replacement value. |
46
|
|
|
*/ |
47
|
|
|
public static function fillRecursive(array $data, $fill) |
48
|
|
|
{ |
49
|
|
|
$result = []; |
50
|
|
|
foreach ($data as $key => $value) { |
51
|
|
|
$result[$key] = $fill; |
52
|
|
|
if (self::isAssociative($value)) { |
53
|
|
|
$result[$key] = self::fillRecursive($value, $fill); |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
return $result; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Return true if the provided parameter is an array, and at least |
61
|
|
|
* one key is non-numeric. |
62
|
|
|
*/ |
63
|
|
|
public static function isAssociative($testArray) |
64
|
|
|
{ |
65
|
|
|
if (!is_array($testArray)) { |
66
|
|
|
return false; |
67
|
|
|
} |
68
|
|
|
foreach (array_keys($testArray) as $key) { |
69
|
|
|
if (!is_numeric($key)) { |
70
|
|
|
return true; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
return false; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|