CollectionInterface.php 40 KB

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