CollectionInterface.php 39 KB

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