CollectionTrait.php 26 KB

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