CollectionInterface.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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 a new collection that will skip the specified amount of elements
  538. * at the beginning of the iteration.
  539. *
  540. * @param int $howMany The number of elements to skip.
  541. * @return \Cake\Collection\CollectionInterface
  542. */
  543. public function skip($howMany);
  544. /**
  545. * Looks through each value in the list, returning a Collection of all the
  546. * values that contain all of the key-value pairs listed in $conditions.
  547. *
  548. * ### Example:
  549. *
  550. * ```
  551. * $items = [
  552. * ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
  553. * ['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
  554. * ];
  555. *
  556. * $extracted = (new Collection($items))->match(['user.name' => 'Renan']);
  557. *
  558. * // Result will look like this when converted to array
  559. * [
  560. * ['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
  561. * ]
  562. * ```
  563. *
  564. * @param array $conditions a key-value list of conditions where
  565. * the key is a property path as accepted by `Collection::extract,
  566. * and the value the condition against with each element will be matched
  567. * @return \Cake\Collection\CollectionInterface
  568. */
  569. public function match(array $conditions);
  570. /**
  571. * Returns the first result matching all of the key-value pairs listed in
  572. * conditions.
  573. *
  574. * @param array $conditions a key-value list of conditions where the key is
  575. * a property path as accepted by `Collection::extract`, and the value the
  576. * condition against with each element will be matched
  577. * @see \Cake\Collection\CollectionInterface::match()
  578. * @return mixed
  579. */
  580. public function firstMatch(array $conditions);
  581. /**
  582. * Returns the first result in this collection
  583. *
  584. * @return mixed The first value in the collection will be returned.
  585. */
  586. public function first();
  587. /**
  588. * Returns the last result in this collection
  589. *
  590. * @return mixed The last value in the collection will be returned.
  591. */
  592. public function last();
  593. /**
  594. * Returns a new collection as the result of concatenating the list of elements
  595. * in this collection with the passed list of elements
  596. *
  597. * @param array|\Traversable $items Items list.
  598. * @return \Cake\Collection\CollectionInterface
  599. */
  600. public function append($items);
  601. /**
  602. * Returns a new collection where the values extracted based on a value path
  603. * and then indexed by a key path. Optionally this method can produce parent
  604. * groups based on a group property path.
  605. *
  606. * ### Examples:
  607. *
  608. * ```
  609. * $items = [
  610. * ['id' => 1, 'name' => 'foo', 'parent' => 'a'],
  611. * ['id' => 2, 'name' => 'bar', 'parent' => 'b'],
  612. * ['id' => 3, 'name' => 'baz', 'parent' => 'a'],
  613. * ];
  614. *
  615. * $combined = (new Collection($items))->combine('id', 'name');
  616. *
  617. * // Result will look like this when converted to array
  618. * [
  619. * 1 => 'foo',
  620. * 2 => 'bar',
  621. * 3 => 'baz',
  622. * ];
  623. *
  624. * $combined = (new Collection($items))->combine('id', 'name', 'parent');
  625. *
  626. * // Result will look like this when converted to array
  627. * [
  628. * 'a' => [1 => 'foo', 3 => 'baz'],
  629. * 'b' => [2 => 'bar']
  630. * ];
  631. * ```
  632. *
  633. * @param callable|string $keyPath the column name path to use for indexing
  634. * or a function returning the indexing key out of the provided element
  635. * @param callable|string $valuePath the column name path to use as the array value
  636. * or a function returning the value out of the provided element
  637. * @param callable|string|null $groupPath the column name path to use as the parent
  638. * grouping key or a function returning the key out of the provided element
  639. * @return \Cake\Collection\CollectionInterface
  640. */
  641. public function combine($keyPath, $valuePath, $groupPath = null);
  642. /**
  643. * Returns a new collection where the values are nested in a tree-like structure
  644. * based on an id property path and a parent id property path.
  645. *
  646. * @param callable|string $idPath the column name path to use for determining
  647. * whether an element is parent of another
  648. * @param callable|string $parentPath the column name path to use for determining
  649. * whether an element is child of another
  650. * @param string $nestingKey The key name under which children are nested
  651. * @return \Cake\Collection\CollectionInterface
  652. */
  653. public function nest($idPath, $parentPath, $nestingKey = 'children');
  654. /**
  655. * Returns a new collection containing each of the elements found in `$values` as
  656. * a property inside the corresponding elements in this collection. The property
  657. * where the values will be inserted is described by the `$path` parameter.
  658. *
  659. * The $path can be a string with a property name or a dot separated path of
  660. * properties that should be followed to get the last one in the path.
  661. *
  662. * If a column or property could not be found for a particular element in the
  663. * collection as part of the path, the element will be kept unchanged.
  664. *
  665. * ### Example:
  666. *
  667. * Insert ages into a collection containing users:
  668. *
  669. * ```
  670. * $items = [
  671. * ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
  672. * ['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan']]
  673. * ];
  674. * $ages = [25, 28];
  675. * $inserted = (new Collection($items))->insert('comment.user.age', $ages);
  676. *
  677. * // Result will look like this when converted to array
  678. * [
  679. * ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark', 'age' => 25]],
  680. * ['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan', 'age' => 28]]
  681. * ];
  682. * ```
  683. *
  684. * @param string $path a dot separated string symbolizing the path to follow
  685. * inside the hierarchy of each value so that the value can be inserted
  686. * @param mixed $values The values to be inserted at the specified path,
  687. * values are matched with the elements in this collection by its positional index.
  688. * @return \Cake\Collection\CollectionInterface
  689. */
  690. public function insert($path, $values);
  691. /**
  692. * Returns an array representation of the results
  693. *
  694. * @param bool $preserveKeys whether to use the keys returned by this
  695. * collection as the array keys. Keep in mind that it is valid for iterators
  696. * to return the same key for different elements, setting this value to false
  697. * can help getting all items if keys are not important in the result.
  698. * @return array
  699. */
  700. public function toArray($preserveKeys = true);
  701. /**
  702. * Returns an numerically-indexed array representation of the results.
  703. * This is equivalent to calling `toArray(false)`
  704. *
  705. * @return array
  706. */
  707. public function toList();
  708. /**
  709. * Convert a result set into JSON.
  710. *
  711. * Part of JsonSerializable interface.
  712. *
  713. * @return array The data to convert to JSON
  714. */
  715. public function jsonSerialize();
  716. /**
  717. * Iterates once all elements in this collection and executes all stacked
  718. * operations of them, finally it returns a new collection with the result.
  719. * This is useful for converting non-rewindable internal iterators into
  720. * a collection that can be rewound and used multiple times.
  721. *
  722. * A common use case is to re-use the same variable for calculating different
  723. * data. In those cases it may be helpful and more performant to first compile
  724. * a collection and then apply more operations to it.
  725. *
  726. * ### Example:
  727. *
  728. * ```
  729. * $collection->map($mapper)->sortBy('age')->extract('name');
  730. * $compiled = $collection->compile();
  731. * $isJohnHere = $compiled->some($johnMatcher);
  732. * $allButJohn = $compiled->filter($johnMatcher);
  733. * ```
  734. *
  735. * In the above example, had the collection not been compiled before, the
  736. * iterations for `map`, `sortBy` and `extract` would've been executed twice:
  737. * once for getting `$isJohnHere` and once for `$allButJohn`
  738. *
  739. * You can think of this method as a way to create save points for complex
  740. * calculations in a collection.
  741. *
  742. * @param bool $preserveKeys whether to use the keys returned by this
  743. * collection as the array keys. Keep in mind that it is valid for iterators
  744. * to return the same key for different elements, setting this value to false
  745. * can help getting all items if keys are not important in the result.
  746. * @return \Cake\Collection\CollectionInterface
  747. */
  748. public function compile($preserveKeys = true);
  749. /**
  750. * Returns a new collection where the operations performed by this collection.
  751. * No matter how many times the new collection is iterated, those operations will
  752. * only be performed once.
  753. *
  754. * This can also be used to make any non-rewindable iterator rewindable.
  755. *
  756. * @return \Cake\Collection\CollectionInterface
  757. */
  758. public function buffered();
  759. /**
  760. * Returns a new collection with each of the elements of this collection
  761. * after flattening the tree structure. The tree structure is defined
  762. * by nesting elements under a key with a known name. It is possible
  763. * to specify such name by using the '$nestingKey' parameter.
  764. *
  765. * By default all elements in the tree following a Depth First Search
  766. * will be returned, that is, elements from the top parent to the leaves
  767. * for each branch.
  768. *
  769. * It is possible to return all elements from bottom to top using a Breadth First
  770. * Search approach by passing the '$dir' parameter with 'asc'. That is, it will
  771. * return all elements for the same tree depth first and from bottom to top.
  772. *
  773. * Finally, you can specify to only get a collection with the leaf nodes in the
  774. * tree structure. You do so by passing 'leaves' in the first argument.
  775. *
  776. * The possible values for the first argument are aliases for the following
  777. * constants and it is valid to pass those instead of the alias:
  778. *
  779. * - desc: TreeIterator::SELF_FIRST
  780. * - asc: TreeIterator::CHILD_FIRST
  781. * - leaves: TreeIterator::LEAVES_ONLY
  782. *
  783. * ### Example:
  784. *
  785. * ```
  786. * $collection = new Collection([
  787. * ['id' => 1, 'children' => [['id' => 2, 'children' => [['id' => 3]]]]],
  788. * ['id' => 4, 'children' => [['id' => 5]]]
  789. * ]);
  790. * $flattenedIds = $collection->listNested()->extract('id'); // Yields [1, 2, 3, 4, 5]
  791. * ```
  792. *
  793. * @param string|int $dir The direction in which to return the elements
  794. * @param string|callable $nestingKey The key name under which children are nested
  795. * or a callable function that will return the children list
  796. * @return \Cake\Collection\CollectionInterface
  797. */
  798. public function listNested($dir = 'desc', $nestingKey = 'children');
  799. /**
  800. * Creates a new collection that when iterated will stop yielding results if
  801. * the provided condition evaluates to false.
  802. *
  803. * This is handy for dealing with infinite iterators or any generator that
  804. * could start returning invalid elements at a certain point. For example,
  805. * when reading lines from a file stream you may want to stop the iteration
  806. * after a certain value is reached.
  807. *
  808. * ### Example:
  809. *
  810. * Get an array of lines in a CSV file until the timestamp column is less than a date
  811. *
  812. * ```
  813. * $lines = (new Collection($fileLines))->stopWhen(function ($value, $key) {
  814. * return (new DateTime($value))->format('Y') < 2012;
  815. * })
  816. * ->toArray();
  817. * ```
  818. *
  819. * Get elements until the first unapproved message is found:
  820. *
  821. * ```
  822. * $comments = (new Collection($comments))->stopWhen(['is_approved' => false]);
  823. * ```
  824. *
  825. * @param callable $condition the method that will receive each of the elements and
  826. * returns false when the iteration should be stopped.
  827. * If an array, it will be interpreted as a key-value list of conditions where
  828. * the key is a property path as accepted by `Collection::extract`,
  829. * and the value the condition against with each element will be matched.
  830. * @return \Cake\Collection\CollectionInterface
  831. */
  832. public function stopWhen($condition);
  833. /**
  834. * Creates a new collection where the items are the
  835. * concatenation of the lists of items generated by the transformer function
  836. * applied to each item in the original collection.
  837. *
  838. * The transformer function will receive the value and the key for each of the
  839. * items in the collection, in that order, and it must return an array or a
  840. * Traversable object that can be concatenated to the final result.
  841. *
  842. * If no transformer function is passed, an "identity" function will be used.
  843. * This is useful when each of the elements in the source collection are
  844. * lists of items to be appended one after another.
  845. *
  846. * ### Example:
  847. *
  848. * ```
  849. * $items [[1, 2, 3], [4, 5]];
  850. * $unfold = (new Collection($items))->unfold(); // Returns [1, 2, 3, 4, 5]
  851. * ```
  852. *
  853. * Using a transformer
  854. *
  855. * ```
  856. * $items [1, 2, 3];
  857. * $allItems = (new Collection($items))->unfold(function ($page) {
  858. * return $service->fetchPage($page)->toArray();
  859. * });
  860. * ```
  861. *
  862. * @param callable|null $transformer A callable function that will receive each of
  863. * the items in the collection and should return an array or Traversable object
  864. * @return \Cake\Collection\CollectionInterface
  865. */
  866. public function unfold(callable $transformer = null);
  867. /**
  868. * Passes this collection through a callable as its first argument.
  869. * This is useful for decorating the full collection with another object.
  870. *
  871. * ### Example:
  872. *
  873. * ```
  874. * $items = [1, 2, 3];
  875. * $decorated = (new Collection($items))->through(function ($collection) {
  876. * return new MyCustomCollection($collection);
  877. * });
  878. * ```
  879. *
  880. * @param callable $handler A callable function that will receive
  881. * this collection as first argument.
  882. * @return \Cake\Collection\CollectionInterface
  883. */
  884. public function through(callable $handler);
  885. /**
  886. * Combines the elements of this collection with each of the elements of the
  887. * passed iterables, using their positional index as a reference.
  888. *
  889. * ### Example:
  890. *
  891. * ```
  892. * $collection = new Collection([1, 2]);
  893. * $collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
  894. * ```
  895. *
  896. * @param array|\Traversable ...$items The collections to zip.
  897. * @return \Cake\Collection\CollectionInterface
  898. */
  899. public function zip($items);
  900. /**
  901. * Combines the elements of this collection with each of the elements of the
  902. * passed iterables, using their positional index as a reference.
  903. *
  904. * The resulting element will be the return value of the $callable function.
  905. *
  906. * ### Example:
  907. *
  908. * ```
  909. * $collection = new Collection([1, 2]);
  910. * $zipped = $collection->zipWith([3, 4], [5, 6], function (...$args) {
  911. * return array_sum($args);
  912. * });
  913. * $zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)]
  914. * ```
  915. *
  916. * @param array|\Traversable ...$items The collections to zip.
  917. * @param callable $callable The function to use for zipping the elements together.
  918. * @return \Cake\Collection\CollectionInterface
  919. */
  920. public function zipWith($items, $callable);
  921. /**
  922. * Breaks the collection into smaller arrays of the given size.
  923. *
  924. * ### Example:
  925. *
  926. * ```
  927. * $items [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
  928. * $chunked = (new Collection($items))->chunk(3)->toList();
  929. * // Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
  930. * ```
  931. *
  932. * @param int $chunkSize The maximum size for each chunk
  933. * @return \Cake\Collection\CollectionInterface
  934. * @deprecated 4.0.0 Deprecated in favor of chunks
  935. */
  936. public function chunk($chunkSize);
  937. /**
  938. * Breaks the collection into smaller arrays of the given size.
  939. *
  940. * ### Example:
  941. *
  942. * ```
  943. * $items ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
  944. * $chunked = (new Collection($items))->chunkWithKeys(3)->toList();
  945. * // Returns [['a' => 1, 'b' => 2, 'c' => 3], ['d' => 4, 'e' => 5, 'f' => 6]]
  946. * ```
  947. *
  948. * @param int $chunkSize The maximum size for each chunk
  949. * @param bool $preserveKeys If the keys of the array should be preserved
  950. * @return \Cake\Collection\CollectionInterface
  951. */
  952. public function chunkWithKeys($chunkSize, $preserveKeys = true);
  953. /**
  954. * Returns whether or not there are elements in this collection
  955. *
  956. * ### Example:
  957. *
  958. * ```
  959. * $items [1, 2, 3];
  960. * (new Collection($items))->isEmpty(); // false
  961. * ```
  962. *
  963. * ```
  964. * (new Collection([]))->isEmpty(); // true
  965. * ```
  966. *
  967. * @return bool
  968. */
  969. public function isEmpty();
  970. /**
  971. * Returns the closest nested iterator that can be safely traversed without
  972. * losing any possible transformations. This is used mainly to remove empty
  973. * IteratorIterator wrappers that can only slowdown the iteration process.
  974. *
  975. * @return \Traversable
  976. */
  977. public function unwrap();
  978. /**
  979. * Transpose rows and columns into columns and rows
  980. *
  981. * ### Example:
  982. *
  983. * ```
  984. * $items = [
  985. * ['Products', '2012', '2013', '2014'],
  986. * ['Product A', '200', '100', '50'],
  987. * ['Product B', '300', '200', '100'],
  988. * ['Product C', '400', '300', '200'],
  989. * ]
  990. *
  991. * $transpose = (new Collection($items))->transpose()->toList();
  992. *
  993. * // Returns
  994. * // [
  995. * // ['Products', 'Product A', 'Product B', 'Product C'],
  996. * // ['2012', '200', '300', '400'],
  997. * // ['2013', '100', '200', '300'],
  998. * // ['2014', '50', '100', '200'],
  999. * // ]
  1000. * ```
  1001. *
  1002. * @return \Cake\Collection\CollectionInterface
  1003. */
  1004. public function transpose();
  1005. }