-
Notifications
You must be signed in to change notification settings - Fork 5
/
Collections.php
950 lines (876 loc) · 31.6 KB
/
Collections.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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
<?php
namespace __\Traits;
use __;
use Closure;
use Exception;
use stdClass;
trait Collections
{
/**
* Returns the values in the collection that pass the truth test.
*
* @param array $array array to filter
* @param \Closure $closure closure to filter array based on
*
* @return array
*/
public static function filter(array $array = [], Closure $closure = null): array
{
if ($closure) {
$result = [];
foreach ($array as $key => $value) {
if (call_user_func($closure, $value)) {
$result[] = $value;
}
}
return $result;
}
return __::compact($array);
}
/**
* Gets the first element of an array. Passing n returns the first n elements.
*
* @usage __::first([1, 2, 3]);
* >> 1
*
* @param array $array of values
* @param int|null $take number of values to return
*
* @return mixed
*/
public static function first(array $array, $take = null)
{
if (!$take) {
return array_shift($array);
}
return array_splice($array, 0, $take);
}
/**
* Get item of an array by index, accepting nested index
*
* @usage __::get(['foo' => ['bar' => 'ter']], 'foo.bar');
* >> 'ter'
*
* @param array|object $collection array of values
* @param null|string $key key or index
* @param mixed $default default value to return if index not exist
*
* @return mixed
*/
public static function get($collection = [], $key = null, $default = null)
{
if (__::isNull($key)) {
return $collection;
}
if (!__::isObject($collection) && isset($collection[$key])) {
return $collection[$key];
}
foreach (explode('.', $key) as $segment) {
if (__::isObject($collection)) {
if (!isset($collection->{$segment})) {
return $default instanceof Closure ? $default() : $default;
} else {
$collection = $collection->{$segment};
}
} else {
if (!isset($collection[$segment])) {
return $default instanceof Closure ? $default() : $default;
} else {
$collection = $collection[$segment];
}
}
}
return $collection;
}
/**
* Get last item(s) of an array
*
* @usage __::last([1, 2, 3, 4, 5], 2);
* >> [4, 5]
*
* @param array $array array of values
* @param int|null $take number of returned values
*
* @return mixed
*/
public static function last(array $array, $take = null)
{
if (!$take) {
return array_pop($array);
}
return array_splice($array, -$take);
}
/**
* Returns an array of values by mapping each in collection through the iterateFn. The iterateFn is invoked with
* three arguments: (value, index|key, collection).
*
* @usage __::map([1, 2, 3], function($n) {
* return $n * 3;
* });
* >> [3, 6, 9]
*
* @param array|object $collection The collection of values to map over.
* @param \Closure $iterateFn The function to apply on each value.
*
* @return array
*/
public static function map($collection, Closure $iterateFn): array
{
$result = [];
__::doForEach($collection, function ($value, $key, $collection) use (&$result, $iterateFn) {
$result[] = $iterateFn($value, $key, $collection);
});
return $result;
}
/**
* Returns the maximum value from the collection. If passed an iterator, max will return max value returned by the
* iterator.
*
* @usage __::max([1, 2, 3]);
* >> 3
*
* @param array $array The array to iterate over
*
* @return mixed Returns the maximum value
*/
public static function max(array $array = [])
{
return max($array);
}
/**
* Returns the minimum value from the collection. If passed an iterator, min will return min value returned by the
* iterator.
*
* @usage __::min([1, 2, 3]);
* >> 1
*
* @param array $array array of values
*
* @return mixed
*/
public static function min(array $array = [])
{
return min($array);
}
/**
* Returns an array of values belonging to a given property of each item in a collection.
*
* @usage $a = [
* ['foo' => 'bar', 'bis' => 'ter' ],
* ['foo' => 'bar2', 'bis' => 'ter2'],
* ];
*
* __::pluck($a, 'foo');
* >> ['bar', 'bar2']
*
* @param array|object $collection array or object that can be converted to array
* @param string $property property name
*
* @return array
*/
public static function pluck($collection, string $property): array
{
$result = array_map(function ($value) use ($property) {
if (is_array($value) && isset($value[$property])) {
return $value[$property];
} elseif (is_object($value) && isset($value->{$property})) {
return $value->{$property};
}
foreach (__::split($property, '.') as $segment) {
if (is_object($value)) {
if (isset($value->{$segment})) {
$value = $value->{$segment};
} else {
return null;
}
} else {
if (isset($value[$segment])) {
$value = $value[$segment];
} else {
return null;
}
}
}
return $value;
}, (array)$collection);
return array_values($result);
}
/**
* Return data matching specific key value condition
*
* @usage __::where($a, ['age' => 16]);
* >> [['name' => 'maciej', 'age' => 16]]
*
* @param array $array array of values
* @param array $key condition in format of ['KEY'=>'VALUE']
* @param bool $keepKeys keep original keys
*
* @return array
*/
public static function where(array $array = [], array $key = [], bool $keepKeys = false): array
{
$result = [];
foreach ($array as $k => $v) {
$not = false;
foreach ($key as $j => $w) {
if (__::isArray($w)) {
$inKV = $v[$j] ?? [];
if (count(array_intersect_assoc($w, $inKV)) == 0) {
$not = true;
break;
}
} else {
if (!isset($v[$j]) || $v[$j] != $w) {
$not = true;
break;
}
}
}
if ($not == false) {
if ($keepKeys) {
$result[$k] = $v;
} else {
$result[] = $v;
}
}
}
return $result;
}
/**
* Combines and merge collections provided with each others.
*
* If the collections have common keys, then the last passed keys override the
* previous. If numerical indexes are passed, then last passed indexes override
* the previous.
*
* For a recursive merge, see __::merge.
*
* @usage __::assign(['color' => ['favorite' => 'red', 5], 3], [10, 'color' => ['favorite' => 'green', 'blue']]);
* >> ['color' => ['favorite' => 'green', 'blue'], 10]
*
* @param array|object $collection1 Collection to assign to.
* @param array|object $collection2 Other collections to assign
*
* @return array|object Assigned collection.
*/
public static function assign($collection1, $collection2)
{
return __::reduceRight(func_get_args(), function ($source, $result) {
__::doForEach($source, function ($sourceValue, $key) use (&$result) {
$result = __::set($result, $key, $sourceValue);
});
return $result;
}, []);
}
/**
* Reduces $collection to a value which is the $accumulator result of running each
* element in $collection - from right to left - thru $iterateFn, where each
* successive invocation is supplied the return value of the previous.
*
* If $accumulator is not given, the first element of $collection is used as the
* initial value.
*
* The $iterateFn is invoked with four arguments:
* ($accumulator, $value, $index|$key, $collection).
*
* @usage __::reduceRight(['a', 'b', 'c'], function ($word, $char) {
* return $word . $char;
* }, '');
* >> 'cba'
*
* @param array|object $collection The collection to iterate over.
* @param \Closure $iterateFn The function invoked per iteration.
* @param mixed $accumulator
*
* @return array|mixed|null (*): Returns the accumulated value.
*/
public static function reduceRight($collection, Closure $iterateFn, $accumulator = null)
{
if ($accumulator === null) {
$accumulator = array_pop($collection);
}
__::doForEachRight(
$collection,
function ($value, $key, $collection) use (&$accumulator, $iterateFn) {
$accumulator = $iterateFn($accumulator, $value, $key, $collection);
}
);
return $accumulator;
}
/**
* Iterate over elements of the collection, from right to left, and invokes iterate
* for each element.
*
* The iterate is invoked with three arguments: (value, index|key, collection).
* Iterate functions may exit iteration early by explicitly returning false.
*
* @usage __::doForEachRight([1, 2, 3], function ($value) { print_r($value) });
* >> (Side effect: print 3, 2, 1)
*
* @param array|object $collection The collection to iterate over.
* @param \Closure $iterateFn The function to call for each value.
*
* @return boolean
*/
public static function doForEachRight($collection, Closure $iterateFn)
{
__::doForEach(__::iteratorReverse($collection), $iterateFn);
return true;
}
/**
* Iterate over elements of the collection and invokes iterate for each element.
*
* The iterate is invoked with three arguments: (value, index|key, collection).
* Iterate functions may exit iteration early by explicitly returning false.
*
* @usage __::doForEach([1, 2, 3], function ($value) { print_r($value) });
* >> (Side effect: print 1, 2, 3)
*
* @param array|object $collection The collection to iterate over.
* @param \Closure $iterateFn The function to call for each value
*
* @return boolean
*/
public static function doForEach($collection, Closure $iterateFn)
{
foreach ($collection as $key => $value) {
if ($iterateFn($value, $key, $collection) === false) {
break;
}
}
return true;
}
/**
* @param array $iterable
*
* @return \Generator
*/
public static function iteratorReverse($iterable)
{
for (end($iterable); ($key = key($iterable)) !== null; prev($iterable)) {
yield $key => current($iterable);
}
}
/**
* Return a new collection with the item set at index to given value.
* Index can be a path of nested indexes.
*
* If a portion of path doesn't exist, it's created. Arrays are created for missing
* index in an array; objects are created for missing property in an object.
*
* @usage __::set(['foo' => ['bar' => 'ter']], 'foo.baz.ber', 'fer');
* >> '['foo' => ['bar' => 'ter', 'baz' => ['ber' => 'fer']]]'
*
* @param array|object $collection collection of values
* @param string|int|null $path key or index
* @param mixed $value the value to set at position $key
*
* @throws \Exception if the path consists of a non collection and strict is set to false
*
* @return array|object the new collection with the item set
*/
public static function set($collection, $path, $value = null)
{
if ($path === null) {
return $collection;
}
$portions = __::split($path, '.', 2);
$key = $portions[0];
if (count($portions) === 1) {
return __::universalSet($collection, $key, $value);
}
// Here we manage the case where the portion of the path points to nothing,
// or to a value that does not match the type of the source collection
// (e.g. the path portion 'foo.bar' points to an integer value, while we
// want to set a string at 'foo.bar.fun'. We first set an object or array
// - following the current collection type - to 'for.bar' before setting
// 'foo.bar.fun' to the specified value).
if (!__::has($collection, $key)
|| (__::isObject($collection) && !__::isObject(__::get($collection, $key)))
|| (__::isArray($collection) && !__::isArray(__::get($collection, $key)))
) {
$collection = __::universalSet($collection, $key, __::isObject($collection) ? new stdClass : []);
}
return __::universalSet($collection, $key, __::set(__::get($collection, $key), $portions[1], $value));
}
/**
* @param mixed $collection
* @param mixed $key
* @param mixed $value
*
* @return mixed
*/
public static function universalSet($collection, $key, $value)
{
$set_object = function ($object, $key, $value) {
$newObject = clone $object;
$newObject->$key = $value;
return $newObject;
};
$set_array = function ($array, $key, $value) {
$array[$key] = $value;
return $array;
};
$setter = __::isObject($collection) ? $set_object : $set_array;
return call_user_func_array($setter, [$collection, $key, $value]);
}
/**
* Returns if $input contains all requested $keys. If $strict is true it also checks if $input exclusively contains
* the given $keys.
*
* @usage __::hasKeys(['foo' => 'bar', 'foz' => 'baz'], ['foo', 'foz']);
* >> true
*
* @param array $collection of key values pairs
* @param array $keys collection of keys to look for
* @param boolean $strict to exclusively check
*
* @return boolean
*/
public static function hasKeys($collection = [], array $keys = [], bool $strict = false): bool
{
$keyCount = count($keys);
if ($strict && count($collection) !== $keyCount) {
return false;
}
return __::every(
__::map($keys, function ($key) use ($collection) {
return __::has($collection, $key);
}),
function ($v) {
return $v === true;
}
);
}
/**
* Return true if $collection contains the requested $key.
*
* In constraint to isset(), __::has() returns true if the key exists but is null.
*
* @usage __::has(['foo' => ['bar' => 'num'], 'foz' => 'baz'], 'foo.bar');
* >> true
*
* __::hasKeys((object) ['foo' => 'bar', 'foz' => 'baz'], 'bar');
* >> false
*
* @param array|object $collection of key values pairs
* @param string $path Path to look for.
*
* @return boolean
*/
public static function has($collection, $path): bool
{
$portions = __::split($path, '.', 2);
$key = $portions[0];
if (count($portions) === 1) {
return array_key_exists($key, (array)$collection);
}
return __::has(__::get($collection, $key), $portions[1]);
}
/**
* Combines and concat collections provided with each others.
*
* If the collections have common keys, then the values are appended in an array.
* If numerical indexes are passed, then values are appended.
*
* For a recursive merge, see __::merge.
*
* @usage __::concat(['color' => ['favorite' => 'red', 5], 3], [10, 'color' => ['favorite' => 'green', 'blue']]);
* >> ['color' => ['favorite' => ['green'], 5, 'blue'], 3, 10]
*
* @param array|object $collection1 Collection to assign to.
* @param array|object $collection2 Other collections to assign.
*
* @return array|object Assigned collection.
*/
public static function concat($collection1, $collection2)
{
$isObject = __::isObject($collection1);
$args = __::map(func_get_args(), function ($arg) {
return (array)$arg;
});
$merged = call_user_func_array('array_merge', $args);
return $isObject ? (object)$merged : $merged;
}
/**
* Recursively combines and concat collections provided with each others.
*
* If the collections have common keys, then the values are appended in an array.
* If numerical indexes are passed, then values are appended.
*
* For a non-recursive concat, see __::concat.
*
* @usage __::concatDeep(['color' => ['favorite' => 'red', 5], 3], [10, 'color' => ['favorite' => 'green',
* 'blue']]);
* >> ['color' => ['favorite' => ['red', 'green'], 5, 'blue'], 3, 10]
*
* @param array|object $collection1 First collection to concatDeep.
* @param array|object $collection2 other collections to concatDeep.
*
* @return array|object Concatenated collection.
*/
public static function concatDeep($collection1, $collection2)
{
return __::reduceRight(func_get_args(), function ($source, $result) {
__::doForEach($source, function ($sourceValue, $key) use (&$result) {
if (!__::has($result, $key)) {
$result = __::set($result, $key, $sourceValue);
} else {
if (is_numeric($key)) {
$result = __::concat($result, [$sourceValue]);
} else {
$resultValue = __::get($result, $key);
$result = __::set($result, $key, __::concatDeep(
__::isCollection($resultValue) ? $resultValue : (array)$resultValue,
__::isCollection($sourceValue) ? $sourceValue : (array)$sourceValue
));
}
}
});
return $result;
}, []);
}
/**
* Flattens a complex collection by mapping each ending leafs value to a key consisting of all previous indexes.
*
* @usage __::ease(['foo' => ['bar' => 'ter'], 'baz' => ['b', 'z']]);
* >> '['foo.bar' => 'ter', 'baz.0' => 'b', , 'baz.1' => 'z']'
*
* @param array $collection array of values
* @param string $glue glue between key path
*
* @return array flatten collection
*/
public static function ease(array $collection, string $glue = '.'): array
{
$map = [];
__::internalEase($map, $collection, $glue);
return $map;
}
/**
* Inner function for collections::ease
*
* @param array $map
* @param array $array
* @param string $glue
* @param string $prefix
*/
private static function internalEase(array &$map, array $array, string $glue, string $prefix = '')
{
foreach ($array as $index => $value) {
if (is_array($value)) {
__::internalEase($map, $value, $glue, $prefix . $index . $glue);
} else {
$map[$prefix . $index] = $value;
}
}
}
/**
* Checks if predicate returns truthy for all elements of collection.
*
* Iteration is stopped once predicate returns falsey.
* The predicate is invoked with three arguments: (value, index|key, collection).
*
* @usage __::every([1, 3, 4], function ($v) { return is_int($v); });
* >> true
*
* @param array|object $collection The collection to iterate over.
* @param \Closure $iterateFn The function to call for each value.
*
* @return bool
*/
public static function every($collection, Closure $iterateFn): bool
{
$truthy = true;
__::doForEach(
$collection,
function ($value, $key, $collection) use (&$truthy, $iterateFn) {
$truthy = $truthy && $iterateFn($value, $key, $collection);
if (!$truthy) {
return false;
}
}
);
return $truthy;
}
/**
* Returns an associative array where the keys are values of $key.
*
* @author Chauncey McAskill
* @link https://gist.github.com/mcaskill/baaee44487653e1afc0d array_group_by() function.
*
* @usage __::groupBy([
* ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
* ['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
* ['state' => 'CA', 'city' => 'Mountain View', 'object' => 'Space pen'],
* ], 'state');
* >> [
* 'IN' => [
* ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
* ['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
* ],
* 'CA' => [
* ['state' => 'CA', 'city' => 'Mountain View', 'object' => 'Space pen']
* ]
* ]
*
*
* __::groupBy([
* ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
* ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'Manhole'],
* ['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
* ],
* function ($value) {
* return $value->city;
* }
* );
* >> [
* 'Indianapolis' => [
* ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
* ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'Manhole'],
* ],
* 'San Diego' => [
* ['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
* ]
* ]
*
* @param array $array
* @param mixed $key
*
* @return array
*/
public static function groupBy(array $array, $key): array
{
if (!is_bool($key) && !is_scalar($key) && !is_callable($key)) {
return $array;
}
$grouped = [];
foreach ($array as $value) {
$groupKey = null;
if (is_callable($key)) {
$groupKey = call_user_func($key, $value);
} elseif (is_object($value) && property_exists($value, (string)$key)) {
$groupKey = $value->{$key};
} elseif (is_array($value) && isset($value[$key])) {
$groupKey = $value[$key];
}
if ($groupKey === null) {
continue;
}
$grouped[$groupKey][] = $value;
}
if (($argCnt = func_num_args()) > 2) {
$args = func_get_args();
foreach ($grouped as $_key => $value) {
$params = array_merge([$value], array_slice($args, 2, $argCnt));
$grouped[$_key] = call_user_func_array('\__::groupBy', $params);
}
}
return $grouped;
}
/**
* Check if value is an empty array or object. We consider any non enumerable as empty.
*
* @usage __::isEmpty([]);
* >> true
*
* @param mixed $value The value to check for emptiness.
*
* @return bool
*/
public static function isEmpty($value): bool
{
return (!__::isArray($value) && !__::isObject($value)) || count((array)$value) === 0;
}
/**
* Transforms the keys in a collection by running each key through the iterator
*
* @param array $array array of values
* @param \Closure $closure closure to map the keys
*
* @throws \Exception if closure doesn't return a valid key that can be used in PHP array
*
* @return array
*/
public static function mapKeys(array $array, Closure $closure = null): array
{
if (is_null($closure)) {
$closure = '__::identity';
}
$resultArray = [];
foreach ($array as $key => $value) {
$newKey = call_user_func_array($closure, [$key, $value, $array]);
// key must be a number or string
if (!is_numeric($newKey) && !is_string($newKey)) {
throw new Exception('closure must returns a number or string');
}
$resultArray[$newKey] = $value;
}
return $resultArray;
}
/**
* Transforms the values in a collection by running each value through the iterator
*
* @param array $array array of values
* @param \Closure $closure closure to map the values
*
* @return array
*/
public static function mapValues(array $array, Closure $closure = null): array
{
if (is_null($closure)) {
$closure = '__::identity';
}
$resultArray = [];
foreach ($array as $key => $value) {
$resultArray[$key] = call_user_func_array($closure, [$value, $key, $array]);
}
return $resultArray;
}
/**
* Recursively combines and merge collections provided with each others.
*
* If the collections have common keys, then the last passed keys override the previous.
* If numerical indexes are passed, then last passed indexes override the previous.
*
* For a non-recursive merge, see __::merge.
*
* @usage __::merge(['color' => ['favorite' => 'red', 'model' => 3, 5], 3], [10, 'color' => ['favorite' => 'green',
* 'blue']]);
* >> ['color' => ['favorite' => 'green', 'model' => 3, 'blue'], 10]
*
* @param array|object $collection1 First collection to merge.
* @param array|object $collection2 Other collections to merge.
*
* @return array|object Concatenated collection.
*/
public static function merge($collection1, $collection2)
{
return __::reduceRight(func_get_args(), function ($source, $result) {
__::doForEach($source, function ($sourceValue, $key) use (&$result) {
$value = $sourceValue;
if (__::isCollection($value)) {
$value = __::merge(__::get($result, $key), $sourceValue);
}
$result = __::set($result, $key, $value);
});
return $result;
}, []);
}
/**
* Returns an array having only keys present in the given path list. Values for missing keys values will be filled
* with provided default value.
*
* @usage __::pick(['a' => 1, 'b' => ['c' => 3, 'd' => 4]], ['a', 'b.d']);
* >> ['a' => 1, 'b' => ['d' => 4]]
*
* @param array|object $collection The collection to iterate over.
* @param array $paths array paths to pick
* @param null $default
*
* @return array|object
*/
public static function pick($collection = [], array $paths = [], $default = null)
{
return __::reduce($paths, function ($results, $path) use ($collection, $default) {
return __::set($results, $path, __::get($collection, $path, $default));
}, __::isObject($collection) ? new stdClass() : []);
}
/**
* Reduces $collection to a value which is the $accumulator result of running each
* element in $collection thru $iterateFn, where each successive invocation is supplied
* the return value of the previous.
*
* If $accumulator is not given, the first element of $collection is used as the
* initial value.
*
* The $iterateFn is invoked with four arguments:
* ($accumulator, $value, $index|$key, $collection).
*
* @usage __::reduce([1, 2], function ($sum, $number) {
* return $sum + $number;
* }, 0);
* >> 3
*
* $a = [
* ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
* ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'Manhole'],
* ['state' => 'IN', 'city' => 'Plainfield', 'object' => 'Basketball'],
* ['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
* ['state' => 'CA', 'city' => 'Mountain View', 'object' => 'Space pen'],
* ];
* $iterateFn = function ($accumulator, $value) {
* if (isset($accumulator[$value['city']]))
* $accumulator[$value['city']]++;
* else
* $accumulator[$value['city']] = 1;
* return $accumulator;
* };
* __::reduce($c, $iterateFn, []);
* >> [
* 'Indianapolis' => 2,
* 'Plainfield' => 1,
* 'San Diego' => 1,
* 'Mountain View' => 1,
* ]
*
* $object = new \stdClass();
* $object->a = 1;
* $object->b = 2;
* $object->c = 1;
* __::reduce($object, function ($result, $value, $key) {
* if (!isset($result[$value]))
* $result[$value] = [];
* $result[$value][] = $key;
* return $result;
* }, [])
* >> [
* '1' => ['a', 'c'],
* '2' => ['b']
* ]
*
* @param array $collection The collection to iterate over.
* @param \Closure $iterateFn The function invoked per iteration.
* @param array|null $accumulator
*
* @return array|mixed|null (*): Returns the accumulated value.
*/
public static function reduce($collection, Closure $iterateFn, $accumulator = null)
{
if ($accumulator === null) {
$accumulator = array_shift($collection);
}
__::doForEach(
$collection,
function ($value, $key, $collection) use (&$accumulator, $iterateFn) {
$accumulator = $iterateFn($accumulator, $value, $key, $collection);
}
);
return $accumulator;
}
/**
* Builds a multidimensional collection out of a hash map using the key as indicator where to put the value.
*
* @usage __::unease(['foo.bar' => 'ter', 'baz.0' => 'b', , 'baz.1' => 'z']);
* >> '['foo' => ['bar' => 'ter'], 'baz' => ['b', 'z']]'
*
* @param array $collection hash map of values
* @param string $separator the glue used in the keys
*
* @return array
* @throws \Exception
*/
public static function unease(array $collection, string $separator = '.'): array
{
$nonDefaultSeparator = $separator !== '.';
$map = [];
foreach ($collection as $key => $value) {
$map = __::set(
$map,
$nonDefaultSeparator ? str_replace($separator, '.', $key) : $key,
$value
);
}
return $map;
}
}