forked from acquia/blt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArrayManipulator.php
123 lines (111 loc) · 2.75 KB
/
ArrayManipulator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
<?php
namespace Acquia\Blt\Robo\Common;
use Dflydev\DotAccessData\Data;
/**
*
*/
class ArrayManipulator {
/**
* Merges arrays recursively while preserving.
*
* @param array $array1
* @param array $array2
*
* @return array
*
* @see http://php.net/manual/en/function.array-merge-recursive.php#92195
*/
public static function arrayMergeRecursiveDistinct(
array &$array1,
array &$array2
) {
$merged = $array1;
foreach ($array2 as $key => &$value) {
if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
$merged[$key] = self::arrayMergeRecursiveDistinct($merged[$key],
$value);
}
else {
$merged[$key] = $value;
}
}
return $merged;
}
/**
* Converts dot-notated keys to proper associative nested keys.
*
* @param $array
*
* @return array
*/
public static function expandFromDotNotatedKeys($array) {
$data = new Data();
// @todo Make this work at all levels of array.
foreach ($array as $key => $value) {
$data->set($key, $value);
}
return $data->export();
}
/**
* @param $array
*
* @return array
*/
public static function flattenToDotNotatedKeys($array) {
return self::flattenMultidimensionalArray($array, '.');
}
/**
* @param $array
*
* @return array
*/
public static function flattenMultidimensionalArray($array, $glue) {
$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($array));
$result = array();
foreach ($iterator as $leafValue) {
$keys = array();
foreach (range(0, $iterator->getDepth()) as $depth) {
$keys[] = $iterator->getSubIterator($depth)->key();
}
$result[join($glue, $keys)] = $leafValue;
}
return $result;
}
/**
* Converts a multi-dimensional array to a human-readable flat array.
*
* Used primarily for rendering tables via Symfony Console commands.
*
* @param $array
*
* @return array
*/
public static function convertArrayToFlatTextArray($array) {
$rows = [];
$max_line_length = 80;
foreach ($array as $key => $value) {
if (is_array($value)) {
$flattened_array = self::flattenToDotNotatedKeys($value);
foreach ($flattened_array as $sub_key => $sub_value) {
$rows[] = [
"$key.$sub_key",
wordwrap($sub_value, $max_line_length, "\n", TRUE)
];
}
}
else {
if ($value === TRUE) {
$contents = 'true';
}
elseif ($value === FALSE) {
$contents = 'false';
}
else {
$contents = wordwrap($value, $max_line_length, "\n", TRUE);
}
$rows[] = [$key, $contents];
}
}
return $rows;
}
}