-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayUtil.php
More file actions
414 lines (367 loc) · 11.5 KB
/
ArrayUtil.php
File metadata and controls
414 lines (367 loc) · 11.5 KB
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
<?php
namespace Oro\Component\PhpUtils;
use Oro\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\PropertyAccess\PropertyPathInterface;
/**
* Provides various kind of functions for working with arrays
* example: ArrayUtil::sortBy provides stable sorting alternative to native php functions
* see methods documentation for more details
*
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
*/
class ArrayUtil
{
/**
* Returns elements of the array separated by separator
*
* @param mixed $separator
* @param array $array
*
* @return array
*/
public static function interpose($separator, array $array)
{
$result = [];
foreach ($array as $element) {
$result[] = $separator;
$result[] = $element;
}
array_shift($result);
return $result;
}
/**
* Checks whether the array is associative or sequential.
*
* @param array $array
*
* @return bool
*/
public static function isAssoc(array $array)
{
return array_values($array) !== $array;
}
/**
* Sorts an array by specified property.
*
* This method uses the stable sorting algorithm. See http://en.wikipedia.org/wiki/Sorting_algorithm#Stability
* Please use this method only if you really need stable sorting because this method is not so fast
* as native PHP sort functions.
*
* @param array $array The array to be sorted
* @param bool $reverse Indicates whether the sorting should be performed
* in reverse order
* @param mixed $propertyPath The property accessor. Can be string or PropertyPathInterface or callable
* @param int $sortingFlags The sorting type. Can be SORT_NUMERIC or SORT_STRING
* Also SORT_STRING can be combined with SORT_FLAG_CASE to sort
* strings case-insensitively
*/
public static function sortBy(
array &$array,
$reverse = false,
$propertyPath = 'priority',
$sortingFlags = SORT_NUMERIC
) {
if (empty($array)) {
return;
}
/**
* we have to implement such complex logic because the stable sorting is not supported in PHP for now
* see https://bugs.php.net/bug.php?id=53341
*/
$stringComparison = 0 !== ($sortingFlags & SORT_STRING);
$caseInsensitive = 0 !== ($sortingFlags & SORT_FLAG_CASE);
$sortable = self::prepareSortable($array, $propertyPath, $reverse, $stringComparison, $caseInsensitive);
if (!empty($sortable)) {
$keys = self::getSortedKeys($sortable, $stringComparison, $reverse);
$result = [];
foreach ($keys as $key) {
if (is_string($key)) {
$result[$key] = $array[$key];
} else {
$result[] = $array[$key];
}
}
$array = $result;
}
}
/**
* @param mixed $a
* @param mixed $b
* @param bool $stringComparison
*
* @return int
*/
private static function compare($a, $b, $stringComparison = false)
{
if ($a === $b) {
return 0;
}
if ($stringComparison) {
return strcmp($a, $b);
} else {
return $a < $b ? -1 : 1;
}
}
/**
* @param array $array
* @param string|PropertyPathInterface|callable $propertyPath
* @param bool $reverse
* @param bool $stringComparison
* @param bool $caseInsensitive
*
* @return array|null
*
* @SuppressWarnings(PHPMD.NPathComplexity)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
private static function prepareSortable($array, $propertyPath, $reverse, $stringComparison, $caseInsensitive)
{
$propertyAccessor = new PropertyAccessor();
$isSimplePropertyPath = is_string($propertyPath) && !preg_match('/.\[/', $propertyPath);
$isCallback = is_callable($propertyPath);
$defaultValue = $stringComparison ? '' : 0;
$needSorting = $reverse;
$result = [];
$lastVal = null;
$index = 0;
foreach ($array as $key => $value) {
if (is_array($value) && $isSimplePropertyPath) {
// get array property directly to speed up
$val = isset($value[$propertyPath]) || array_key_exists($propertyPath, $value)
? $value[$propertyPath]
: null;
} elseif ($isCallback) {
$val = call_user_func($propertyPath, $value);
} else {
$val = $propertyAccessor->getValue($value, $propertyPath);
}
if (null === $val) {
$val = $defaultValue;
} elseif ($caseInsensitive) {
$val = strtolower($val);
}
$result[$key] = [$val, $index++];
if ($lastVal === null) {
$lastVal = $val;
} elseif (0 !== self::compare($lastVal, $val, $stringComparison)) {
$lastVal = $val;
$needSorting = true;
}
}
if (!$needSorting) {
return null;
}
return $result;
}
/**
* @param array $sortable
* @param bool $stringComparison
* @param bool $reverse
*
* @return array
*/
private static function getSortedKeys($sortable, $stringComparison, $reverse)
{
uasort(
$sortable,
function ($a, $b) use ($stringComparison, $reverse) {
$result = self::compare($a[0], $b[0], $stringComparison);
if (0 === $result) {
$result = self::compare($a[1], $b[1]);
} elseif ($reverse) {
$result = 0 - $result;
}
return $result;
}
);
return array_keys($sortable);
}
/**
* Compares 2 values based on order specified in the argument
*
* @param int[] $order
*
* @return callable
*/
public static function createOrderedComparator(array $order)
{
return function ($a, $b) use ($order) {
if (!array_key_exists($b, $order)) {
return -1;
}
if (!array_key_exists($a, $order)) {
return 1;
}
return $order[$a] - $order[$b];
};
}
/**
* Return true if callback on any element returns truthy value, false otherwise
*
* @param callable $callback
* @param array $array
*
* @return boolean
*/
public static function some(callable $callback, array $array)
{
foreach ($array as $item) {
if (call_user_func($callback, $item)) {
return true;
}
}
return false;
}
/**
* Return first element on which callback returns true value, null otherwise
*
* @param callable $callback
* @param array $array
*
* @return mixed|null
*/
public static function find(callable $callback, array $array)
{
foreach ($array as $item) {
if (call_user_func($callback, $item)) {
return $item;
}
}
return null;
}
/**
* Return copy of the array starting with item for which callback returns falsity value
*
* @param callable $callback
* @param array $array
*
* @return array
*/
public static function dropWhile(callable $callback, array $array)
{
foreach ($array as $key => $value) {
if (!call_user_func($callback, $value)) {
return array_slice($array, $key);
}
}
return [];
}
/**
* Recursively merge arrays.
*
* Merge two arrays as array_merge_recursive do, but instead of converting values to arrays when keys are same
* replaces value from first array with value from second
*
* @param array $first
* @param array $second
*
* @return array
*/
public static function arrayMergeRecursiveDistinct(array $first, array $second)
{
foreach ($second as $idx => $value) {
if (is_integer($idx)) {
$first[] = $value;
} else {
if (!array_key_exists($idx, $first)) {
$first[$idx] = $value;
} else {
if (is_array($value)) {
if (is_array($first[$idx])) {
$first[$idx] = self::arrayMergeRecursiveDistinct($first[$idx], $value);
} else {
$first[$idx] = $value;
}
} else {
$first[$idx] = $value;
}
}
}
}
return $first;
}
/**
* Return array of ranges (inclusive)
* [[min1, max1], [min2, max2], ...]
*
* @param int[] $ints List of integers
*
* @return array
*/
public static function intRanges(array $ints)
{
$ints = array_unique($ints);
sort($ints);
$result = [];
while (false !== ($subResult = static::shiftRange($ints))) {
$result[] = $subResult;
}
return $result;
}
/**
* @param array $sortedUniqueInts
*
* @return array|false Array 2 elements [min, max] or false when the array is empty
*/
public static function shiftRange(array &$sortedUniqueInts)
{
if (!$sortedUniqueInts) {
return false;
}
$min = $max = reset($sortedUniqueInts);
$c = 1;
while (next($sortedUniqueInts) !== false && current($sortedUniqueInts) - $c === $min) {
$max = current($sortedUniqueInts);
array_shift($sortedUniqueInts);
$c++;
}
array_shift($sortedUniqueInts);
return [$min, $max];
}
/**
* @param array $array
* @param array $path
*
* @return array
*/
public static function unsetPath(array $array, array $path)
{
$key = array_shift($path);
if (!$path) {
unset($array[$key]);
return $array;
}
if (array_key_exists($key, $array) && is_array($array[$key])) {
$array[$key] = static::unsetPath($array[$key], $path);
}
return $array;
}
/**
* Returns the value in a nested associative array,
* where $path is an array of keys. Returns $defaultValue if the key
* is not present, or the not-found value if supplied.
*
* @param array $array
* @param array $path
* @param mixed $defaultValue
*
* @return mixed
*/
public static function getIn(array $array, array $path, $defaultValue = null)
{
$propertyPath = implode(
'',
array_map(
function ($part) {
return sprintf('[%s]', $part);
},
$path
)
);
$propertyAccessor = new PropertyAccessor();
if (!$propertyAccessor->isReadable($array, $propertyPath)) {
return $defaultValue;
}
return $propertyAccessor->getValue($array, $propertyPath);
}
}