CollectionInterface.php 33 KB

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