CollectionInterface.php 40 KB

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