CollectionInterface.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.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 void
  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 a sorted iterator out of the elements in this collection,
  276. * ranked in ascending order by the results of running each value through a
  277. * callback. $callback can also be a string representing the column or property
  278. * name.
  279. *
  280. * The callback will receive as its first argument each of the elements in $items,
  281. * the value returned by the callback will be used as the value for sorting such
  282. * element. Please note that the callback function could be called more than once
  283. * per element.
  284. *
  285. * ### Example:
  286. *
  287. * ```
  288. * $items = $collection->sortBy(function ($user) {
  289. * return $user->age;
  290. * });
  291. *
  292. * // alternatively
  293. * $items = $collection->sortBy('age');
  294. *
  295. * // or use a property path
  296. * $items = $collection->sortBy('department.name');
  297. *
  298. * // output all user name order by their age in descending order
  299. * foreach ($items as $user) {
  300. * echo $user->name;
  301. * }
  302. * ```
  303. *
  304. * @param callable|string $callback the callback or column name to use for sorting
  305. * @param int $dir either SORT_DESC or SORT_ASC
  306. * @param int $type the type of comparison to perform, either SORT_STRING
  307. * SORT_NUMERIC or SORT_NATURAL
  308. * @return \Cake\Collection\CollectionInterface
  309. */
  310. public function sortBy($callback, $dir = SORT_DESC, $type = SORT_NUMERIC);
  311. /**
  312. * Splits a collection into sets, grouped by the result of running each value
  313. * through the callback. If $callback is a string instead of a callable,
  314. * groups by the property named by $callback on each of the values.
  315. *
  316. * When $callback is a string it should be a property name to extract or
  317. * a dot separated path of properties that should be followed to get the last
  318. * one in the path.
  319. *
  320. * ### Example:
  321. *
  322. * ```
  323. * $items = [
  324. * ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
  325. * ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
  326. * ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
  327. * ];
  328. *
  329. * $group = (new Collection($items))->groupBy('parent_id');
  330. *
  331. * // Or
  332. * $group = (new Collection($items))->groupBy(function ($e) {
  333. * return $e['parent_id'];
  334. * });
  335. *
  336. * // Result will look like this when converted to array
  337. * [
  338. * 10 => [
  339. * ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
  340. * ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
  341. * ],
  342. * 11 => [
  343. * ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
  344. * ]
  345. * ];
  346. * ```
  347. *
  348. * @param callable|string $callback the callback or column name to use for grouping
  349. * or a function returning the grouping key out of the provided element
  350. * @return \Cake\Collection\CollectionInterface
  351. */
  352. public function groupBy($callback);
  353. /**
  354. * Given a list and a callback function that returns a key for each element
  355. * in the list (or a property name), returns an object with an index of each item.
  356. * Just like groupBy, but for when you know your keys are unique.
  357. *
  358. * When $callback is a string it should be a property name to extract or
  359. * a dot separated path of properties that should be followed to get the last
  360. * one in the path.
  361. *
  362. * ### Example:
  363. *
  364. * ```
  365. * $items = [
  366. * ['id' => 1, 'name' => 'foo'],
  367. * ['id' => 2, 'name' => 'bar'],
  368. * ['id' => 3, 'name' => 'baz'],
  369. * ];
  370. *
  371. * $indexed = (new Collection($items))->indexBy('id');
  372. *
  373. * // Or
  374. * $indexed = (new Collection($items))->indexBy(function ($e) {
  375. * return $e['id'];
  376. * });
  377. *
  378. * // Result will look like this when converted to array
  379. * [
  380. * 1 => ['id' => 1, 'name' => 'foo'],
  381. * 3 => ['id' => 3, 'name' => 'baz'],
  382. * 2 => ['id' => 2, 'name' => 'bar'],
  383. * ];
  384. * ```
  385. *
  386. * @param callable|string $callback the callback or column name to use for indexing
  387. * or a function returning the indexing key out of the provided element
  388. * @return \Cake\Collection\CollectionInterface
  389. */
  390. public function indexBy($callback);
  391. /**
  392. * Sorts a list into groups and returns a count for the number of elements
  393. * in each group. Similar to groupBy, but instead of returning a list of values,
  394. * returns a count for the number of values in that group.
  395. *
  396. * When $callback is a string it should be a property name to extract or
  397. * a dot separated path of properties that should be followed to get the last
  398. * one in the path.
  399. *
  400. * ### Example:
  401. *
  402. * ```
  403. * $items = [
  404. * ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
  405. * ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
  406. * ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
  407. * ];
  408. *
  409. * $group = (new Collection($items))->countBy('parent_id');
  410. *
  411. * // Or
  412. * $group = (new Collection($items))->countBy(function ($e) {
  413. * return $e['parent_id'];
  414. * });
  415. *
  416. * // Result will look like this when converted to array
  417. * [
  418. * 10 => 2,
  419. * 11 => 1
  420. * ];
  421. * ```
  422. *
  423. * @param callable|string $callback the callback or column name to use for indexing
  424. * or a function returning the indexing key out of the provided element
  425. * @return \Cake\Collection\CollectionInterface
  426. */
  427. public function countBy($callback);
  428. /**
  429. * Returns the total sum of all the values extracted with $matcher
  430. * or of this collection.
  431. *
  432. * ### Example:
  433. *
  434. * ```
  435. * $items = [
  436. * ['invoice' => ['total' => 100],
  437. * ['invoice' => ['total' => 200]
  438. * ];
  439. *
  440. * $total = (new Collection($items))->sumOf('invoice.total');
  441. *
  442. * // Total: 300
  443. *
  444. * $total = (new Collection([1, 2, 3]))->sumOf();
  445. * // Total: 6
  446. * ```
  447. *
  448. * @param string|callable|null $matcher The property name to sum or a function
  449. * If no value is passed, an identity function will be used.
  450. * that will return the value of the property to sum.
  451. * @return float|int
  452. */
  453. public function sumOf($matcher = null);
  454. /**
  455. * Returns a new collection with the elements placed in a random order,
  456. * this function does not preserve the original keys in the collection.
  457. *
  458. * @return \Cake\Collection\CollectionInterface
  459. */
  460. public function shuffle();
  461. /**
  462. * Returns a new collection with maximum $size random elements
  463. * from this collection
  464. *
  465. * @param int $size the maximum number of elements to randomly
  466. * take from this collection
  467. * @return \Cake\Collection\CollectionInterface
  468. */
  469. public function sample($size = 10);
  470. /**
  471. * Returns a new collection with maximum $size elements in the internal
  472. * order this collection was created. If a second parameter is passed, it
  473. * will determine from what position to start taking elements.
  474. *
  475. * @param int $size the maximum number of elements to take from
  476. * this collection
  477. * @param int $from A positional offset from where to take the elements
  478. * @return \Cake\Collection\CollectionInterface
  479. */
  480. public function take($size = 1, $from = 0);
  481. /**
  482. * Returns a new collection that will skip the specified amount of elements
  483. * at the beginning of the iteration.
  484. *
  485. * @param int $howMany The number of elements to skip.
  486. * @return \Cake\Collection\CollectionInterface
  487. */
  488. public function skip($howMany);
  489. /**
  490. * Looks through each value in the list, returning a Collection of all the
  491. * values that contain all of the key-value pairs listed in $conditions.
  492. *
  493. * ### Example:
  494. *
  495. * ```
  496. * $items = [
  497. * ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
  498. * ['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
  499. * ];
  500. *
  501. * $extracted = (new Collection($items))->match(['user.name' => 'Renan']);
  502. *
  503. * // Result will look like this when converted to array
  504. * [
  505. * ['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
  506. * ]
  507. * ```
  508. *
  509. * @param array $conditions a key-value list of conditions where
  510. * the key is a property path as accepted by `Collection::extract,
  511. * and the value the condition against with each element will be matched
  512. * @return \Cake\Collection\CollectionInterface
  513. */
  514. public function match(array $conditions);
  515. /**
  516. * Returns the first result matching all of the key-value pairs listed in
  517. * conditions.
  518. *
  519. * @param array $conditions a key-value list of conditions where the key is
  520. * a property path as accepted by `Collection::extract`, and the value the
  521. * condition against with each element will be matched
  522. * @see \Cake\Collection\CollectionInterface::match()
  523. * @return mixed
  524. */
  525. public function firstMatch(array $conditions);
  526. /**
  527. * Returns the first result in this collection
  528. *
  529. * @return mixed The first value in the collection will be returned.
  530. */
  531. public function first();
  532. /**
  533. * Returns the last result in this collection
  534. *
  535. * @return mixed The last value in the collection will be returned.
  536. */
  537. public function last();
  538. /**
  539. * Returns a new collection as the result of concatenating the list of elements
  540. * in this collection with the passed list of elements
  541. *
  542. * @param array|\Traversable $items Items list.
  543. * @return \Cake\Collection\CollectionInterface
  544. */
  545. public function append($items);
  546. /**
  547. * Returns a new collection where the values extracted based on a value path
  548. * and then indexed by a key path. Optionally this method can produce parent
  549. * groups based on a group property path.
  550. *
  551. * ### Examples:
  552. *
  553. * ```
  554. * $items = [
  555. * ['id' => 1, 'name' => 'foo', 'parent' => 'a'],
  556. * ['id' => 2, 'name' => 'bar', 'parent' => 'b'],
  557. * ['id' => 3, 'name' => 'baz', 'parent' => 'a'],
  558. * ];
  559. *
  560. * $combined = (new Collection($items))->combine('id', 'name');
  561. *
  562. * // Result will look like this when converted to array
  563. * [
  564. * 1 => 'foo',
  565. * 2 => 'bar',
  566. * 3 => 'baz',
  567. * ];
  568. *
  569. * $combined = (new Collection($items))->combine('id', 'name', 'parent');
  570. *
  571. * // Result will look like this when converted to array
  572. * [
  573. * 'a' => [1 => 'foo', 3 => 'baz'],
  574. * 'b' => [2 => 'bar']
  575. * ];
  576. * ```
  577. *
  578. * @param callable|string $keyPath the column name path to use for indexing
  579. * or a function returning the indexing key out of the provided element
  580. * @param callable|string $valuePath the column name path to use as the array value
  581. * or a function returning the value out of the provided element
  582. * @param callable|string|null $groupPath the column name path to use as the parent
  583. * grouping key or a function returning the key out of the provided element
  584. * @return \Cake\Collection\CollectionInterface
  585. */
  586. public function combine($keyPath, $valuePath, $groupPath = null);
  587. /**
  588. * Returns a new collection where the values are nested in a tree-like structure
  589. * based on an id property path and a parent id property path.
  590. *
  591. * @param callable|string $idPath the column name path to use for determining
  592. * whether an element is parent of another
  593. * @param callable|string $parentPath the column name path to use for determining
  594. * whether an element is child of another
  595. * @param string $nestingKey The key name under which children are nested
  596. * @return \Cake\Collection\CollectionInterface
  597. */
  598. public function nest($idPath, $parentPath, $nestingKey = 'children');
  599. /**
  600. * Returns a new collection containing each of the elements found in `$values` as
  601. * a property inside the corresponding elements in this collection. The property
  602. * where the values will be inserted is described by the `$path` parameter.
  603. *
  604. * The $path can be a string with a property name or a dot separated path of
  605. * properties that should be followed to get the last one in the path.
  606. *
  607. * If a column or property could not be found for a particular element in the
  608. * collection as part of the path, the element will be kept unchanged.
  609. *
  610. * ### Example:
  611. *
  612. * Insert ages into a collection containing users:
  613. *
  614. * ```
  615. * $items = [
  616. * ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
  617. * ['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan']]
  618. * ];
  619. * $ages = [25, 28];
  620. * $inserted = (new Collection($items))->insert('comment.user.age', $ages);
  621. *
  622. * // Result will look like this when converted to array
  623. * [
  624. * ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark', 'age' => 25]],
  625. * ['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan', 'age' => 28]]
  626. * ];
  627. * ```
  628. *
  629. * @param string $path a dot separated string symbolizing the path to follow
  630. * inside the hierarchy of each value so that the value can be inserted
  631. * @param mixed $values The values to be inserted at the specified path,
  632. * values are matched with the elements in this collection by its positional index.
  633. * @return \Cake\Collection\CollectionInterface
  634. */
  635. public function insert($path, $values);
  636. /**
  637. * Returns an array representation of the results
  638. *
  639. * @param bool $preserveKeys whether to use the keys returned by this
  640. * collection as the array keys. Keep in mind that it is valid for iterators
  641. * to return the same key for different elements, setting this value to false
  642. * can help getting all items if keys are not important in the result.
  643. * @return array
  644. */
  645. public function toArray($preserveKeys = true);
  646. /**
  647. * Returns an numerically-indexed array representation of the results.
  648. * This is equivalent to calling `toArray(false)`
  649. *
  650. * @return array
  651. */
  652. public function toList();
  653. /**
  654. * Convert a result set into JSON.
  655. *
  656. * Part of JsonSerializable interface.
  657. *
  658. * @return array The data to convert to JSON
  659. */
  660. public function jsonSerialize();
  661. /**
  662. * Iterates once all elements in this collection and executes all stacked
  663. * operations of them, finally it returns a new collection with the result.
  664. * This is useful for converting non-rewindable internal iterators into
  665. * a collection that can be rewound and used multiple times.
  666. *
  667. * A common use case is to re-use the same variable for calculating different
  668. * data. In those cases it may be helpful and more performant to first compile
  669. * a collection and then apply more operations to it.
  670. *
  671. * ### Example:
  672. *
  673. * ```
  674. * $collection->map($mapper)->sortBy('age')->extract('name');
  675. * $compiled = $collection->compile();
  676. * $isJohnHere = $compiled->some($johnMatcher);
  677. * $allButJohn = $compiled->filter($johnMatcher);
  678. * ```
  679. *
  680. * In the above example, had the collection not been compiled before, the
  681. * iterations for `map`, `sortBy` and `extract` would've been executed twice:
  682. * once for getting `$isJohnHere` and once for `$allButJohn`
  683. *
  684. * You can think of this method as a way to create save points for complex
  685. * calculations in a collection.
  686. *
  687. * @param bool $preserveKeys whether to use the keys returned by this
  688. * collection as the array keys. Keep in mind that it is valid for iterators
  689. * to return the same key for different elements, setting this value to false
  690. * can help getting all items if keys are not important in the result.
  691. * @return \Cake\Collection\CollectionInterface
  692. */
  693. public function compile($preserveKeys = true);
  694. /**
  695. * Returns a new collection where the operations performed by this collection.
  696. * No matter how many times the new collection is iterated, those operations will
  697. * only be performed once.
  698. *
  699. * This can also be used to make any non-rewindable iterator rewindable.
  700. *
  701. * @return \Cake\Collection\CollectionInterface
  702. */
  703. public function buffered();
  704. /**
  705. * Returns a new collection with each of the elements of this collection
  706. * after flattening the tree structure. The tree structure is defined
  707. * by nesting elements under a key with a known name. It is possible
  708. * to specify such name by using the '$nestingKey' parameter.
  709. *
  710. * By default all elements in the tree following a Depth First Search
  711. * will be returned, that is, elements from the top parent to the leaves
  712. * for each branch.
  713. *
  714. * It is possible to return all elements from bottom to top using a Breadth First
  715. * Search approach by passing the '$dir' parameter with 'asc'. That is, it will
  716. * return all elements for the same tree depth first and from bottom to top.
  717. *
  718. * Finally, you can specify to only get a collection with the leaf nodes in the
  719. * tree structure. You do so by passing 'leaves' in the first argument.
  720. *
  721. * The possible values for the first argument are aliases for the following
  722. * constants and it is valid to pass those instead of the alias:
  723. *
  724. * - desc: TreeIterator::SELF_FIRST
  725. * - asc: TreeIterator::CHILD_FIRST
  726. * - leaves: TreeIterator::LEAVES_ONLY
  727. *
  728. * ### Example:
  729. *
  730. * ```
  731. * $collection = new Collection([
  732. * ['id' => 1, 'children' => [['id' => 2, 'children' => [['id' => 3]]]]],
  733. * ['id' => 4, 'children' => [['id' => 5]]]
  734. * ]);
  735. * $flattenedIds = $collection->listNested()->extract('id'); // Yields [1, 2, 3, 4, 5]
  736. * ```
  737. *
  738. * @param string|int $dir The direction in which to return the elements
  739. * @param string|callable $nestingKey The key name under which children are nested
  740. * or a callable function that will return the children list
  741. * @return \Cake\Collection\CollectionInterface
  742. */
  743. public function listNested($dir = 'desc', $nestingKey = 'children');
  744. /**
  745. * Creates a new collection that when iterated will stop yielding results if
  746. * the provided condition evaluates to false.
  747. *
  748. * This is handy for dealing with infinite iterators or any generator that
  749. * could start returning invalid elements at a certain point. For example,
  750. * when reading lines from a file stream you may want to stop the iteration
  751. * after a certain value is reached.
  752. *
  753. * ### Example:
  754. *
  755. * Get an array of lines in a CSV file until the timestamp column is less than a date
  756. *
  757. * ```
  758. * $lines = (new Collection($fileLines))->stopWhen(function ($value, $key) {
  759. * return (new DateTime($value))->format('Y') < 2012;
  760. * })
  761. * ->toArray();
  762. * ```
  763. *
  764. * Get elements until the first unapproved message is found:
  765. *
  766. * ```
  767. * $comments = (new Collection($comments))->stopWhen(['is_approved' => false]);
  768. * ```
  769. *
  770. * @param callable $condition the method that will receive each of the elements and
  771. * returns false when the iteration should be stopped.
  772. * If an array, it will be interpreted as a key-value list of conditions where
  773. * the key is a property path as accepted by `Collection::extract`,
  774. * and the value the condition against with each element will be matched.
  775. * @return \Cake\Collection\CollectionInterface
  776. */
  777. public function stopWhen($condition);
  778. /**
  779. * Creates a new collection where the items are the
  780. * concatenation of the lists of items generated by the transformer function
  781. * applied to each item in the original collection.
  782. *
  783. * The transformer function will receive the value and the key for each of the
  784. * items in the collection, in that order, and it must return an array or a
  785. * Traversable object that can be concatenated to the final result.
  786. *
  787. * If no transformer function is passed, an "identity" function will be used.
  788. * This is useful when each of the elements in the source collection are
  789. * lists of items to be appended one after another.
  790. *
  791. * ### Example:
  792. *
  793. * ```
  794. * $items [[1, 2, 3], [4, 5]];
  795. * $unfold = (new Collection($items))->unfold(); // Returns [1, 2, 3, 4, 5]
  796. * ```
  797. *
  798. * Using a transformer
  799. *
  800. * ```
  801. * $items [1, 2, 3];
  802. * $allItems = (new Collection($items))->unfold(function ($page) {
  803. * return $service->fetchPage($page)->toArray();
  804. * });
  805. * ```
  806. *
  807. * @param callable|null $transformer A callable function that will receive each of
  808. * the items in the collection and should return an array or Traversable object
  809. * @return \Cake\Collection\CollectionInterface
  810. */
  811. public function unfold(callable $transformer = null);
  812. /**
  813. * Passes this collection through a callable as its first argument.
  814. * This is useful for decorating the full collection with another object.
  815. *
  816. * ### Example:
  817. *
  818. * ```
  819. * $items = [1, 2, 3];
  820. * $decorated = (new Collection($items))->through(function ($collection) {
  821. * return new MyCustomCollection($collection);
  822. * });
  823. * ```
  824. *
  825. * @param callable $handler A callable function that will receive
  826. * this collection as first argument.
  827. * @return \Cake\Collection\CollectionInterface
  828. */
  829. public function through(callable $handler);
  830. /**
  831. * Combines the elements of this collection with each of the elements of the
  832. * passed iterables, using their positional index as a reference.
  833. *
  834. * ### Example:
  835. *
  836. * ```
  837. * $collection = new Collection([1, 2]);
  838. * $collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
  839. * ```
  840. *
  841. * @param array|\Traversable ...$items The collections to zip.
  842. * @return \Cake\Collection\CollectionInterface
  843. */
  844. public function zip($items);
  845. /**
  846. * Combines the elements of this collection with each of the elements of the
  847. * passed iterables, using their positional index as a reference.
  848. *
  849. * The resulting element will be the return value of the $callable function.
  850. *
  851. * ### Example:
  852. *
  853. * ```
  854. * $collection = new Collection([1, 2]);
  855. * $zipped = $collection->zipWith([3, 4], [5, 6], function (...$args) {
  856. * return array_sum($args);
  857. * });
  858. * $zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)]
  859. * ```
  860. *
  861. * @param array|\Traversable ...$items The collections to zip.
  862. * @param callable $callable The function to use for zipping the elements together.
  863. * @return \Cake\Collection\CollectionInterface
  864. */
  865. public function zipWith($items, $callable);
  866. /**
  867. * Breaks the collection into smaller arrays of the given size.
  868. *
  869. * ### Example:
  870. *
  871. * ```
  872. * $items [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
  873. * $chunked = (new Collection($items))->chunk(3)->toList();
  874. * // Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
  875. * ```
  876. *
  877. * @param int $chunkSize The maximum size for each chunk
  878. * @return \Cake\Collection\CollectionInterface
  879. * @deprecated 4.0.0 Deprecated in favor of chunks
  880. */
  881. public function chunk($chunkSize);
  882. /**
  883. * Breaks the collection into smaller arrays of the given size.
  884. *
  885. * ### Example:
  886. *
  887. * ```
  888. * $items ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
  889. * $chunked = (new Collection($items))->chunkWithKeys(3)->toList();
  890. * // Returns [['a' => 1, 'b' => 2, 'c' => 3], ['d' => 4, 'e' => 5, 'f' => 6]]
  891. * ```
  892. *
  893. * @param int $chunkSize The maximum size for each chunk
  894. * @param bool $preserveKeys If the keys of the array should be preserved
  895. * @return \Cake\Collection\CollectionInterface
  896. */
  897. public function chunkWithKeys($chunkSize, $preserveKeys = true);
  898. /**
  899. * Returns whether or not there are elements in this collection
  900. *
  901. * ### Example:
  902. *
  903. * ```
  904. * $items [1, 2, 3];
  905. * (new Collection($items))->isEmpty(); // false
  906. * ```
  907. *
  908. * ```
  909. * (new Collection([]))->isEmpty(); // true
  910. * ```
  911. *
  912. * @return bool
  913. */
  914. public function isEmpty();
  915. /**
  916. * Returns the closest nested iterator that can be safely traversed without
  917. * losing any possible transformations. This is used mainly to remove empty
  918. * IteratorIterator wrappers that can only slowdown the iteration process.
  919. *
  920. * @return \Iterator
  921. */
  922. public function unwrap();
  923. /**
  924. * Transpose rows and columns into columns and rows
  925. *
  926. * ### Example:
  927. *
  928. * ```
  929. * $items = [
  930. * ['Products', '2012', '2013', '2014'],
  931. * ['Product A', '200', '100', '50'],
  932. * ['Product B', '300', '200', '100'],
  933. * ['Product C', '400', '300', '200'],
  934. * ]
  935. *
  936. * $transpose = (new Collection($items))->transpose()->toList();
  937. *
  938. * // Returns
  939. * // [
  940. * // ['Products', 'Product A', 'Product B', 'Product C'],
  941. * // ['2012', '200', '300', '400'],
  942. * // ['2013', '100', '200', '300'],
  943. * // ['2014', '50', '100', '200'],
  944. * // ]
  945. * ```
  946. *
  947. * @return \Cake\Collection\CollectionInterface
  948. */
  949. public function transpose();
  950. }