-
-
Notifications
You must be signed in to change notification settings - Fork 175
/
Copy pathCollection.php
1443 lines (1252 loc) · 30.1 KB
/
Collection.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
namespace Kirby\Toolkit;
use Closure;
use Countable;
use Exception;
/**
* The collection class provides a nicer
* interface around arrays of arrays or objects,
* with advanced filters, sorting, navigation and more.
*
* @package Kirby Toolkit
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*/
class Collection extends Iterator implements Countable
{
/**
* All registered collection filters
*
* @var array
*/
public static $filters = [];
/**
* Whether the collection keys should be
* treated as case-sensitive
*
* @todo 5.0 Check if case-sensitive can become the
* default mode, see https://github.com/getkirby/kirby/pull/5635
*
* @var bool
*/
protected $caseSensitive = false;
/**
* Pagination object
* @var \Kirby\Toolkit\Pagination
*/
protected $pagination;
/**
* Magic getter function
*
* @param string $key
* @param mixed $arguments
* @return mixed
*/
public function __call(string $key, $arguments)
{
return $this->__get($key);
}
/**
* Constructor
*
* @param array $data
* @param bool $caseSensitive Whether the collection keys should be
* treated as case-sensitive
*/
public function __construct(array $data = [], bool $caseSensitive = false)
{
$this->caseSensitive = $caseSensitive;
$this->set($data);
}
/**
* Improve var_dump() output
* @codeCoverageIgnore
*/
public function __debugInfo(): array
{
return $this->keys();
}
/**
* Low-level getter for elements
*
* @param mixed $key
* @return mixed
*/
public function __get($key)
{
if ($this->caseSensitive === true) {
return $this->data[$key] ?? null;
}
return $this->data[$key] ?? $this->data[strtolower($key)] ?? null;
}
/**
* Low-level setter for elements
*
* @param string $key string or array
*/
public function __set(string $key, $value): void
{
if ($this->caseSensitive !== true) {
$key = strtolower($key);
}
$this->data[$key] = $value;
}
/**
* Makes it possible to echo the entire object
*
* @return string
*/
public function __toString(): string
{
return $this->toString();
}
/**
* Low-level element remover
*
* @param mixed $key the name of the key
*/
public function __unset($key)
{
if ($this->caseSensitive !== true) {
$key = strtolower($key);
}
unset($this->data[$key]);
}
/**
* Appends an element
*
* @param mixed $key
* @param mixed $item
* @param mixed ...$args
* @return $this
*/
public function append(...$args)
{
if (count($args) === 1) {
$this->data[] = $args[0];
} elseif (count($args) > 1) {
$this->set($args[0], $args[1]);
}
return $this;
}
/**
* Creates chunks of the same size.
* The last chunk may be smaller
*
* @param int $size Number of elements per chunk
* @return static A new collection with an element for each chunk and
* a sub collection in each chunk
*/
public function chunk(int $size)
{
// create a multidimensional array that is chunked with the given
// chunk size keep keys of the elements
$chunks = array_chunk($this->data, $size, true);
// convert each chunk to a sub collection
$collection = [];
foreach ($chunks as $items) {
// we clone $this instead of creating a new object because
// different objects may have different constructors
$clone = clone $this;
$clone->data = $items;
$collection[] = $clone;
}
// convert the array of chunks to a collection
$result = clone $this;
$result->data = $collection;
return $result;
}
/**
* Returns a cloned instance of the collection
*
* @return $this
*/
public function clone()
{
return clone $this;
}
/**
* Getter and setter for the data
*
* @param array|null $data
* @return array|$this
*/
public function data(array|null $data = null)
{
if ($data === null) {
return $this->data;
}
// clear all previous data
$this->data = [];
// overwrite the data array
$this->data = $data;
return $this;
}
/**
* Clone and remove all elements from the collection
*
* @return static
*/
public function empty()
{
$collection = clone $this;
$collection->data = [];
return $collection;
}
/**
* Adds all elements to the collection
*
* @param mixed $items
* @return static
*/
public function extend($items)
{
$collection = clone $this;
return $collection->set($items);
}
/**
* Filters elements by one of the
* predefined filter methods, by a
* custom filter function or an array of filters
*
* @param string|array|\Closure $field
* @param mixed ...$args
* @return static
*/
public function filter($field, ...$args)
{
$operator = '==';
$test = $args[0] ?? null;
$split = $args[1] ?? false;
// filter by custom filter function
if (is_string($field) === false && is_callable($field) === true) {
$collection = clone $this;
$collection->data = array_filter($this->data, $field);
return $collection;
}
// array of filters
if (is_array($field) === true) {
$collection = $this;
foreach ($field as $filter) {
$collection = $collection->filter(...$filter);
}
return $collection;
}
if (
is_string($test) === true &&
isset(static::$filters[$test]) === true
) {
$operator = $test;
$test = $args[1] ?? null;
$split = $args[2] ?? false;
}
if (
is_object($test) === true &&
method_exists($test, '__toString') === true
) {
$test = (string)$test;
}
// get the filter from the filters array
$filter = static::$filters[$operator];
if (is_array($filter) === true) {
$collection = clone $this;
$validator = $filter['validator'];
$strict = $filter['strict'] ?? true;
$method = $strict ? 'filterMatchesAll' : 'filterMatchesAny';
foreach ($collection->data as $key => $item) {
$value = $collection->getAttribute($item, $field, $split);
if ($split !== false) {
if ($this->$method($validator, $value, $test) === false) {
unset($collection->data[$key]);
}
} elseif ($validator($value, $test) === false) {
unset($collection->data[$key]);
}
}
return $collection;
}
return $filter(clone $this, $field, $test, $split);
}
/**
* Alias for `Kirby\Toolkit\Collection::filter`
*
* @param string|array|\Closure $field
* @param mixed ...$args
* @return static
*/
public function filterBy(...$args)
{
return $this->filter(...$args);
}
protected function filterMatchesAny($validator, $values, $test): bool
{
foreach ($values as $value) {
if ($validator($value, $test) !== false) {
return true;
}
}
return false;
}
/**
* @param string $validator
* @param array $values
* @param mixed $test
* @return bool
*/
protected function filterMatchesAll($validator, $values, $test): bool
{
foreach ($values as $value) {
if ($validator($value, $test) === false) {
return false;
}
}
return true;
}
/**
* @param string $validator
* @param array $values
* @param mixed $test
* @return bool
*/
protected function filterMatchesNone($validator, $values, $test): bool
{
$matches = 0;
foreach ($values as $value) {
if ($validator($value, $test) !== false) {
$matches++;
}
}
return $matches === 0;
}
/**
* Find one or multiple elements by id
*
* @param string ...$keys
* @return mixed
*/
public function find(...$keys)
{
if (count($keys) === 1) {
if (is_array($keys[0]) === false) {
return $this->findByKey($keys[0]);
}
$keys = $keys[0];
}
$result = [];
foreach ($keys as $key) {
if ($item = $this->findByKey($key)) {
if (is_object($item) && method_exists($item, 'id') === true) {
$key = $item->id();
}
$result[$key] = $item;
}
}
$collection = clone $this;
$collection->data = $result;
return $collection;
}
/**
* Find a single element by an attribute and its value
*
* @param string $attribute
* @param mixed $value
* @return mixed|null
*/
public function findBy(string $attribute, $value)
{
foreach ($this->data as $item) {
if ($this->getAttribute($item, $attribute) == $value) {
return $item;
}
}
return null;
}
/**
* Find a single element by key (id)
*
* @param string $key
* @return mixed
*/
public function findByKey(string $key)
{
return $this->get($key);
}
/**
* Returns the first element
*
* @return mixed
*/
public function first()
{
$array = $this->data;
return array_shift($array);
}
/**
* Returns the elements in reverse order
*
* @return static
*/
public function flip()
{
$collection = clone $this;
$collection->data = array_reverse($this->data, true);
return $collection;
}
/**
* Getter
*
* @param mixed $key
* @param mixed $default
* @return mixed
*/
public function get($key, $default = null)
{
return $this->__get($key) ?? $default;
}
/**
* Extracts an attribute value from the given element
* in the collection. This is useful if elements in the collection
* might be objects, arrays or anything else and you need to
* get the value independently from that. We use it for `filter`.
*
* @param array|object $item
* @param string $attribute
* @param bool $split
* @param mixed $related
* @return mixed
*/
public function getAttribute($item, string $attribute, $split = false, $related = null)
{
$value = $this->{'getAttributeFrom' . gettype($item)}($item, $attribute);
if ($split !== false) {
return Str::split($value, $split === true ? ',' : $split);
}
if ($related !== null) {
return Str::toType((string)$value, $related);
}
return $value;
}
/**
* @param array $array
* @param string $attribute
* @return mixed
*/
protected function getAttributeFromArray(array $array, string $attribute)
{
return $array[$attribute] ?? null;
}
/**
* @param object $object
* @param string $attribute
* @return mixed
*/
protected function getAttributeFromObject($object, string $attribute)
{
return $object->{$attribute}();
}
/**
* Groups the elements by a given field or callback function
*
* @param string|Closure $field
* @return \Kirby\Toolkit\Collection A new collection with an element for
* each group and a subcollection in
* each group
* @throws \Exception if $field is not a string nor a callback function
*/
public function group($field, bool $caseInsensitive = true)
{
// group by field name
if (is_string($field) === true) {
return $this->group(function ($item) use ($field, $caseInsensitive) {
$value = $this->getAttribute($item, $field);
// ignore upper/lowercase for group names
if ($caseInsensitive === true) {
return Str::lower($value);
}
return (string)$value;
});
}
// group via callback function
if (is_callable($field) === true) {
$groups = [];
foreach ($this->data as $key => $item) {
// get the value to group by
$value = $field($item);
// make sure that there's always a proper value to group by
if (!$value) {
throw new Exception('Invalid grouping value for key: ' . $key);
}
// make sure we have a proper key for each group
if (is_array($value) === true) {
throw new Exception('You cannot group by arrays or objects');
}
if (is_object($value) === true) {
if (method_exists($value, '__toString') === false) {
throw new Exception('You cannot group by arrays or objects');
}
$value = (string)$value;
}
if (isset($groups[$value]) === false) {
// create a new entry for the group if it does not exist yet
$groups[$value] = new static([$key => $item]);
} else {
// add the element to an existing group
$groups[$value]->set($key, $item);
}
}
return new Collection($groups);
}
throw new Exception('Can only group by string values or by providing a callback function');
}
/**
* Alias for `Kirby\Toolkit\Collection::group`
*
* @param string|Closure $field
* @param bool $i
* @return \Kirby\Toolkit\Collection A new collection with an element for
* each group and a sub collection in
* each group
* @throws \Exception
*/
public function groupBy(...$args)
{
return $this->group(...$args);
}
/**
* Returns a Collection with the intersection of the given elements
* @since 3.3.0
*
* @param \Kirby\Toolkit\Collection $other
* @return static
*/
public function intersection($other)
{
return $other->find($this->keys());
}
/**
* Checks if there is an intersection between the given collection and this collection
* @since 3.3.0
*
* @param \Kirby\Toolkit\Collection $other
* @return bool
*/
public function intersects($other): bool
{
foreach ($this->keys() as $key) {
if ($other->has($key)) {
return true;
}
}
return false;
}
/**
* Checks if the number of elements is zero
*
* @return bool
*/
public function isEmpty(): bool
{
return $this->count() === 0;
}
/**
* Checks if the number of elements is even
*
* @return bool
*/
public function isEven(): bool
{
return $this->count() % 2 === 0;
}
/**
* Checks if the number of elements is more than zero
*
* @return bool
*/
public function isNotEmpty(): bool
{
return $this->count() > 0;
}
/**
* Checks if the number of elements is odd
*
* @return bool
*/
public function isOdd(): bool
{
return $this->count() % 2 !== 0;
}
/**
* Returns the last element
*
* @return mixed
*/
public function last()
{
$array = $this->data;
return array_pop($array);
}
/**
* Returns a new object with a limited number of elements
*
* @param int $limit The number of elements to return
* @return static
*/
public function limit(int $limit)
{
return $this->slice(0, $limit);
}
/**
* Map a function to each element
*
* @param callable $callback
* @return $this
*/
public function map(callable $callback)
{
$this->data = array_map($callback, $this->data);
return $this;
}
/**
* Returns the nth element from the collection
*
* @param int $n
* @return mixed
*/
public function nth(int $n)
{
return array_values($this->data)[$n] ?? null;
}
/**
* Returns a Collection without the given element(s)
*
* @param string ...$keys any number of keys, passed as individual arguments
* @return static
*/
public function not(...$keys)
{
$collection = clone $this;
foreach ($keys as $key) {
unset($collection->data[$key]);
}
return $collection;
}
/**
* Returns a new object starting from the given offset
*
* @param int $offset The index to start from
* @return static
*/
public function offset(int $offset)
{
return $this->slice($offset);
}
/**
* Add pagination
*
* @param array ...$arguments
* @return $this|static a sliced set of data
*/
public function paginate(...$arguments)
{
$this->pagination = Pagination::for($this, ...$arguments);
// slice and clone the collection according to the pagination
return $this->slice(
$this->pagination->offset(),
$this->pagination->limit()
);
}
/**
* Get the previously added pagination object
*
* @return \Kirby\Toolkit\Pagination|null
*/
public function pagination()
{
return $this->pagination;
}
/**
* Extracts all values for a single field into
* a new array
*
* @param string $field
* @param string|null $split
* @param bool $unique
* @return array
*/
public function pluck(string $field, string|null $split = null, bool $unique = false): array
{
$result = [];
foreach ($this->data as $item) {
$row = $this->getAttribute($item, $field);
if ($split !== null) {
$result = array_merge($result, Str::split($row, $split));
} else {
$result[] = $row;
}
}
if ($unique === true) {
$result = array_unique($result);
}
return array_values($result);
}
/**
* Prepends an element to the data array
*
* @param mixed $key
* @param mixed $item
* @param mixed ...$args
* @return $this
*/
public function prepend(...$args)
{
if (count($args) === 1) {
array_unshift($this->data, $args[0]);
} elseif (count($args) > 1) {
$data = $this->data;
$this->data = [];
$this->set($args[0], $args[1]);
$this->data += $data;
}
return $this;
}
/**
* Runs a combination of filter, sort, not,
* offset, limit and paginate on the collection.
* Any part of the query is optional.
*
* @param array $arguments
* @return static
*/
public function query(array $arguments = [])
{
$result = clone $this;
if (isset($arguments['not']) === true) {
$result = $result->not(...$arguments['not']);
}
if ($filters = $arguments['filterBy'] ?? $arguments['filter'] ?? null) {
foreach ($filters as $filter) {
if (
isset($filter['field']) === true &&
isset($filter['value']) === true
) {
$result = $result->filter(
$filter['field'],
$filter['operator'] ?? '==',
$filter['value']
);
}
}
}
if (isset($arguments['offset']) === true) {
$result = $result->offset($arguments['offset']);
}
if (isset($arguments['limit']) === true) {
$result = $result->limit($arguments['limit']);
}
if ($sort = $arguments['sortBy'] ?? $arguments['sort'] ?? null) {
if (is_array($sort)) {
$sort = explode(' ', implode(' ', $sort));
} else {
// if there are commas in the sort argument, removes it
if (Str::contains($sort, ',') === true) {
$sort = Str::replace($sort, ',', '');
}
$sort = explode(' ', $sort);
}
$result = $result->sort(...$sort);
}
if (isset($arguments['paginate']) === true) {
$result = $result->paginate($arguments['paginate']);
}
return $result;
}
/**
* Returns a new collection consisting of random elements,
* from the original collection, shuffled or ordered
*
* @param int $count
* @param bool $shuffle
* @return static
*/
public function random(int $count = 1, bool $shuffle = false)
{
if ($shuffle) {
return $this->shuffle()->slice(0, $count);
}
$collection = clone $this;
$collection->data = A::random($collection->data, $count);
return $collection;
}
/**
* Removes an element from the array by key
*
* @param mixed $key the name of the key
* @return $this
*/
public function remove($key)
{
$this->__unset($key);
return $this;
}
/**
* Adds a new element to the collection
*
* @param mixed $key string or array
* @param mixed $value
* @return $this
*/
public function set($key, $value = null)
{
if (is_array($key)) {
foreach ($key as $k => $v) {
$this->__set($k, $v);
}
} else {
$this->__set($key, $value);
}
return $this;
}
/**
* Shuffle all elements
*
* @return static
*/
public function shuffle()
{
$data = $this->data;
$keys = $this->keys();
shuffle($keys);
$collection = clone $this;
$collection->data = [];
foreach ($keys as $key) {
$collection->data[$key] = $data[$key];
}
return $collection;
}
/**
* Returns a slice of the object
*
* @param int $offset The optional index to start the slice from
* @param int|null $limit The optional number of elements to return
* @return $this|static
*/
public function slice(int $offset = 0, int|null $limit = null)
{
if ($offset === 0 && $limit === null) {
return $this;
}
$collection = clone $this;
$collection->data = array_slice($this->data, $offset, $limit);
return $collection;
}
/**
* Get sort arguments from a string
*
* @param string $sort
* @return array
*/
public static function sortArgs(string $sort): array
{
// if there are commas in the sortBy argument, removes it
if (Str::contains($sort, ',') === true) {
$sort = Str::replace($sort, ',', '');
}
$sortArgs = Str::split($sort, ' ');
// fill in PHP constants
array_walk($sortArgs, function (string &$value) {
if (Str::startsWith($value, 'SORT_') === true && defined($value) === true) {
$value = constant($value);
}
});
return $sortArgs;
}
/**
* Sorts the elements by any number of fields
*
* @param string|callable $field Field name or value callback to sort by
* @param string $direction asc or desc
* @param int $method The sort flag, SORT_REGULAR, SORT_NUMERIC etc.