-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathArrayTool.php
697 lines (640 loc) · 19.1 KB
/
ArrayTool.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
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
<?php
namespace Ling\Bat;
use Ling\Bat\Exception\BatException;
/**
* The ArrayTool class.
* LingTalfi 2015-12-20 -> 2020-06-29
*/
class ArrayTool
{
/**
* Checks that every given keys exist in the given pool array, and returns the result as a boolean.
*
* If the throwEx flag is set to true, then this method throws an exception as soon as a missing key is found.
* If it's set to false, the missing keys are available via the missingKeys array.
*
*
*
* @param array|string $keys
* @param array $pool
* @param bool $throwEx
* @param array $missingKeys
* @return bool
* @throws \Exception
*/
public static function arrayKeyExistAll($keys, array $pool, bool $throwEx = false, array &$missingKeys = []): bool
{
if (false === is_array($keys)) {
$keys = [$keys];
}
$hasAll = true;
foreach ($keys as $key) {
if (false === array_key_exists($key, $pool)) {
if (true === $throwEx) {
throw new BatException("Key not found: $key.");
}
$hasAll = false;
$missingKeys[] = $key;
}
}
return $hasAll;
}
/**
* Merge the given arrays and return a resulting array,
* appending numeric keys, and replacing existing associative keys.
*
* This algorithm merges arrays together, and when a value already exists, one of the two cases occur:
*
* - either the replaced value is an array, in which case the new value gets appended to that array
* - or the replaced value is a scalar value (i.e. not an array), in which case the new value completely replaces the old one
*
*
*
* Technically, the merging rules are basically the following:
* - set the associative key only if it doesn't already exist
* - if it's a numeric key, append it
*
*
* Example:
* -----------
* Given array1:
* array(1) {
* ["example"] => array(2) {
* ["fruits"] => array(2) {
* [0] => string(5) "apple"
* [1] => string(6) "banana"
* }
* ["numbers"] => array(2) {
* ["one"] => int(1)
* ["two"] => int(2)
* }
* }
* }
*
*
* and array2:
* array(1) {
* ["example"] => array(3) {
* ["fruits"] => array(1) {
* [0] => string(6) "cherry"
* }
* ["sports"] => array(2) {
* [0] => string(4) "judo"
* [1] => string(6) "karate"
* }
* ["numbers"] => array(1) {
* ["two"] => int(222)
* }
* }
* }
*
*
* The result of Bat::arrayMergeReplaceRecursive([array1, array2]) gives:
*
* array(1) {
* ["example"] => array(3) {
* ["fruits"] => array(3) {
* [0] => string(5) "apple"
* [1] => string(6) "banana"
* [2] => string(6) "cherry"
* }
* ["numbers"] => array(2) {
* ["one"] => int(1)
* ["two"] => int(222)
* }
* ["sports"] => array(2) {
* [0] => string(4) "judo"
* [1] => string(6) "karate"
* }
* }
* }
*
*
*
*
*
*
*
* @param array $arrays
* @return array
*/
public static function arrayMergeReplaceRecursive(array $arrays)
{
$arr = [];
foreach ($arrays as $array) {
foreach ($array as $k => $v) {
if (is_numeric($k)) {
$arr[] = $v;
} else {
if (false === array_key_exists($k, $arr)) {
$arr[$k] = $v;
} else {
if (
true === is_array($v) &&
false === empty($v) &&
true === is_array($arr[$k])
) {
$arr[$k] = self::arrayMergeReplaceRecursive([$arr[$k], $v]);
} else {
$arr[$k] = $v;
}
}
}
}
}
return $arr;
}
public static function arrayUniqueRecursive(array $array)
{
$result = array_map("unserialize", array_unique(array_map("serialize", $array)));
foreach ($result as $key => $value) {
if (is_array($value)) {
$result[$key] = self::arrayUniqueRecursive($value);
}
}
return $result;
}
/**
* Walks the given array, applying the given callable to every key.
*
* The callable must return a valid key (i.e. a string or a number).
*
*
* @param array $arr
* @param callable $fn
* @return void
*/
public static function arrayWalkKeys(array &$arr, callable $fn)
{
$ret = [];
foreach ($arr as $k => $v) {
$k = $fn($k);
$ret[$k] = $v;
}
$arr = $ret;
}
/**
* Walks the given array recursively, applying the given callable to every key.
*
* The callable must return a valid key (i.e. a string or a number).
*
*
* @param array $arr
* @param callable $fn
* @return void
*/
public static function arrayWalkKeysRecursive(array &$arr, callable $fn)
{
$ret = [];
$pathsToRemove = [];
BDotTool::walk($arr, function ($v, $k, $curPath) use (&$ret, $fn, &$pathsToRemove) {
$newK = call_user_func($fn, $k);
if ($k !== $newK) {
$pathsToRemove[] = $curPath;
$components = BDotTool::getPathComponents($curPath);
array_pop($components);
$components[] = str_replace('.', '\.', $newK);
$curPath = implode('.', $components);
}
BDotTool::setDotValue($curPath, $v, $ret);
});
foreach ($pathsToRemove as $p) {
BDotTool::unsetDotValue($p, $ret);
}
$arr = $ret;
}
/**
* Returns the $array, without the entries which keys are NOT listed in $allowed.
*
* Example:
* ---------
* $array = [
* "one" => 11,
* "two" => 22,
* "garbage" => 123,
* ];
*
* $allowed = ["one", "two"];
*
* az(ArrayTool::filterByAllowed($array, $allowed));
*
* - one: 11
* - two: 22
*
*
*
* @param array $array
* @param array $allowed
* @return array
*/
public static function filterByAllowed(array $array, array $allowed): array
{
return array_intersect_key($array, array_flip($allowed));
}
/**
* Filters the elements of an array recursively, using a given callable.
*
* The callable function must return a boolean (whether to accept the value or remove it).
*
* See the examples from the doc for more details.
*
*
* @param array $array
* @param callable $callback
* @return array
*/
public static function filterRecursive(array $array, callable $callback): array
{
foreach ($array as $k => $v) {
$res = call_user_func($callback, $v);
if (false === $res) {
unset($array[$k]);
} else {
if (is_array($v)) {
$array[$k] = self::filterRecursive($v, $callback);
}
}
}
return $array;
}
/**
* Check that all given $keys exist (as keys) in the given $arr.
* If not, returns the missing keys.
*
*
* @param array $arr
* @param array $keys
* @return array|false
* Returns false if there is no missing key.
*
*/
public static function getMissingKeys(array $arr, array $keys)
{
$missing = [];
foreach ($keys as $key) {
if (!array_key_exists($key, $arr)) {
$missing[] = $key;
}
}
if ($missing) {
return $missing;
}
return false;
}
/**
* Returns whether array a and b contains the same values;
* The order doesn't matter.
*
* https://stackoverflow.com/questions/21138505/check-if-two-arrays-have-the-same-values
*
* @param array $a
* @param array $b
* @return bool
*/
public static function hasSameValues(array $a, array $b): bool
{
$copy = $a;
foreach ($b as $element) {
$key = array_search($element, $copy, true);
if ($key === false) {
return false;
}
unset($copy[$key]);
}
return empty($copy);
}
/**
* Insert the given row into the rows;
*
*
* @param $index
* @param array $entry
* @param array $rows , an array with numerical keys, each value being an array.
*/
public static function insertRowAfter(int $index, array $row, array &$rows)
{
$zeIndex = $index + 1;
$start = array_slice($rows, 0, $zeIndex);
$end = array_slice($rows, $zeIndex);
$entryWrapped = [$row];
$rows = array_merge($start, $entryWrapped, $end);
}
/**
* Returns an array containing all the key/value pairs of the given $array which keys are in the given $keys.
* See the examples for more information.
*
*
* @param array $array
* @param array $keys
* @return array
*/
public static function intersect(array $array, array $keys): array
{
return array_intersect_key($array, array_flip($keys));
}
/**
* Returns whether the given argument is an array which first key is numerical.
*
* Note: supposedly if the first key is numerical, chances are that the whole array is numerical,
* depending on the array structure. This method was designed to give a quick guess, as opposed to
* check all the keys of the array, which might take too long depending on the array size.
*
*
*
*
* @param $array
* @param bool $emptyIsValid
* Whether an empty array is considered a valid numerically indexed array (default is true)
*
* @return bool
*/
public static function isNumericalArray($array, $emptyIsValid = true): bool
{
if (is_array($array)) {
if (empty($array)) {
return $emptyIsValid;
}
return is_numeric(key($array));
}
return false;
}
/**
* Returns whether array a and b are identical.
* The order of keys matters.
*
* @param array $a
* @param array $b
* @return bool
*/
public static function isIdentical(array $a, array $b): bool
{
return ($a === $b);
}
/**
* Return an array with keys equal to values.
*
* @param array $values
* @return array
*/
public static function keysSameAsValues(array $values): array
{
$ret = [];
foreach ($values as $value) {
$ret[$value] = $value;
}
return $ret;
}
/**
* Like php range function, but the ranges applies on both the values and the keys
* (i.e. not just the values like the php range function does)
*
* @param $start
* @param $end
* @param int $step
* @return array
*/
public static function mirrorRange($start, $end, $step = 1)
{
return array_combine(range($start, $end, $step), range($start, $end, $step));
}
/**
* This method returns the array corresponding to an object, including non public members.
*
* If the deep flag is true, is will operate recursively, otherwise (if false) just at the first level.
*
* @param object $obj
* @param bool $deep = true
* @return array
* @throws \Exception
*/
public static function objectToArray(object $obj, bool $deep = true)
{
$reflectionClass = new \ReflectionClass(get_class($obj));
$array = [];
foreach ($reflectionClass->getProperties() as $property) {
$property->setAccessible(true);
$val = $property->getValue($obj);
if (true === $deep && is_object($val)) {
$val = self::objectToArray($val);
}
$array[$property->getName()] = $val;
$property->setAccessible(false);
}
return $array;
}
public static function removeEntry($entry, array &$arr)
{
if (false !== ($index = array_search($entry, $arr))) {
unset($arr[$index]);
}
}
/**
* Returns a one dimensional numerically indexed array,
* which values are the row[column] values.
*
* Note: we trust that the user provides consistent rows
* (i.e. we don't loose time with checking the data).
*
*
* @param array $rows
* @param string $column
* @return array
*/
public static function reduce(array $rows, string $column): array
{
$ret = [];
foreach ($rows as $row) {
$ret[] = $row[$column];
}
return $ret;
}
/**
* Parses the given array recursively replacing the tag keys by their values
* directly in the array values of type string, using str_replace under the hood.
*
* Tags is an array of key/value pairs,
* such as:
*
* - {myTag} => 123
* - {myTag2} => abc
*
* Only scalar values are accepted.
* If you need to replace with non scalar values such as arrays, you might
* be interested in the [ArrayVariableResolver]https://github.com/lingtalfi/ArrayVariableResolver tool.
*
* See the online documentation for some concrete examples.
*
*
* @param array $tags
* @param array &$array
* @return array
*/
public static function replaceRecursive(array $tags, array &$array): array
{
array_walk_recursive($array, function (&$v) use ($tags) {
if (is_string($v)) {
$v = str_replace(array_keys($tags), array_values($tags), $v);
}
});
return $array;
}
/**
* Same as php array_splice, but preserve keys.
*
*
* @param $input
* @param $offset
* @param $length
* @param array $replacement
*/
public static function splice(&$input, $offset, $length, $replacement = array())
{
// https://stackoverflow.com/questions/16585502/array-splice-preserving-keys
$replacement = (array)$replacement;
$key_indices = array_flip(array_keys($input));
if (isset($input[$offset]) && is_string($offset)) {
$offset = $key_indices[$offset];
}
if (isset($input[$length]) && is_string($length)) {
$length = $key_indices[$length] - $offset;
}
$input = array_slice($input, 0, $offset, true)
+ $replacement
+ array_slice($input, $offset + $length, null, true);
}
/**
* Returns the given $defaults array,
* with values possibly overridden by the $array.
*
* Example
* ----------
*
* $array = [
* "color" => "blue",
* "hobby" => "music",
* ];
*
* $defaults = [
* "color" => "green",
* "sport" => "judo",
* "fruit" => "apple",
* ];
*
*
* a(ArrayTool::superimpose($array, $defaults));
*
* - color: blue
* - sport: judo
* - fruit: apple
*
*
*
*
* @param array $array
* @param array $defaults
* @return array
*/
public static function superimpose(array $array, array $defaults)
{
return array_merge($defaults, array_intersect_key($array, $defaults));
}
/**
* Updates an array recursively, like (php) array_walk_recursive, but adapted for nested item structures.
*
* A nested item structure looks like this for instance:
*
* -
* id: one
* label: One
* children: []
* -
* id: two
* label: Two
* children:
* -
* id: three
* label: Three
* children: []
*
*
*
*
*
*
*
*
* @param array $arr
* @param callable $callback
* @param array $options
*
*
* Example:
* (this will add the link property to every node in the array recursively)
*
*
* $linkFmt = "/mylink/{type}/{slug}";
* ArrayTool::updateNodeRecursive($ret, function (array &$row) use ($linkFmt) {
* $row['link'] = str_replace([
* "{type}",
* "{slug}",
* ], [
* $row['type'],
* $row['slug'],
* ], $linkFmt);
* });
*
*
*
*
*/
public static function updateNodeRecursive(array &$arr, callable $callback, array $options = [])
{
$childrenKey = $options['childrenKey'] ?? "children";
foreach ($arr as $k => $v) {
call_user_func_array($callback, [&$v]);
if (array_key_exists($childrenKey, $v) && $v[$childrenKey]) {
$children = $v[$childrenKey];
self::updateNodeRecursive($children, $callback, $options);
$v[$childrenKey] = $children;
}
$arr[$k] = $v;
}
}
/**
* Walks the given rows recursively, triggering the given callback on each row.
*
* A row is an array.
* Generally all rows have the same structure.
* A row can contain other rows, in which case it's a parent row.
* The parent row holds its children using a **children** key, which defaults to **children** (third argument).
*
*
* The callable receives the row as its only argument.
* If the row is defined as a reference, then we can update the row from inside the callable.
*
*
* By default, the callable is called for every row, including the parent rows.
* If you want to trigger the callable only on leaves (rows with no children), you can set
* the $triggerCallableOnParents flag to false.
*
*
* @param array $arr
* @param callable $callback
* @param string $childrenKey =children
* @param bool $triggerCallableOnParents =true
*/
public static function walkRowsRecursive(array &$arr, callable $callback, string $childrenKey = "children", bool $triggerCallableOnParents = true): void
{
foreach ($arr as $k => &$v) {
$isParent = array_key_exists($childrenKey, $v) && $v[$childrenKey];
if (false === $isParent || true === $triggerCallableOnParents) {
call_user_func_array($callback, [&$v]);
}
if (true === $isParent) {
$children = $v[$childrenKey];
self::walkRowsRecursive($children, $callback, $childrenKey);
$v[$childrenKey] = $children;
}
}
}
}