1: <?php
2: /**
3: * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
4: * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
5: *
6: * Licensed under The MIT License
7: * For full copyright and license information, please see the LICENSE.txt
8: * Redistributions of files must retain the above copyright notice.
9: *
10: * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
11: * @link https://cakephp.org CakePHP(tm) Project
12: * @since 3.0.0
13: * @license https://opensource.org/licenses/mit-license.php MIT License
14: */
15: namespace Cake\Collection;
16:
17: use Iterator;
18: use JsonSerializable;
19:
20: /**
21: * Describes the methods a Collection should implement. A collection is an immutable
22: * list of elements exposing a number of traversing and extracting method for
23: * generating other collections.
24: *
25: * @method \Cake\Collection\CollectionInterface cartesianProduct(callable $operation = null, callable $filter = null)
26: */
27: interface CollectionInterface extends Iterator, JsonSerializable
28: {
29:
30: /**
31: * Executes the passed callable for each of the elements in this collection
32: * and passes both the value and key for them on each step.
33: * Returns the same collection for chaining.
34: *
35: * ### Example:
36: *
37: * ```
38: * $collection = (new Collection($items))->each(function ($value, $key) {
39: * echo "Element $key: $value";
40: * });
41: * ```
42: *
43: * @param callable $c callable function that will receive each of the elements
44: * in this collection
45: * @return \Cake\Collection\CollectionInterface
46: */
47: public function each(callable $c);
48:
49: /**
50: * Looks through each value in the collection, and returns another collection with
51: * all the values that pass a truth test. Only the values for which the callback
52: * returns true will be present in the resulting collection.
53: *
54: * Each time the callback is executed it will receive the value of the element
55: * in the current iteration, the key of the element and this collection as
56: * arguments, in that order.
57: *
58: * ### Example:
59: *
60: * Filtering odd numbers in an array, at the end only the value 2 will
61: * be present in the resulting collection:
62: *
63: * ```
64: * $collection = (new Collection([1, 2, 3]))->filter(function ($value, $key) {
65: * return $value % 2 === 0;
66: * });
67: * ```
68: *
69: * @param callable|null $c the method that will receive each of the elements and
70: * returns true whether or not they should be in the resulting collection.
71: * If left null, a callback that filters out falsey values will be used.
72: * @return \Cake\Collection\CollectionInterface
73: */
74: public function filter(callable $c = null);
75:
76: /**
77: * Looks through each value in the collection, and returns another collection with
78: * all the values that do not pass a truth test. This is the opposite of `filter`.
79: *
80: * Each time the callback is executed it will receive the value of the element
81: * in the current iteration, the key of the element and this collection as
82: * arguments, in that order.
83: *
84: * ### Example:
85: *
86: * Filtering even numbers in an array, at the end only values 1 and 3 will
87: * be present in the resulting collection:
88: *
89: * ```
90: * $collection = (new Collection([1, 2, 3]))->reject(function ($value, $key) {
91: * return $value % 2 === 0;
92: * });
93: * ```
94: *
95: * @param callable $c the method that will receive each of the elements and
96: * returns true whether or not they should be out of the resulting collection.
97: * @return \Cake\Collection\CollectionInterface
98: */
99: public function reject(callable $c);
100:
101: /**
102: * Returns true if all values in this collection pass the truth test provided
103: * in the callback.
104: *
105: * Each time the callback is executed it will receive the value of the element
106: * in the current iteration and the key of the element as arguments, in that
107: * order.
108: *
109: * ### Example:
110: *
111: * ```
112: * $overTwentyOne = (new Collection([24, 45, 60, 15]))->every(function ($value, $key) {
113: * return $value > 21;
114: * });
115: * ```
116: *
117: * Empty collections always return true because it is a vacuous truth.
118: *
119: * @param callable $c a callback function
120: * @return bool true if for all elements in this collection the provided
121: * callback returns true, false otherwise.
122: */
123: public function every(callable $c);
124:
125: /**
126: * Returns true if any of the values in this collection pass the truth test
127: * provided in the callback.
128: *
129: * Each time the callback is executed it will receive the value of the element
130: * in the current iteration and the key of the element as arguments, in that
131: * order.
132: *
133: * ### Example:
134: *
135: * ```
136: * $hasYoungPeople = (new Collection([24, 45, 15]))->every(function ($value, $key) {
137: * return $value < 21;
138: * });
139: * ```
140: *
141: * @param callable $c a callback function
142: * @return bool true if the provided callback returns true for any element in this
143: * collection, false otherwise
144: */
145: public function some(callable $c);
146:
147: /**
148: * Returns true if $value is present in this collection. Comparisons are made
149: * both by value and type.
150: *
151: * @param mixed $value The value to check for
152: * @return bool true if $value is present in this collection
153: */
154: public function contains($value);
155:
156: /**
157: * Returns another collection after modifying each of the values in this one using
158: * the provided callable.
159: *
160: * Each time the callback is executed it will receive the value of the element
161: * in the current iteration, the key of the element and this collection as
162: * arguments, in that order.
163: *
164: * ### Example:
165: *
166: * Getting a collection of booleans where true indicates if a person is female:
167: *
168: * ```
169: * $collection = (new Collection($people))->map(function ($person, $key) {
170: * return $person->gender === 'female';
171: * });
172: * ```
173: *
174: * @param callable $c the method that will receive each of the elements and
175: * returns the new value for the key that is being iterated
176: * @return \Cake\Collection\CollectionInterface
177: */
178: public function map(callable $c);
179:
180: /**
181: * Folds the values in this collection to a single value, as the result of
182: * applying the callback function to all elements. $zero is the initial state
183: * of the reduction, and each successive step of it should be returned
184: * by the callback function.
185: * If $zero is omitted the first value of the collection will be used in its place
186: * and reduction will start from the second item.
187: *
188: * @param callable $c The callback function to be called
189: * @param mixed $zero The state of reduction
190: * @return mixed
191: */
192: public function reduce(callable $c, $zero = null);
193:
194: /**
195: * Returns a new collection containing the column or property value found in each
196: * of the elements, as requested in the $matcher param.
197: *
198: * The matcher can be a string with a property name to extract or a dot separated
199: * path of properties that should be followed to get the last one in the path.
200: *
201: * If a column or property could not be found for a particular element in the
202: * collection, that position is filled with null.
203: *
204: * ### Example:
205: *
206: * Extract the user name for all comments in the array:
207: *
208: * ```
209: * $items = [
210: * ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
211: * ['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
212: * ];
213: * $extracted = (new Collection($items))->extract('comment.user.name');
214: *
215: * // Result will look like this when converted to array
216: * ['Mark', 'Renan']
217: * ```
218: *
219: * It is also possible to extract a flattened collection out of nested properties
220: *
221: * ```
222: * $items = [
223: * ['comment' => ['votes' => [['value' => 1], ['value' => 2], ['value' => 3]]],
224: * ['comment' => ['votes' => [['value' => 4]]
225: * ];
226: * $extracted = (new Collection($items))->extract('comment.votes.{*}.value');
227: *
228: * // Result will contain
229: * [1, 2, 3, 4]
230: * ```
231: *
232: * @param string $matcher a dot separated string symbolizing the path to follow
233: * inside the hierarchy of each value so that the column can be extracted.
234: * @return \Cake\Collection\CollectionInterface
235: */
236: public function extract($matcher);
237:
238: /**
239: * Returns the top element in this collection after being sorted by a property.
240: * Check the sortBy method for information on the callback and $type parameters
241: *
242: * ### Examples:
243: *
244: * ```
245: * // For a collection of employees
246: * $max = $collection->max('age');
247: * $max = $collection->max('user.salary');
248: * $max = $collection->max(function ($e) {
249: * return $e->get('user')->get('salary');
250: * });
251: *
252: * // Display employee name
253: * echo $max->name;
254: * ```
255: *
256: * @param callable|string $callback the callback or column name to use for sorting
257: * @param int $type the type of comparison to perform, either SORT_STRING
258: * SORT_NUMERIC or SORT_NATURAL
259: * @see \Cake\Collection\CollectionIterface::sortBy()
260: * @return mixed The value of the top element in the collection
261: */
262: public function max($callback, $type = \SORT_NUMERIC);
263:
264: /**
265: * Returns the bottom element in this collection after being sorted by a property.
266: * Check the sortBy method for information on the callback and $type parameters
267: *
268: * ### Examples:
269: *
270: * ```
271: * // For a collection of employees
272: * $min = $collection->min('age');
273: * $min = $collection->min('user.salary');
274: * $min = $collection->min(function ($e) {
275: * return $e->get('user')->get('salary');
276: * });
277: *
278: * // Display employee name
279: * echo $min->name;
280: * ```
281: *
282: * @param callable|string $callback the callback or column name to use for sorting
283: * @param int $type the type of comparison to perform, either SORT_STRING
284: * SORT_NUMERIC or SORT_NATURAL
285: * @see \Cake\Collection\CollectionInterface::sortBy()
286: * @return mixed The value of the bottom element in the collection
287: */
288: public function min($callback, $type = \SORT_NUMERIC);
289:
290: /**
291: * Returns the average of all the values extracted with $matcher
292: * or of this collection.
293: *
294: * ### Example:
295: *
296: * ```
297: * $items = [
298: * ['invoice' => ['total' => 100]],
299: * ['invoice' => ['total' => 200]]
300: * ];
301: *
302: * $total = (new Collection($items))->avg('invoice.total');
303: *
304: * // Total: 150
305: *
306: * $total = (new Collection([1, 2, 3]))->avg();
307: * // Total: 2
308: * ```
309: *
310: * @param string|callable|null $matcher The property name to sum or a function
311: * If no value is passed, an identity function will be used.
312: * that will return the value of the property to sum.
313: * @return float|int|null
314: */
315: public function avg($matcher = null);
316:
317: /**
318: * Returns the median of all the values extracted with $matcher
319: * or of this collection.
320: *
321: * ### Example:
322: *
323: * ```
324: * $items = [
325: * ['invoice' => ['total' => 400]],
326: * ['invoice' => ['total' => 500]]
327: * ['invoice' => ['total' => 100]]
328: * ['invoice' => ['total' => 333]]
329: * ['invoice' => ['total' => 200]]
330: * ];
331: *
332: * $total = (new Collection($items))->median('invoice.total');
333: *
334: * // Total: 333
335: *
336: * $total = (new Collection([1, 2, 3, 4]))->median();
337: * // Total: 2.5
338: * ```
339: *
340: * @param string|callable|null $matcher The property name to sum or a function
341: * If no value is passed, an identity function will be used.
342: * that will return the value of the property to sum.
343: * @return float|int|null
344: */
345: public function median($matcher = null);
346:
347: /**
348: * Returns a sorted iterator out of the elements in this collection,
349: * ranked in ascending order by the results of running each value through a
350: * callback. $callback can also be a string representing the column or property
351: * name.
352: *
353: * The callback will receive as its first argument each of the elements in $items,
354: * the value returned by the callback will be used as the value for sorting such
355: * element. Please note that the callback function could be called more than once
356: * per element.
357: *
358: * ### Example:
359: *
360: * ```
361: * $items = $collection->sortBy(function ($user) {
362: * return $user->age;
363: * });
364: *
365: * // alternatively
366: * $items = $collection->sortBy('age');
367: *
368: * // or use a property path
369: * $items = $collection->sortBy('department.name');
370: *
371: * // output all user name order by their age in descending order
372: * foreach ($items as $user) {
373: * echo $user->name;
374: * }
375: * ```
376: *
377: * @param callable|string $callback the callback or column name to use for sorting
378: * @param int $dir either SORT_DESC or SORT_ASC
379: * @param int $type the type of comparison to perform, either SORT_STRING
380: * SORT_NUMERIC or SORT_NATURAL
381: * @return \Cake\Collection\CollectionInterface
382: */
383: public function sortBy($callback, $dir = SORT_DESC, $type = \SORT_NUMERIC);
384:
385: /**
386: * Splits a collection into sets, grouped by the result of running each value
387: * through the callback. If $callback is a string instead of a callable,
388: * groups by the property named by $callback on each of the values.
389: *
390: * When $callback is a string it should be a property name to extract or
391: * a dot separated path of properties that should be followed to get the last
392: * one in the path.
393: *
394: * ### Example:
395: *
396: * ```
397: * $items = [
398: * ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
399: * ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
400: * ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
401: * ];
402: *
403: * $group = (new Collection($items))->groupBy('parent_id');
404: *
405: * // Or
406: * $group = (new Collection($items))->groupBy(function ($e) {
407: * return $e['parent_id'];
408: * });
409: *
410: * // Result will look like this when converted to array
411: * [
412: * 10 => [
413: * ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
414: * ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
415: * ],
416: * 11 => [
417: * ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
418: * ]
419: * ];
420: * ```
421: *
422: * @param callable|string $callback the callback or column name to use for grouping
423: * or a function returning the grouping key out of the provided element
424: * @return \Cake\Collection\CollectionInterface
425: */
426: public function groupBy($callback);
427:
428: /**
429: * Given a list and a callback function that returns a key for each element
430: * in the list (or a property name), returns an object with an index of each item.
431: * Just like groupBy, but for when you know your keys are unique.
432: *
433: * When $callback is a string it should be a property name to extract or
434: * a dot separated path of properties that should be followed to get the last
435: * one in the path.
436: *
437: * ### Example:
438: *
439: * ```
440: * $items = [
441: * ['id' => 1, 'name' => 'foo'],
442: * ['id' => 2, 'name' => 'bar'],
443: * ['id' => 3, 'name' => 'baz'],
444: * ];
445: *
446: * $indexed = (new Collection($items))->indexBy('id');
447: *
448: * // Or
449: * $indexed = (new Collection($items))->indexBy(function ($e) {
450: * return $e['id'];
451: * });
452: *
453: * // Result will look like this when converted to array
454: * [
455: * 1 => ['id' => 1, 'name' => 'foo'],
456: * 3 => ['id' => 3, 'name' => 'baz'],
457: * 2 => ['id' => 2, 'name' => 'bar'],
458: * ];
459: * ```
460: *
461: * @param callable|string $callback the callback or column name to use for indexing
462: * or a function returning the indexing key out of the provided element
463: * @return \Cake\Collection\CollectionInterface
464: */
465: public function indexBy($callback);
466:
467: /**
468: * Sorts a list into groups and returns a count for the number of elements
469: * in each group. Similar to groupBy, but instead of returning a list of values,
470: * returns a count for the number of values in that group.
471: *
472: * When $callback is a string it should be a property name to extract or
473: * a dot separated path of properties that should be followed to get the last
474: * one in the path.
475: *
476: * ### Example:
477: *
478: * ```
479: * $items = [
480: * ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
481: * ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
482: * ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
483: * ];
484: *
485: * $group = (new Collection($items))->countBy('parent_id');
486: *
487: * // Or
488: * $group = (new Collection($items))->countBy(function ($e) {
489: * return $e['parent_id'];
490: * });
491: *
492: * // Result will look like this when converted to array
493: * [
494: * 10 => 2,
495: * 11 => 1
496: * ];
497: * ```
498: *
499: * @param callable|string $callback the callback or column name to use for indexing
500: * or a function returning the indexing key out of the provided element
501: * @return \Cake\Collection\CollectionInterface
502: */
503: public function countBy($callback);
504:
505: /**
506: * Returns the total sum of all the values extracted with $matcher
507: * or of this collection.
508: *
509: * ### Example:
510: *
511: * ```
512: * $items = [
513: * ['invoice' => ['total' => 100]],
514: * ['invoice' => ['total' => 200]]
515: * ];
516: *
517: * $total = (new Collection($items))->sumOf('invoice.total');
518: *
519: * // Total: 300
520: *
521: * $total = (new Collection([1, 2, 3]))->sumOf();
522: * // Total: 6
523: * ```
524: *
525: * @param string|callable|null $matcher The property name to sum or a function
526: * If no value is passed, an identity function will be used.
527: * that will return the value of the property to sum.
528: * @return float|int
529: */
530: public function sumOf($matcher = null);
531:
532: /**
533: * Returns a new collection with the elements placed in a random order,
534: * this function does not preserve the original keys in the collection.
535: *
536: * @return \Cake\Collection\CollectionInterface
537: */
538: public function shuffle();
539:
540: /**
541: * Returns a new collection with maximum $size random elements
542: * from this collection
543: *
544: * @param int $size the maximum number of elements to randomly
545: * take from this collection
546: * @return \Cake\Collection\CollectionInterface
547: */
548: public function sample($size = 10);
549:
550: /**
551: * Returns a new collection with maximum $size elements in the internal
552: * order this collection was created. If a second parameter is passed, it
553: * will determine from what position to start taking elements.
554: *
555: * @param int $size the maximum number of elements to take from
556: * this collection
557: * @param int $from A positional offset from where to take the elements
558: * @return \Cake\Collection\CollectionInterface
559: */
560: public function take($size = 1, $from = 0);
561:
562: /**
563: * Returns the last N elements of a collection
564: *
565: * ### Example:
566: *
567: * ```
568: * $items = [1, 2, 3, 4, 5];
569: *
570: * $last = (new Collection($items))->takeLast(3);
571: *
572: * // Result will look like this when converted to array
573: * [3, 4, 5];
574: * ```
575: *
576: * @param int $howMany The number of elements at the end of the collection
577: * @return \Cake\Collection\CollectionInterface
578: */
579: public function takeLast($howMany);
580:
581: /**
582: * Returns a new collection that will skip the specified amount of elements
583: * at the beginning of the iteration.
584: *
585: * @param int $howMany The number of elements to skip.
586: * @return \Cake\Collection\CollectionInterface
587: */
588: public function skip($howMany);
589:
590: /**
591: * Looks through each value in the list, returning a Collection of all the
592: * values that contain all of the key-value pairs listed in $conditions.
593: *
594: * ### Example:
595: *
596: * ```
597: * $items = [
598: * ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
599: * ['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
600: * ];
601: *
602: * $extracted = (new Collection($items))->match(['user.name' => 'Renan']);
603: *
604: * // Result will look like this when converted to array
605: * [
606: * ['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
607: * ]
608: * ```
609: *
610: * @param array $conditions a key-value list of conditions where
611: * the key is a property path as accepted by `Collection::extract,
612: * and the value the condition against with each element will be matched
613: * @return \Cake\Collection\CollectionInterface
614: */
615: public function match(array $conditions);
616:
617: /**
618: * Returns the first result matching all of the key-value pairs listed in
619: * conditions.
620: *
621: * @param array $conditions a key-value list of conditions where the key is
622: * a property path as accepted by `Collection::extract`, and the value the
623: * condition against with each element will be matched
624: * @see \Cake\Collection\CollectionInterface::match()
625: * @return mixed
626: */
627: public function firstMatch(array $conditions);
628:
629: /**
630: * Returns the first result in this collection
631: *
632: * @return mixed The first value in the collection will be returned.
633: */
634: public function first();
635:
636: /**
637: * Returns the last result in this collection
638: *
639: * @return mixed The last value in the collection will be returned.
640: */
641: public function last();
642:
643: /**
644: * Returns a new collection as the result of concatenating the list of elements
645: * in this collection with the passed list of elements
646: *
647: * @param array|\Traversable $items Items list.
648: * @return \Cake\Collection\CollectionInterface
649: */
650: public function append($items);
651:
652: /**
653: * Returns a new collection where the values extracted based on a value path
654: * and then indexed by a key path. Optionally this method can produce parent
655: * groups based on a group property path.
656: *
657: * ### Examples:
658: *
659: * ```
660: * $items = [
661: * ['id' => 1, 'name' => 'foo', 'parent' => 'a'],
662: * ['id' => 2, 'name' => 'bar', 'parent' => 'b'],
663: * ['id' => 3, 'name' => 'baz', 'parent' => 'a'],
664: * ];
665: *
666: * $combined = (new Collection($items))->combine('id', 'name');
667: *
668: * // Result will look like this when converted to array
669: * [
670: * 1 => 'foo',
671: * 2 => 'bar',
672: * 3 => 'baz',
673: * ];
674: *
675: * $combined = (new Collection($items))->combine('id', 'name', 'parent');
676: *
677: * // Result will look like this when converted to array
678: * [
679: * 'a' => [1 => 'foo', 3 => 'baz'],
680: * 'b' => [2 => 'bar']
681: * ];
682: * ```
683: *
684: * @param callable|string $keyPath the column name path to use for indexing
685: * or a function returning the indexing key out of the provided element
686: * @param callable|string $valuePath the column name path to use as the array value
687: * or a function returning the value out of the provided element
688: * @param callable|string|null $groupPath the column name path to use as the parent
689: * grouping key or a function returning the key out of the provided element
690: * @return \Cake\Collection\CollectionInterface
691: */
692: public function combine($keyPath, $valuePath, $groupPath = null);
693:
694: /**
695: * Returns a new collection where the values are nested in a tree-like structure
696: * based on an id property path and a parent id property path.
697: *
698: * @param callable|string $idPath the column name path to use for determining
699: * whether an element is parent of another
700: * @param callable|string $parentPath the column name path to use for determining
701: * whether an element is child of another
702: * @param string $nestingKey The key name under which children are nested
703: * @return \Cake\Collection\CollectionInterface
704: */
705: public function nest($idPath, $parentPath, $nestingKey = 'children');
706:
707: /**
708: * Returns a new collection containing each of the elements found in `$values` as
709: * a property inside the corresponding elements in this collection. The property
710: * where the values will be inserted is described by the `$path` parameter.
711: *
712: * The $path can be a string with a property name or a dot separated path of
713: * properties that should be followed to get the last one in the path.
714: *
715: * If a column or property could not be found for a particular element in the
716: * collection as part of the path, the element will be kept unchanged.
717: *
718: * ### Example:
719: *
720: * Insert ages into a collection containing users:
721: *
722: * ```
723: * $items = [
724: * ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
725: * ['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan']]
726: * ];
727: * $ages = [25, 28];
728: * $inserted = (new Collection($items))->insert('comment.user.age', $ages);
729: *
730: * // Result will look like this when converted to array
731: * [
732: * ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark', 'age' => 25]],
733: * ['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan', 'age' => 28]]
734: * ];
735: * ```
736: *
737: * @param string $path a dot separated string symbolizing the path to follow
738: * inside the hierarchy of each value so that the value can be inserted
739: * @param mixed $values The values to be inserted at the specified path,
740: * values are matched with the elements in this collection by its positional index.
741: * @return \Cake\Collection\CollectionInterface
742: */
743: public function insert($path, $values);
744:
745: /**
746: * Returns an array representation of the results
747: *
748: * @param bool $preserveKeys whether to use the keys returned by this
749: * collection as the array keys. Keep in mind that it is valid for iterators
750: * to return the same key for different elements, setting this value to false
751: * can help getting all items if keys are not important in the result.
752: * @return array
753: */
754: public function toArray($preserveKeys = true);
755:
756: /**
757: * Returns an numerically-indexed array representation of the results.
758: * This is equivalent to calling `toArray(false)`
759: *
760: * @return array
761: */
762: public function toList();
763:
764: /**
765: * Convert a result set into JSON.
766: *
767: * Part of JsonSerializable interface.
768: *
769: * @return array The data to convert to JSON
770: */
771: public function jsonSerialize();
772:
773: /**
774: * Iterates once all elements in this collection and executes all stacked
775: * operations of them, finally it returns a new collection with the result.
776: * This is useful for converting non-rewindable internal iterators into
777: * a collection that can be rewound and used multiple times.
778: *
779: * A common use case is to re-use the same variable for calculating different
780: * data. In those cases it may be helpful and more performant to first compile
781: * a collection and then apply more operations to it.
782: *
783: * ### Example:
784: *
785: * ```
786: * $collection->map($mapper)->sortBy('age')->extract('name');
787: * $compiled = $collection->compile();
788: * $isJohnHere = $compiled->some($johnMatcher);
789: * $allButJohn = $compiled->filter($johnMatcher);
790: * ```
791: *
792: * In the above example, had the collection not been compiled before, the
793: * iterations for `map`, `sortBy` and `extract` would've been executed twice:
794: * once for getting `$isJohnHere` and once for `$allButJohn`
795: *
796: * You can think of this method as a way to create save points for complex
797: * calculations in a collection.
798: *
799: * @param bool $preserveKeys whether to use the keys returned by this
800: * collection as the array keys. Keep in mind that it is valid for iterators
801: * to return the same key for different elements, setting this value to false
802: * can help getting all items if keys are not important in the result.
803: * @return \Cake\Collection\CollectionInterface
804: */
805: public function compile($preserveKeys = true);
806:
807: /**
808: * Returns a new collection where any operations chained after it are guaranteed
809: * to be run lazily. That is, elements will be yieleded one at a time.
810: *
811: * A lazy collection can only be iterated once. A second attempt results in an error.
812: *
813: * @return \Cake\Collection\CollectionInterface
814: */
815: public function lazy();
816:
817: /**
818: * Returns a new collection where the operations performed by this collection.
819: * No matter how many times the new collection is iterated, those operations will
820: * only be performed once.
821: *
822: * This can also be used to make any non-rewindable iterator rewindable.
823: *
824: * @return \Cake\Collection\CollectionInterface
825: */
826: public function buffered();
827:
828: /**
829: * Returns a new collection with each of the elements of this collection
830: * after flattening the tree structure. The tree structure is defined
831: * by nesting elements under a key with a known name. It is possible
832: * to specify such name by using the '$nestingKey' parameter.
833: *
834: * By default all elements in the tree following a Depth First Search
835: * will be returned, that is, elements from the top parent to the leaves
836: * for each branch.
837: *
838: * It is possible to return all elements from bottom to top using a Breadth First
839: * Search approach by passing the '$dir' parameter with 'asc'. That is, it will
840: * return all elements for the same tree depth first and from bottom to top.
841: *
842: * Finally, you can specify to only get a collection with the leaf nodes in the
843: * tree structure. You do so by passing 'leaves' in the first argument.
844: *
845: * The possible values for the first argument are aliases for the following
846: * constants and it is valid to pass those instead of the alias:
847: *
848: * - desc: TreeIterator::SELF_FIRST
849: * - asc: TreeIterator::CHILD_FIRST
850: * - leaves: TreeIterator::LEAVES_ONLY
851: *
852: * ### Example:
853: *
854: * ```
855: * $collection = new Collection([
856: * ['id' => 1, 'children' => [['id' => 2, 'children' => [['id' => 3]]]]],
857: * ['id' => 4, 'children' => [['id' => 5]]]
858: * ]);
859: * $flattenedIds = $collection->listNested()->extract('id'); // Yields [1, 2, 3, 4, 5]
860: * ```
861: *
862: * @param string|int $dir The direction in which to return the elements
863: * @param string|callable $nestingKey The key name under which children are nested
864: * or a callable function that will return the children list
865: * @return \Cake\Collection\CollectionInterface
866: */
867: public function listNested($dir = 'desc', $nestingKey = 'children');
868:
869: /**
870: * Creates a new collection that when iterated will stop yielding results if
871: * the provided condition evaluates to true.
872: *
873: * This is handy for dealing with infinite iterators or any generator that
874: * could start returning invalid elements at a certain point. For example,
875: * when reading lines from a file stream you may want to stop the iteration
876: * after a certain value is reached.
877: *
878: * ### Example:
879: *
880: * Get an array of lines in a CSV file until the timestamp column is less than a date
881: *
882: * ```
883: * $lines = (new Collection($fileLines))->stopWhen(function ($value, $key) {
884: * return (new DateTime($value))->format('Y') < 2012;
885: * })
886: * ->toArray();
887: * ```
888: *
889: * Get elements until the first unapproved message is found:
890: *
891: * ```
892: * $comments = (new Collection($comments))->stopWhen(['is_approved' => false]);
893: * ```
894: *
895: * @param callable $condition the method that will receive each of the elements and
896: * returns true when the iteration should be stopped.
897: * If an array, it will be interpreted as a key-value list of conditions where
898: * the key is a property path as accepted by `Collection::extract`,
899: * and the value the condition against with each element will be matched.
900: * @return \Cake\Collection\CollectionInterface
901: */
902: public function stopWhen($condition);
903:
904: /**
905: * Creates a new collection where the items are the
906: * concatenation of the lists of items generated by the transformer function
907: * applied to each item in the original collection.
908: *
909: * The transformer function will receive the value and the key for each of the
910: * items in the collection, in that order, and it must return an array or a
911: * Traversable object that can be concatenated to the final result.
912: *
913: * If no transformer function is passed, an "identity" function will be used.
914: * This is useful when each of the elements in the source collection are
915: * lists of items to be appended one after another.
916: *
917: * ### Example:
918: *
919: * ```
920: * $items [[1, 2, 3], [4, 5]];
921: * $unfold = (new Collection($items))->unfold(); // Returns [1, 2, 3, 4, 5]
922: * ```
923: *
924: * Using a transformer
925: *
926: * ```
927: * $items [1, 2, 3];
928: * $allItems = (new Collection($items))->unfold(function ($page) {
929: * return $service->fetchPage($page)->toArray();
930: * });
931: * ```
932: *
933: * @param callable|null $transformer A callable function that will receive each of
934: * the items in the collection and should return an array or Traversable object
935: * @return \Cake\Collection\CollectionInterface
936: */
937: public function unfold(callable $transformer = null);
938:
939: /**
940: * Passes this collection through a callable as its first argument.
941: * This is useful for decorating the full collection with another object.
942: *
943: * ### Example:
944: *
945: * ```
946: * $items = [1, 2, 3];
947: * $decorated = (new Collection($items))->through(function ($collection) {
948: * return new MyCustomCollection($collection);
949: * });
950: * ```
951: *
952: * @param callable $handler A callable function that will receive
953: * this collection as first argument.
954: * @return \Cake\Collection\CollectionInterface
955: */
956: public function through(callable $handler);
957:
958: /**
959: * Combines the elements of this collection with each of the elements of the
960: * passed iterables, using their positional index as a reference.
961: *
962: * ### Example:
963: *
964: * ```
965: * $collection = new Collection([1, 2]);
966: * $collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
967: * ```
968: *
969: * @param array|\Traversable ...$items The collections to zip.
970: * @return \Cake\Collection\CollectionInterface
971: */
972: public function zip($items);
973:
974: /**
975: * Combines the elements of this collection with each of the elements of the
976: * passed iterables, using their positional index as a reference.
977: *
978: * The resulting element will be the return value of the $callable function.
979: *
980: * ### Example:
981: *
982: * ```
983: * $collection = new Collection([1, 2]);
984: * $zipped = $collection->zipWith([3, 4], [5, 6], function (...$args) {
985: * return array_sum($args);
986: * });
987: * $zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)]
988: * ```
989: *
990: * @param array|\Traversable ...$items The collections to zip.
991: * @param callable $callable The function to use for zipping the elements together.
992: * @return \Cake\Collection\CollectionInterface
993: */
994: public function zipWith($items, $callable);
995:
996: /**
997: * Breaks the collection into smaller arrays of the given size.
998: *
999: * ### Example:
1000: *
1001: * ```
1002: * $items [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
1003: * $chunked = (new Collection($items))->chunk(3)->toList();
1004: * // Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
1005: * ```
1006: *
1007: * @param int $chunkSize The maximum size for each chunk
1008: * @return \Cake\Collection\CollectionInterface
1009: */
1010: public function chunk($chunkSize);
1011:
1012: /**
1013: * Breaks the collection into smaller arrays of the given size.
1014: *
1015: * ### Example:
1016: *
1017: * ```
1018: * $items ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
1019: * $chunked = (new Collection($items))->chunkWithKeys(3)->toList();
1020: * // Returns [['a' => 1, 'b' => 2, 'c' => 3], ['d' => 4, 'e' => 5, 'f' => 6]]
1021: * ```
1022: *
1023: * @param int $chunkSize The maximum size for each chunk
1024: * @param bool $preserveKeys If the keys of the array should be preserved
1025: * @return \Cake\Collection\CollectionInterface
1026: */
1027: public function chunkWithKeys($chunkSize, $preserveKeys = true);
1028:
1029: /**
1030: * Returns whether or not there are elements in this collection
1031: *
1032: * ### Example:
1033: *
1034: * ```
1035: * $items [1, 2, 3];
1036: * (new Collection($items))->isEmpty(); // false
1037: * ```
1038: *
1039: * ```
1040: * (new Collection([]))->isEmpty(); // true
1041: * ```
1042: *
1043: * @return bool
1044: */
1045: public function isEmpty();
1046:
1047: /**
1048: * Returns the closest nested iterator that can be safely traversed without
1049: * losing any possible transformations. This is used mainly to remove empty
1050: * IteratorIterator wrappers that can only slowdown the iteration process.
1051: *
1052: * @return \Traversable
1053: */
1054: public function unwrap();
1055:
1056: /**
1057: * Transpose rows and columns into columns and rows
1058: *
1059: * ### Example:
1060: *
1061: * ```
1062: * $items = [
1063: * ['Products', '2012', '2013', '2014'],
1064: * ['Product A', '200', '100', '50'],
1065: * ['Product B', '300', '200', '100'],
1066: * ['Product C', '400', '300', '200'],
1067: * ]
1068: *
1069: * $transpose = (new Collection($items))->transpose()->toList();
1070: *
1071: * // Returns
1072: * // [
1073: * // ['Products', 'Product A', 'Product B', 'Product C'],
1074: * // ['2012', '200', '300', '400'],
1075: * // ['2013', '100', '200', '300'],
1076: * // ['2014', '50', '100', '200'],
1077: * // ]
1078: * ```
1079: *
1080: * @return \Cake\Collection\CollectionInterface
1081: */
1082: public function transpose();
1083:
1084: /**
1085: * Returns the amount of elements in the collection.
1086: *
1087: * ## WARNINGS:
1088: *
1089: * ### Consumes all elements for NoRewindIterator collections:
1090: *
1091: * On certain type of collections, calling this method may render unusable afterwards.
1092: * That is, you may not be able to get elements out of it, or to iterate on it anymore.
1093: *
1094: * Specifically any collection wrapping a Generator (a function with a yield statement)
1095: * or a unbuffered database cursor will not accept any other function calls after calling
1096: * `count()` on it.
1097: *
1098: * Create a new collection with `buffered()` method to overcome this problem.
1099: *
1100: * ### Can report more elements than unique keys:
1101: *
1102: * Any collection constructed by appending collections together, or by having internal iterators
1103: * returning duplicate keys, will report a larger amount of elements using this functions than
1104: * the final amount of elements when converting the collections to a keyed array. This is because
1105: * duplicate keys will be collapsed into a single one in the final array, whereas this count method
1106: * is only concerned by the amount of elements after converting it to a plain list.
1107: *
1108: * If you need the count of elements after taking the keys in consideration
1109: * (the count of unique keys), you can call `countKeys()`
1110: *
1111: * ### Will change the current position of the iterator:
1112: *
1113: * Calling this method at the same time that you are iterating this collections, for example in
1114: * a foreach, will result in undefined behavior. Avoid doing this.
1115: *
1116: *
1117: * @return int
1118: */
1119: public function count();
1120:
1121: /**
1122: * Returns the number of unique keys in this iterator. This is, the number of
1123: * elements the collection will contain after calling `toArray()`
1124: *
1125: * This method comes with a number of caveats. Please refer to `CollectionInterface::count()`
1126: * for details.
1127: *
1128: * @see \Cake\Collection\CollectionInterface::count()
1129: * @return int
1130: */
1131: public function countKeys();
1132: }
1133: