-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathCollectionTrait.php
1033 lines (892 loc) · 27.7 KB
/
CollectionTrait.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
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Collection;
use AppendIterator;
use ArrayIterator;
use Cake\Collection\Iterator\BufferedIterator;
use Cake\Collection\Iterator\ExtractIterator;
use Cake\Collection\Iterator\FilterIterator;
use Cake\Collection\Iterator\InsertIterator;
use Cake\Collection\Iterator\MapReduce;
use Cake\Collection\Iterator\NestIterator;
use Cake\Collection\Iterator\ReplaceIterator;
use Cake\Collection\Iterator\SortIterator;
use Cake\Collection\Iterator\StoppableIterator;
use Cake\Collection\Iterator\TreeIterator;
use Cake\Collection\Iterator\UnfoldIterator;
use Cake\Collection\Iterator\ZipIterator;
use Countable;
use InvalidArgumentException;
use LimitIterator;
use LogicException;
use OuterIterator;
use RecursiveIteratorIterator;
use RuntimeException;
use Traversable;
/**
* Offers a handful of methods to manipulate iterators
*/
trait CollectionTrait
{
use ExtractTrait;
/**
* Returns a new collection.
*
* Allows classes which use this trait to determine their own
* type of returned collection interface
*
* @param mixed ...$args Constructor arguments.
* @return \Cake\Collection\CollectionInterface
*/
protected function newCollection(...$args): CollectionInterface
{
return new Collection(...$args);
}
/**
* @inheritDoc
*/
public function each(callable $callback)
{
foreach ($this->optimizeUnwrap() as $k => $v) {
$callback($v, $k);
}
return $this;
}
/**
* @inheritDoc
*/
public function filter(?callable $callback = null): CollectionInterface
{
if ($callback === null) {
$callback = function ($v) {
return (bool)$v;
};
}
return new FilterIterator($this->unwrap(), $callback);
}
/**
* @inheritDoc
*/
public function reject(callable $callback): CollectionInterface
{
return new FilterIterator($this->unwrap(), function ($key, $value, $items) use ($callback) {
return !$callback($key, $value, $items);
});
}
/**
* @inheritDoc
*/
public function every(callable $callback): bool
{
foreach ($this->optimizeUnwrap() as $key => $value) {
if (!$callback($value, $key)) {
return false;
}
}
return true;
}
/**
* @inheritDoc
*/
public function some(callable $callback): bool
{
foreach ($this->optimizeUnwrap() as $key => $value) {
if ($callback($value, $key) === true) {
return true;
}
}
return false;
}
/**
* @inheritDoc
*/
public function contains($value): bool
{
foreach ($this->optimizeUnwrap() as $v) {
if ($value === $v) {
return true;
}
}
return false;
}
/**
* @inheritDoc
*/
public function map(callable $callback): CollectionInterface
{
return new ReplaceIterator($this->unwrap(), $callback);
}
/**
* @inheritDoc
*/
public function reduce(callable $callback, $initial = null)
{
$isFirst = false;
if (func_num_args() < 2) {
$isFirst = true;
}
$result = $initial;
foreach ($this->optimizeUnwrap() as $k => $value) {
if ($isFirst) {
$result = $value;
$isFirst = false;
continue;
}
$result = $callback($result, $value, $k);
}
return $result;
}
/**
* @inheritDoc
*/
public function extract($path): CollectionInterface
{
$extractor = new ExtractIterator($this->unwrap(), $path);
if (is_string($path) && strpos($path, '{*}') !== false) {
$extractor = $extractor
->filter(function ($data) {
return $data !== null && ($data instanceof Traversable || is_array($data));
})
->unfold();
}
return $extractor;
}
/**
* @inheritDoc
*/
public function max($path, int $sort = \SORT_NUMERIC)
{
return (new SortIterator($this->unwrap(), $path, \SORT_DESC, $sort))->first();
}
/**
* @inheritDoc
*/
public function min($path, int $sort = \SORT_NUMERIC)
{
return (new SortIterator($this->unwrap(), $path, \SORT_ASC, $sort))->first();
}
/**
* @inheritDoc
*/
public function avg($path = null)
{
$result = $this;
if ($path !== null) {
$result = $result->extract($path);
}
$result = $result
->reduce(function ($acc, $current) {
[$count, $sum] = $acc;
return [$count + 1, $sum + $current];
}, [0, 0]);
if ($result[0] === 0) {
return null;
}
return $result[1] / $result[0];
}
/**
* @inheritDoc
*/
public function median($path = null)
{
$items = $this;
if ($path !== null) {
$items = $items->extract($path);
}
$values = $items->toList();
sort($values);
$count = count($values);
if ($count === 0) {
return null;
}
$middle = (int)($count / 2);
if ($count % 2) {
return $values[$middle];
}
return ($values[$middle - 1] + $values[$middle]) / 2;
}
/**
* @inheritDoc
*/
public function sortBy($path, int $order = \SORT_DESC, int $sort = \SORT_NUMERIC): CollectionInterface
{
return new SortIterator($this->unwrap(), $path, $order, $sort);
}
/**
* @inheritDoc
*/
public function groupBy($path): CollectionInterface
{
$callback = $this->_propertyExtractor($path);
$group = [];
foreach ($this->optimizeUnwrap() as $value) {
$pathValue = $callback($value);
if ($pathValue === null) {
throw new InvalidArgumentException(
'Cannot group by path that does not exist or contains a null value. ' .
'Use a callback to return a default value for that path.'
);
}
$group[$pathValue][] = $value;
}
return $this->newCollection($group);
}
/**
* @inheritDoc
*/
public function indexBy($path): CollectionInterface
{
$callback = $this->_propertyExtractor($path);
$group = [];
foreach ($this->optimizeUnwrap() as $value) {
$pathValue = $callback($value);
if ($pathValue === null) {
throw new InvalidArgumentException(
'Cannot index by path that does not exist or contains a null value. ' .
'Use a callback to return a default value for that path.'
);
}
$group[$pathValue] = $value;
}
return $this->newCollection($group);
}
/**
* @inheritDoc
*/
public function countBy($path): CollectionInterface
{
$callback = $this->_propertyExtractor($path);
$mapper = function ($value, $key, $mr) use ($callback): void {
/** @var \Cake\Collection\Iterator\MapReduce $mr */
$mr->emitIntermediate($value, $callback($value));
};
$reducer = function ($values, $key, $mr): void {
/** @var \Cake\Collection\Iterator\MapReduce $mr */
$mr->emit(count($values), $key);
};
return $this->newCollection(new MapReduce($this->unwrap(), $mapper, $reducer));
}
/**
* @inheritDoc
*/
public function sumOf($path = null)
{
if ($path === null) {
return array_sum($this->toList());
}
$callback = $this->_propertyExtractor($path);
$sum = 0;
foreach ($this->optimizeUnwrap() as $k => $v) {
$sum += $callback($v, $k);
}
return $sum;
}
/**
* @inheritDoc
*/
public function shuffle(): CollectionInterface
{
$items = $this->toList();
shuffle($items);
return $this->newCollection($items);
}
/**
* @inheritDoc
*/
public function sample(int $length = 10): CollectionInterface
{
return $this->newCollection(new LimitIterator($this->shuffle(), 0, $length));
}
/**
* @inheritDoc
*/
public function take(int $length = 1, int $offset = 0): CollectionInterface
{
return $this->newCollection(new LimitIterator($this, $offset, $length));
}
/**
* @inheritDoc
*/
public function skip(int $length): CollectionInterface
{
return $this->newCollection(new LimitIterator($this, $length));
}
/**
* @inheritDoc
*/
public function match(array $conditions): CollectionInterface
{
return $this->filter($this->_createMatcherFilter($conditions));
}
/**
* @inheritDoc
*/
public function firstMatch(array $conditions)
{
return $this->match($conditions)->first();
}
/**
* @inheritDoc
*/
public function first()
{
$iterator = new LimitIterator($this, 0, 1);
foreach ($iterator as $result) {
return $result;
}
}
/**
* @inheritDoc
*/
public function last()
{
$iterator = $this->optimizeUnwrap();
if (is_array($iterator)) {
return array_pop($iterator);
}
if ($iterator instanceof Countable) {
$count = count($iterator);
if ($count === 0) {
return null;
}
/** @var iterable $iterator */
$iterator = new LimitIterator($iterator, $count - 1, 1);
}
$result = null;
foreach ($iterator as $result) {
// No-op
}
return $result;
}
/**
* @inheritDoc
*/
public function takeLast(int $length): CollectionInterface
{
if ($length < 1) {
throw new InvalidArgumentException('The takeLast method requires a number greater than 0.');
}
$iterator = $this->optimizeUnwrap();
if (is_array($iterator)) {
return $this->newCollection(array_slice($iterator, $length * -1));
}
if ($iterator instanceof Countable) {
$count = count($iterator);
if ($count === 0) {
return $this->newCollection([]);
}
$iterator = new LimitIterator($iterator, max(0, $count - $length), $length);
return $this->newCollection($iterator);
}
$generator = function ($iterator, $length) {
$result = [];
$bucket = 0;
$offset = 0;
/**
* Consider the collection of elements [1, 2, 3, 4, 5, 6, 7, 8, 9], in order
* to get the last 4 elements, we can keep a buffer of 4 elements and
* fill it circularly using modulo logic, we use the $bucket variable
* to track the position to fill next in the buffer. This how the buffer
* looks like after 4 iterations:
*
* 0) 1 2 3 4 -- $bucket now goes back to 0, we have filled 4 elementes
* 1) 5 2 3 4 -- 5th iteration
* 2) 5 6 3 4 -- 6th iteration
* 3) 5 6 7 4 -- 7th iteration
* 4) 5 6 7 8 -- 8th iteration
* 5) 9 6 7 8
*
* We can see that at the end of the iterations, the buffer contains all
* the last four elements, just in the wrong order. How do we keep the
* original order? Well, it turns out that the number of iteration also
* give us a clue on what's going on, Let's add a marker for it now:
*
* 0) 1 2 3 4
* ^ -- The 0) above now becomes the $offset variable
* 1) 5 2 3 4
* ^ -- $offset = 1
* 2) 5 6 3 4
* ^ -- $offset = 2
* 3) 5 6 7 4
* ^ -- $offset = 3
* 4) 5 6 7 8
* ^ -- We use module logic for $offset too
* and as you can see each time $offset is 0, then the buffer
* is sorted exactly as we need.
* 5) 9 6 7 8
* ^ -- $offset = 1
*
* The $offset variable is a marker for splitting the buffer in two,
* elements to the right for the marker are the head of the final result,
* whereas the elements at the left are the tail. For example consider step 5)
* which has an offset of 1:
*
* - $head = elements to the right = [6, 7, 8]
* - $tail = elements to the left = [9]
* - $result = $head + $tail = [6, 7, 8, 9]
*
* The logic above applies to collections of any size.
*/
foreach ($iterator as $k => $item) {
$result[$bucket] = [$k, $item];
$bucket = (++$bucket) % $length;
$offset++;
}
$offset = $offset % $length;
$head = array_slice($result, $offset);
$tail = array_slice($result, 0, $offset);
foreach ($head as $v) {
yield $v[0] => $v[1];
}
foreach ($tail as $v) {
yield $v[0] => $v[1];
}
};
return $this->newCollection($generator($iterator, $length));
}
/**
* @inheritDoc
*/
public function append($items): CollectionInterface
{
$list = new AppendIterator();
$list->append($this->unwrap());
$list->append($this->newCollection($items)->unwrap());
return $this->newCollection($list);
}
/**
* @inheritDoc
*/
public function appendItem($item, $key = null): CollectionInterface
{
if ($key !== null) {
$data = [$key => $item];
} else {
$data = [$item];
}
return $this->append($data);
}
/**
* @inheritDoc
*/
public function prepend($items): CollectionInterface
{
return $this->newCollection($items)->append($this);
}
/**
* @inheritDoc
*/
public function prependItem($item, $key = null): CollectionInterface
{
if ($key !== null) {
$data = [$key => $item];
} else {
$data = [$item];
}
return $this->prepend($data);
}
/**
* @inheritDoc
*/
public function combine($keyPath, $valuePath, $groupPath = null): CollectionInterface
{
$options = [
'keyPath' => $this->_propertyExtractor($keyPath),
'valuePath' => $this->_propertyExtractor($valuePath),
'groupPath' => $groupPath ? $this->_propertyExtractor($groupPath) : null,
];
$mapper = function ($value, $key, MapReduce $mapReduce) use ($options) {
$rowKey = $options['keyPath'];
$rowVal = $options['valuePath'];
if (!$options['groupPath']) {
$mapReduce->emit($rowVal($value, $key), $rowKey($value, $key));
return null;
}
$key = $options['groupPath']($value, $key);
$mapReduce->emitIntermediate(
[$rowKey($value, $key) => $rowVal($value, $key)],
$key
);
};
$reducer = function ($values, $key, MapReduce $mapReduce): void {
$result = [];
foreach ($values as $value) {
$result += $value;
}
$mapReduce->emit($result, $key);
};
return $this->newCollection(new MapReduce($this->unwrap(), $mapper, $reducer));
}
/**
* @inheritDoc
*/
public function nest($idPath, $parentPath, string $nestingKey = 'children'): CollectionInterface
{
$parents = [];
$idPath = $this->_propertyExtractor($idPath);
$parentPath = $this->_propertyExtractor($parentPath);
$isObject = true;
$mapper = function ($row, $key, MapReduce $mapReduce) use (&$parents, $idPath, $parentPath, $nestingKey): void {
$row[$nestingKey] = [];
$id = $idPath($row, $key);
$parentId = $parentPath($row, $key);
$parents[$id] = &$row;
$mapReduce->emitIntermediate($id, $parentId);
};
$reducer = function ($values, $key, MapReduce $mapReduce) use (&$parents, &$isObject, $nestingKey) {
static $foundOutType = false;
if (!$foundOutType) {
$isObject = is_object(current($parents));
$foundOutType = true;
}
if (empty($key) || !isset($parents[$key])) {
foreach ($values as $id) {
/** @psalm-suppress PossiblyInvalidArgument */
$parents[$id] = $isObject ? $parents[$id] : new ArrayIterator($parents[$id], 1);
$mapReduce->emit($parents[$id]);
}
return null;
}
$children = [];
foreach ($values as $id) {
$children[] = &$parents[$id];
}
$parents[$key][$nestingKey] = $children;
};
return $this->newCollection(new MapReduce($this->unwrap(), $mapper, $reducer))
->map(function ($value) use (&$isObject) {
/** @var \ArrayIterator $value */
return $isObject ? $value : $value->getArrayCopy();
});
}
/**
* @inheritDoc
*/
public function insert(string $path, $values): CollectionInterface
{
return new InsertIterator($this->unwrap(), $path, $values);
}
/**
* @inheritDoc
*/
public function toArray(bool $preserveKeys = true): array
{
$iterator = $this->unwrap();
if ($iterator instanceof ArrayIterator) {
$items = $iterator->getArrayCopy();
return $preserveKeys ? $items : array_values($items);
}
// RecursiveIteratorIterator can return duplicate key values causing
// data loss when converted into an array
if ($preserveKeys && get_class($iterator) === RecursiveIteratorIterator::class) {
$preserveKeys = false;
}
return iterator_to_array($this, $preserveKeys);
}
/**
* @inheritDoc
*/
public function toList(): array
{
return $this->toArray(false);
}
/**
* @inheritDoc
*/
public function jsonSerialize(): array
{
return $this->toArray();
}
/**
* @inheritDoc
*/
public function compile(bool $preserveKeys = true): CollectionInterface
{
return $this->newCollection($this->toArray($preserveKeys));
}
/**
* @inheritDoc
*/
public function lazy(): CollectionInterface
{
$generator = function () {
foreach ($this->unwrap() as $k => $v) {
yield $k => $v;
}
};
return $this->newCollection($generator());
}
/**
* @inheritDoc
*/
public function buffered(): CollectionInterface
{
return new BufferedIterator($this->unwrap());
}
/**
* @inheritDoc
*/
public function listNested($order = 'desc', $nestingKey = 'children'): CollectionInterface
{
if (is_string($order)) {
$order = strtolower($order);
$modes = [
'desc' => RecursiveIteratorIterator::SELF_FIRST,
'asc' => RecursiveIteratorIterator::CHILD_FIRST,
'leaves' => RecursiveIteratorIterator::LEAVES_ONLY,
];
if (!isset($modes[$order])) {
throw new RuntimeException(sprintf(
"Invalid direction `%s` provided. Must be one of: 'desc', 'asc', 'leaves'",
$order
));
}
$order = $modes[$order];
}
return new TreeIterator(
new NestIterator($this, $nestingKey),
$order
);
}
/**
* @inheritDoc
*/
public function stopWhen($condition): CollectionInterface
{
if (!is_callable($condition)) {
$condition = $this->_createMatcherFilter($condition);
}
return new StoppableIterator($this->unwrap(), $condition);
}
/**
* @inheritDoc
*/
public function unfold(?callable $callback = null): CollectionInterface
{
if ($callback === null) {
$callback = function ($item) {
return $item;
};
}
return $this->newCollection(
new RecursiveIteratorIterator(
new UnfoldIterator($this->unwrap(), $callback),
RecursiveIteratorIterator::LEAVES_ONLY
)
);
}
/**
* @inheritDoc
*/
public function through(callable $callback): CollectionInterface
{
$result = $callback($this);
return $result instanceof CollectionInterface ? $result : $this->newCollection($result);
}
/**
* @inheritDoc
*/
public function zip(iterable $items): CollectionInterface
{
return new ZipIterator(array_merge([$this->unwrap()], func_get_args()));
}
/**
* @inheritDoc
*/
public function zipWith(iterable $items, $callback): CollectionInterface
{
if (func_num_args() > 2) {
$items = func_get_args();
$callback = array_pop($items);
} else {
$items = [$items];
}
return new ZipIterator(array_merge([$this->unwrap()], $items), $callback);
}
/**
* @inheritDoc
*/
public function chunk(int $chunkSize): CollectionInterface
{
return $this->map(function ($v, $k, $iterator) use ($chunkSize) {
$values = [$v];
for ($i = 1; $i < $chunkSize; $i++) {
$iterator->next();
if (!$iterator->valid()) {
break;
}
$values[] = $iterator->current();
}
return $values;
});
}
/**
* @inheritDoc
*/
public function chunkWithKeys(int $chunkSize, bool $preserveKeys = true): CollectionInterface
{
return $this->map(function ($v, $k, $iterator) use ($chunkSize, $preserveKeys) {
$key = 0;
if ($preserveKeys) {
$key = $k;
}
$values = [$key => $v];
for ($i = 1; $i < $chunkSize; $i++) {
$iterator->next();
if (!$iterator->valid()) {
break;
}
if ($preserveKeys) {
$values[$iterator->key()] = $iterator->current();
} else {
$values[] = $iterator->current();
}
}
return $values;
});
}
/**
* @inheritDoc
*/
public function isEmpty(): bool
{
foreach ($this as $el) {
return false;
}
return true;
}
/**
* @inheritDoc
*/
public function unwrap(): Traversable
{
$iterator = $this;
while (
get_class($iterator) === Collection::class
&& $iterator instanceof OuterIterator
) {
$iterator = $iterator->getInnerIterator();
}
if ($iterator !== $this && $iterator instanceof CollectionInterface) {
$iterator = $iterator->unwrap();
}
return $iterator;
}
/**
* {@inheritDoc}
*
* @param callable|null $operation A callable that allows you to customize the product result.
* @param callable|null $filter A filtering callback that must return true for a result to be part
* of the final results.
* @return \Cake\Collection\CollectionInterface
* @throws \LogicException
*/
public function cartesianProduct(?callable $operation = null, ?callable $filter = null): CollectionInterface
{
if ($this->isEmpty()) {
return $this->newCollection([]);
}
$collectionArrays = [];
$collectionArraysKeys = [];
$collectionArraysCounts = [];
foreach ($this->toList() as $value) {
$valueCount = count($value);
if ($valueCount !== count($value, COUNT_RECURSIVE)) {
throw new LogicException('Cannot find the cartesian product of a multidimensional array');
}
$collectionArraysKeys[] = array_keys($value);
$collectionArraysCounts[] = $valueCount;
$collectionArrays[] = $value;
}
$result = [];
$lastIndex = count($collectionArrays) - 1;
// holds the indexes of the arrays that generate the current combination
$currentIndexes = array_fill(0, $lastIndex + 1, 0);
$changeIndex = $lastIndex;
while (!($changeIndex === 0 && $currentIndexes[0] === $collectionArraysCounts[0])) {
$currentCombination = array_map(function ($value, $keys, $index) {
return $value[$keys[$index]];
}, $collectionArrays, $collectionArraysKeys, $currentIndexes);
if ($filter === null || $filter($currentCombination)) {
$result[] = $operation === null ? $currentCombination : $operation($currentCombination);
}
$currentIndexes[$lastIndex]++;
for (
$changeIndex = $lastIndex;
$currentIndexes[$changeIndex] === $collectionArraysCounts[$changeIndex] && $changeIndex > 0;
$changeIndex--
) {
$currentIndexes[$changeIndex] = 0;
$currentIndexes[$changeIndex - 1]++;
}
}
return $this->newCollection($result);
}
/**
* {@inheritDoc}
*
* @return \Cake\Collection\CollectionInterface
* @throws \LogicException
*/
public function transpose(): CollectionInterface
{
$arrayValue = $this->toList();
$length = count(current($arrayValue));
$result = [];
foreach ($arrayValue as $row) {
if (count($row) !== $length) {
throw new LogicException('Child arrays do not have even length');
}
}
for ($column = 0; $column < $length; $column++) {
$result[] = array_column($arrayValue, $column);
}
return $this->newCollection($result);
}
/**
* @inheritDoc
*/
public function count(): int
{
$traversable = $this->optimizeUnwrap();