CollectionTrait.php 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  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 AppendIterator;
  17. use ArrayIterator;
  18. use Cake\Collection\Iterator\BufferedIterator;
  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\NestIterator;
  24. use Cake\Collection\Iterator\ReplaceIterator;
  25. use Cake\Collection\Iterator\SortIterator;
  26. use Cake\Collection\Iterator\StoppableIterator;
  27. use Cake\Collection\Iterator\TreeIterator;
  28. use Cake\Collection\Iterator\UnfoldIterator;
  29. use Cake\Collection\Iterator\ZipIterator;
  30. use Countable;
  31. use LimitIterator;
  32. use LogicException;
  33. use RecursiveIteratorIterator;
  34. use Traversable;
  35. /**
  36. * Offers a handful of method to manipulate iterators
  37. */
  38. trait CollectionTrait
  39. {
  40. use ExtractTrait;
  41. /**
  42. * {@inheritDoc}
  43. */
  44. public function each(callable $c)
  45. {
  46. foreach ($this->optimizeUnwrap() as $k => $v) {
  47. $c($v, $k);
  48. }
  49. return $this;
  50. }
  51. /**
  52. * {@inheritDoc}
  53. *
  54. * @return \Cake\Collection\Iterator\FilterIterator
  55. */
  56. public function filter(callable $c = null)
  57. {
  58. if ($c === null) {
  59. $c = function ($v) {
  60. return (bool)$v;
  61. };
  62. }
  63. return new FilterIterator($this->unwrap(), $c);
  64. }
  65. /**
  66. * {@inheritDoc}
  67. *
  68. * @return \Cake\Collection\Iterator\FilterIterator
  69. */
  70. public function reject(callable $c)
  71. {
  72. return new FilterIterator($this->unwrap(), function ($key, $value, $items) use ($c) {
  73. return !$c($key, $value, $items);
  74. });
  75. }
  76. /**
  77. * {@inheritDoc}
  78. */
  79. public function every(callable $c)
  80. {
  81. foreach ($this->optimizeUnwrap() as $key => $value) {
  82. if (!$c($value, $key)) {
  83. return false;
  84. }
  85. }
  86. return true;
  87. }
  88. /**
  89. * {@inheritDoc}
  90. */
  91. public function some(callable $c)
  92. {
  93. foreach ($this->optimizeUnwrap() as $key => $value) {
  94. if ($c($value, $key) === true) {
  95. return true;
  96. }
  97. }
  98. return false;
  99. }
  100. /**
  101. * {@inheritDoc}
  102. */
  103. public function contains($value)
  104. {
  105. foreach ($this->optimizeUnwrap() as $v) {
  106. if ($value === $v) {
  107. return true;
  108. }
  109. }
  110. return false;
  111. }
  112. /**
  113. * {@inheritDoc}
  114. *
  115. * @return \Cake\Collection\Iterator\ReplaceIterator
  116. */
  117. public function map(callable $c)
  118. {
  119. return new ReplaceIterator($this->unwrap(), $c);
  120. }
  121. /**
  122. * {@inheritDoc}
  123. */
  124. public function reduce(callable $c, $zero = null)
  125. {
  126. $isFirst = false;
  127. if (func_num_args() < 2) {
  128. $isFirst = true;
  129. }
  130. $result = $zero;
  131. foreach ($this->optimizeUnwrap() as $k => $value) {
  132. if ($isFirst) {
  133. $result = $value;
  134. $isFirst = false;
  135. continue;
  136. }
  137. $result = $c($result, $value, $k);
  138. }
  139. return $result;
  140. }
  141. /**
  142. * {@inheritDoc}
  143. */
  144. public function extract($matcher)
  145. {
  146. $extractor = new ExtractIterator($this->unwrap(), $matcher);
  147. if (is_string($matcher) && strpos($matcher, '{*}') !== false) {
  148. $extractor = $extractor
  149. ->filter(function ($data) {
  150. return $data !== null && ($data instanceof Traversable || is_array($data));
  151. })
  152. ->unfold();
  153. }
  154. return $extractor;
  155. }
  156. /**
  157. * {@inheritDoc}
  158. */
  159. public function max($callback, $type = \SORT_NUMERIC)
  160. {
  161. return (new SortIterator($this->unwrap(), $callback, \SORT_DESC, $type))->first();
  162. }
  163. /**
  164. * {@inheritDoc}
  165. */
  166. public function min($callback, $type = \SORT_NUMERIC)
  167. {
  168. return (new SortIterator($this->unwrap(), $callback, \SORT_ASC, $type))->first();
  169. }
  170. /**
  171. * {@inheritDoc}
  172. */
  173. public function avg($matcher = null)
  174. {
  175. $result = $this;
  176. if ($matcher != null) {
  177. $result = $result->extract($matcher);
  178. }
  179. $result = $result
  180. ->reduce(function ($acc, $current) {
  181. list($count, $sum) = $acc;
  182. return [$count + 1, $sum + $current];
  183. }, [0, 0]);
  184. if ($result[0] === 0) {
  185. return null;
  186. }
  187. return $result[1] / $result[0];
  188. }
  189. /**
  190. * {@inheritDoc}
  191. */
  192. public function median($matcher = null)
  193. {
  194. $elements = $this;
  195. if ($matcher != null) {
  196. $elements = $elements->extract($matcher);
  197. }
  198. $values = $elements->toList();
  199. sort($values);
  200. $count = count($values);
  201. if ($count === 0) {
  202. return null;
  203. }
  204. $middle = (int)($count / 2);
  205. if ($count % 2) {
  206. return $values[$middle];
  207. }
  208. return ($values[$middle - 1] + $values[$middle]) / 2;
  209. }
  210. /**
  211. * {@inheritDoc}
  212. */
  213. public function sortBy($callback, $dir = \SORT_DESC, $type = \SORT_NUMERIC)
  214. {
  215. return new SortIterator($this->unwrap(), $callback, $dir, $type);
  216. }
  217. /**
  218. * {@inheritDoc}
  219. */
  220. public function groupBy($callback)
  221. {
  222. $callback = $this->_propertyExtractor($callback);
  223. $group = [];
  224. foreach ($this->optimizeUnwrap() as $value) {
  225. $group[$callback($value)][] = $value;
  226. }
  227. return new Collection($group);
  228. }
  229. /**
  230. * {@inheritDoc}
  231. */
  232. public function indexBy($callback)
  233. {
  234. $callback = $this->_propertyExtractor($callback);
  235. $group = [];
  236. foreach ($this->optimizeUnwrap() as $value) {
  237. $group[$callback($value)] = $value;
  238. }
  239. return new Collection($group);
  240. }
  241. /**
  242. * {@inheritDoc}
  243. */
  244. public function countBy($callback)
  245. {
  246. $callback = $this->_propertyExtractor($callback);
  247. $mapper = function ($value, $key, $mr) use ($callback) {
  248. /** @var \Cake\Collection\Iterator\MapReduce $mr */
  249. $mr->emitIntermediate($value, $callback($value));
  250. };
  251. $reducer = function ($values, $key, $mr) {
  252. /** @var \Cake\Collection\Iterator\MapReduce $mr */
  253. $mr->emit(count($values), $key);
  254. };
  255. return new Collection(new MapReduce($this->unwrap(), $mapper, $reducer));
  256. }
  257. /**
  258. * {@inheritDoc}
  259. */
  260. public function sumOf($matcher = null)
  261. {
  262. if ($matcher === null) {
  263. return array_sum($this->toList());
  264. }
  265. $callback = $this->_propertyExtractor($matcher);
  266. $sum = 0;
  267. foreach ($this->optimizeUnwrap() as $k => $v) {
  268. $sum += $callback($v, $k);
  269. }
  270. return $sum;
  271. }
  272. /**
  273. * {@inheritDoc}
  274. */
  275. public function shuffle()
  276. {
  277. $elements = $this->toArray();
  278. shuffle($elements);
  279. return new Collection($elements);
  280. }
  281. /**
  282. * {@inheritDoc}
  283. */
  284. public function sample($size = 10)
  285. {
  286. return new Collection(new LimitIterator($this->shuffle(), 0, $size));
  287. }
  288. /**
  289. * {@inheritDoc}
  290. */
  291. public function take($size = 1, $from = 0)
  292. {
  293. return new Collection(new LimitIterator($this, $from, $size));
  294. }
  295. /**
  296. * {@inheritDoc}
  297. */
  298. public function skip($howMany)
  299. {
  300. return new Collection(new LimitIterator($this, $howMany));
  301. }
  302. /**
  303. * {@inheritDoc}
  304. */
  305. public function match(array $conditions)
  306. {
  307. return $this->filter($this->_createMatcherFilter($conditions));
  308. }
  309. /**
  310. * {@inheritDoc}
  311. */
  312. public function firstMatch(array $conditions)
  313. {
  314. return $this->match($conditions)->first();
  315. }
  316. /**
  317. * {@inheritDoc}
  318. */
  319. public function first()
  320. {
  321. $iterator = new LimitIterator($this, 0, 1);
  322. foreach ($iterator as $result) {
  323. return $result;
  324. }
  325. }
  326. /**
  327. * {@inheritDoc}
  328. */
  329. public function last()
  330. {
  331. $iterator = $this->optimizeUnwrap();
  332. if (is_array($iterator)) {
  333. return array_pop($iterator);
  334. }
  335. if ($iterator instanceof Countable) {
  336. $count = count($iterator);
  337. if ($count === 0) {
  338. return null;
  339. }
  340. $iterator = new LimitIterator($iterator, $count - 1, 1);
  341. }
  342. $result = null;
  343. foreach ($iterator as $result) {
  344. // No-op
  345. }
  346. return $result;
  347. }
  348. /**
  349. * {@inheritDoc}
  350. */
  351. public function takeLast($howMany)
  352. {
  353. if ($howMany < 1) {
  354. throw new \InvalidArgumentException("The takeLast method requires a number greater than 0.");
  355. }
  356. $iterator = $this->optimizeUnwrap();
  357. if (is_array($iterator)) {
  358. return new Collection(array_slice($iterator, $howMany * -1));
  359. }
  360. if ($iterator instanceof Countable) {
  361. $count = count($iterator);
  362. if ($count === 0) {
  363. return new Collection([]);
  364. }
  365. $iterator = new LimitIterator($iterator, max(0, $count - $howMany), $howMany);
  366. return new Collection($iterator);
  367. }
  368. $generator = function ($iterator, $howMany) {
  369. $result = [];
  370. $bucket = 0;
  371. $offset = 0;
  372. /**
  373. * Consider the collection of elements [1, 2, 3, 4, 5, 6, 7, 8, 9], in order
  374. * to get the last 4 elements, we can keep a buffer of 4 elements and
  375. * fill it circularly using modulo logic, we use the $bucket variable
  376. * to track the position to fill next in the buffer. This how the buffer
  377. * looks like after 4 iterations:
  378. *
  379. * 0) 1 2 3 4 -- $bucket now goes back to 0, we have filled 4 elementes
  380. * 1) 5 2 3 4 -- 5th iteration
  381. * 2) 5 6 3 4 -- 6th iteration
  382. * 3) 5 6 7 4 -- 7th iteration
  383. * 4) 5 6 7 8 -- 8th iteration
  384. * 5) 9 6 7 8
  385. *
  386. * We can see that at the end of the iterations, the buffer contains all
  387. * the last four elements, just in the wrong order. How do we keep the
  388. * original order? Well, it turns out that the number of iteration also
  389. * give us a clue on what's going on, Let's add a marker for it now:
  390. *
  391. * 0) 1 2 3 4
  392. * ^ -- The 0) above now becomes the $offset variable
  393. * 1) 5 2 3 4
  394. * ^ -- $offset = 1
  395. * 2) 5 6 3 4
  396. * ^ -- $offset = 2
  397. * 3) 5 6 7 4
  398. * ^ -- $offset = 3
  399. * 4) 5 6 7 8
  400. * ^ -- We use module logic for $offset too
  401. * and as you can see each time $offset is 0, then the buffer
  402. * is sorted exactly as we need.
  403. * 5) 9 6 7 8
  404. * ^ -- $offset = 1
  405. *
  406. * The $offset variable is a marker for splitting the buffer in two,
  407. * elements to the right for the marker are the head of the final result,
  408. * whereas the elements at the left are the tail. For example consider step 5)
  409. * which has an offset of 1:
  410. *
  411. * - $head = elements to the right = [6, 7, 8]
  412. * - $tail = elements to the left = [9]
  413. * - $result = $head + $tail = [6, 7, 8, 9]
  414. *
  415. * The logic above applies to collections of any size.
  416. */
  417. foreach ($iterator as $k => $item) {
  418. $result[$bucket] = [$k, $item];
  419. $bucket = (++$bucket) % $howMany;
  420. $offset++;
  421. }
  422. $offset = $offset % $howMany;
  423. $head = array_slice($result, $offset);
  424. $tail = array_slice($result, 0, $offset);
  425. foreach ($head as $v) {
  426. yield $v[0] => $v[1];
  427. }
  428. foreach ($tail as $v) {
  429. yield $v[0] => $v[1];
  430. }
  431. };
  432. return new Collection($generator($iterator, $howMany));
  433. }
  434. /**
  435. * {@inheritDoc}
  436. */
  437. public function append($items)
  438. {
  439. $list = new AppendIterator();
  440. $list->append($this->unwrap());
  441. $list->append((new Collection($items))->unwrap());
  442. return new Collection($list);
  443. }
  444. /**
  445. * {@inheritDoc}
  446. */
  447. public function appendItem($item, $key = null)
  448. {
  449. if ($key !== null) {
  450. $data = [$key => $item];
  451. } else {
  452. $data = [$item];
  453. }
  454. return $this->append($data);
  455. }
  456. /**
  457. * {@inheritDoc}
  458. */
  459. public function prepend($items)
  460. {
  461. return (new Collection($items))->append($this);
  462. }
  463. /**
  464. * {@inheritDoc}
  465. */
  466. public function prependItem($item, $key = null)
  467. {
  468. if ($key !== null) {
  469. $data = [$key => $item];
  470. } else {
  471. $data = [$item];
  472. }
  473. return $this->prepend($data);
  474. }
  475. /**
  476. * {@inheritDoc}
  477. */
  478. public function combine($keyPath, $valuePath, $groupPath = null)
  479. {
  480. $options = [
  481. 'keyPath' => $this->_propertyExtractor($keyPath),
  482. 'valuePath' => $this->_propertyExtractor($valuePath),
  483. 'groupPath' => $groupPath ? $this->_propertyExtractor($groupPath) : null
  484. ];
  485. $mapper = function ($value, $key, $mapReduce) use ($options) {
  486. /** @var \Cake\Collection\Iterator\MapReduce $mapReduce */
  487. $rowKey = $options['keyPath'];
  488. $rowVal = $options['valuePath'];
  489. if (!$options['groupPath']) {
  490. $mapReduce->emit($rowVal($value, $key), $rowKey($value, $key));
  491. return null;
  492. }
  493. $key = $options['groupPath']($value, $key);
  494. $mapReduce->emitIntermediate(
  495. [$rowKey($value, $key) => $rowVal($value, $key)],
  496. $key
  497. );
  498. };
  499. $reducer = function ($values, $key, $mapReduce) {
  500. $result = [];
  501. foreach ($values as $value) {
  502. $result += $value;
  503. }
  504. /** @var \Cake\Collection\Iterator\MapReduce $mapReduce */
  505. $mapReduce->emit($result, $key);
  506. };
  507. return new Collection(new MapReduce($this->unwrap(), $mapper, $reducer));
  508. }
  509. /**
  510. * {@inheritDoc}
  511. */
  512. public function nest($idPath, $parentPath, $nestingKey = 'children')
  513. {
  514. $parents = [];
  515. $idPath = $this->_propertyExtractor($idPath);
  516. $parentPath = $this->_propertyExtractor($parentPath);
  517. $isObject = true;
  518. $mapper = function ($row, $key, $mapReduce) use (&$parents, $idPath, $parentPath, $nestingKey) {
  519. $row[$nestingKey] = [];
  520. $id = $idPath($row, $key);
  521. $parentId = $parentPath($row, $key);
  522. $parents[$id] =& $row;
  523. /** @var \Cake\Collection\Iterator\MapReduce $mapReduce */
  524. $mapReduce->emitIntermediate($id, $parentId);
  525. };
  526. $reducer = function ($values, $key, $mapReduce) use (&$parents, &$isObject, $nestingKey) {
  527. static $foundOutType = false;
  528. if (!$foundOutType) {
  529. $isObject = is_object(current($parents));
  530. $foundOutType = true;
  531. }
  532. if (empty($key) || !isset($parents[$key])) {
  533. foreach ($values as $id) {
  534. $parents[$id] = $isObject ? $parents[$id] : new ArrayIterator($parents[$id], 1);
  535. /** @var \Cake\Collection\Iterator\MapReduce $mapReduce */
  536. $mapReduce->emit($parents[$id]);
  537. }
  538. return null;
  539. }
  540. $children = [];
  541. foreach ($values as $id) {
  542. $children[] =& $parents[$id];
  543. }
  544. $parents[$key][$nestingKey] = $children;
  545. };
  546. return (new Collection(new MapReduce($this->unwrap(), $mapper, $reducer)))
  547. ->map(function ($value) use (&$isObject) {
  548. /** @var \ArrayIterator $value */
  549. return $isObject ? $value : $value->getArrayCopy();
  550. });
  551. }
  552. /**
  553. * {@inheritDoc}
  554. *
  555. * @return \Cake\Collection\Iterator\InsertIterator
  556. */
  557. public function insert($path, $values)
  558. {
  559. return new InsertIterator($this->unwrap(), $path, $values);
  560. }
  561. /**
  562. * {@inheritDoc}
  563. */
  564. public function toArray($preserveKeys = true)
  565. {
  566. $iterator = $this->unwrap();
  567. if ($iterator instanceof ArrayIterator) {
  568. $items = $iterator->getArrayCopy();
  569. return $preserveKeys ? $items : array_values($items);
  570. }
  571. // RecursiveIteratorIterator can return duplicate key values causing
  572. // data loss when converted into an array
  573. if ($preserveKeys && get_class($iterator) === 'RecursiveIteratorIterator') {
  574. $preserveKeys = false;
  575. }
  576. return iterator_to_array($this, $preserveKeys);
  577. }
  578. /**
  579. * {@inheritDoc}
  580. */
  581. public function toList()
  582. {
  583. return $this->toArray(false);
  584. }
  585. /**
  586. * {@inheritDoc}
  587. */
  588. public function jsonSerialize()
  589. {
  590. return $this->toArray();
  591. }
  592. /**
  593. * {@inheritDoc}
  594. */
  595. public function compile($preserveKeys = true)
  596. {
  597. return new Collection($this->toArray($preserveKeys));
  598. }
  599. /**
  600. * {@inheritDoc}
  601. */
  602. public function lazy()
  603. {
  604. $generator = function () {
  605. foreach ($this->unwrap() as $k => $v) {
  606. yield $k => $v;
  607. }
  608. };
  609. return new Collection($generator());
  610. }
  611. /**
  612. * {@inheritDoc}
  613. *
  614. * @return \Cake\Collection\Iterator\BufferedIterator
  615. */
  616. public function buffered()
  617. {
  618. return new BufferedIterator($this->unwrap());
  619. }
  620. /**
  621. * {@inheritDoc}
  622. *
  623. * @return \Cake\Collection\Iterator\TreeIterator
  624. */
  625. public function listNested($dir = 'desc', $nestingKey = 'children')
  626. {
  627. $dir = strtolower($dir);
  628. $modes = [
  629. 'desc' => TreeIterator::SELF_FIRST,
  630. 'asc' => TreeIterator::CHILD_FIRST,
  631. 'leaves' => TreeIterator::LEAVES_ONLY
  632. ];
  633. return new TreeIterator(
  634. new NestIterator($this, $nestingKey),
  635. isset($modes[$dir]) ? $modes[$dir] : $dir
  636. );
  637. }
  638. /**
  639. * {@inheritDoc}
  640. *
  641. * @return \Cake\Collection\Iterator\StoppableIterator
  642. */
  643. public function stopWhen($condition)
  644. {
  645. if (!is_callable($condition)) {
  646. $condition = $this->_createMatcherFilter($condition);
  647. }
  648. return new StoppableIterator($this->unwrap(), $condition);
  649. }
  650. /**
  651. * {@inheritDoc}
  652. */
  653. public function unfold(callable $transformer = null)
  654. {
  655. if ($transformer === null) {
  656. $transformer = function ($item) {
  657. return $item;
  658. };
  659. }
  660. return new Collection(
  661. new RecursiveIteratorIterator(
  662. new UnfoldIterator($this->unwrap(), $transformer),
  663. RecursiveIteratorIterator::LEAVES_ONLY
  664. )
  665. );
  666. }
  667. /**
  668. * {@inheritDoc}
  669. */
  670. public function through(callable $handler)
  671. {
  672. $result = $handler($this);
  673. return $result instanceof CollectionInterface ? $result : new Collection($result);
  674. }
  675. /**
  676. * {@inheritDoc}
  677. */
  678. public function zip($items)
  679. {
  680. return new ZipIterator(array_merge([$this->unwrap()], func_get_args()));
  681. }
  682. /**
  683. * {@inheritDoc}
  684. */
  685. public function zipWith($items, $callable)
  686. {
  687. if (func_num_args() > 2) {
  688. $items = func_get_args();
  689. $callable = array_pop($items);
  690. } else {
  691. $items = [$items];
  692. }
  693. return new ZipIterator(array_merge([$this->unwrap()], $items), $callable);
  694. }
  695. /**
  696. * {@inheritDoc}
  697. */
  698. public function chunk($chunkSize)
  699. {
  700. return $this->map(function ($v, $k, $iterator) use ($chunkSize) {
  701. $values = [$v];
  702. for ($i = 1; $i < $chunkSize; $i++) {
  703. $iterator->next();
  704. if (!$iterator->valid()) {
  705. break;
  706. }
  707. $values[] = $iterator->current();
  708. }
  709. return $values;
  710. });
  711. }
  712. /**
  713. * {@inheritDoc}
  714. */
  715. public function chunkWithKeys($chunkSize, $preserveKeys = true)
  716. {
  717. return $this->map(function ($v, $k, $iterator) use ($chunkSize, $preserveKeys) {
  718. $key = 0;
  719. if ($preserveKeys) {
  720. $key = $k;
  721. }
  722. $values = [$key => $v];
  723. for ($i = 1; $i < $chunkSize; $i++) {
  724. $iterator->next();
  725. if (!$iterator->valid()) {
  726. break;
  727. }
  728. if ($preserveKeys) {
  729. $values[$iterator->key()] = $iterator->current();
  730. } else {
  731. $values[] = $iterator->current();
  732. }
  733. }
  734. return $values;
  735. });
  736. }
  737. /**
  738. * {@inheritDoc}
  739. */
  740. public function isEmpty()
  741. {
  742. foreach ($this as $el) {
  743. return false;
  744. }
  745. return true;
  746. }
  747. /**
  748. * {@inheritDoc}
  749. */
  750. public function unwrap()
  751. {
  752. $iterator = $this;
  753. while (get_class($iterator) === 'Cake\Collection\Collection') {
  754. $iterator = $iterator->getInnerIterator();
  755. }
  756. if ($iterator !== $this && $iterator instanceof CollectionInterface) {
  757. $iterator = $iterator->unwrap();
  758. }
  759. return $iterator;
  760. }
  761. /**
  762. * Backwards compatible wrapper for unwrap()
  763. *
  764. * @return \Traversable
  765. * @deprecated 3.0.10 Will be removed in 4.0.0
  766. */
  767. // @codingStandardsIgnoreLine
  768. public function _unwrap()
  769. {
  770. deprecationWarning('CollectionTrait::_unwrap() is deprecated. Use CollectionTrait::unwrap() instead.');
  771. return $this->unwrap();
  772. }
  773. /**
  774. * @param callable|null $operation Operation
  775. * @param callable|null $filter Filter
  776. * @return \Cake\Collection\CollectionInterface
  777. * @throws \LogicException
  778. */
  779. public function cartesianProduct(callable $operation = null, callable $filter = null)
  780. {
  781. if ($this->isEmpty()) {
  782. return new Collection([]);
  783. }
  784. $collectionArrays = [];
  785. $collectionArraysKeys = [];
  786. $collectionArraysCounts = [];
  787. foreach ($this->toList() as $value) {
  788. $valueCount = count($value);
  789. if ($valueCount !== count($value, COUNT_RECURSIVE)) {
  790. throw new LogicException('Cannot find the cartesian product of a multidimensional array');
  791. }
  792. $collectionArraysKeys[] = array_keys($value);
  793. $collectionArraysCounts[] = $valueCount;
  794. $collectionArrays[] = $value;
  795. }
  796. $result = [];
  797. $lastIndex = count($collectionArrays) - 1;
  798. // holds the indexes of the arrays that generate the current combination
  799. $currentIndexes = array_fill(0, $lastIndex + 1, 0);
  800. $changeIndex = $lastIndex;
  801. while (!($changeIndex === 0 && $currentIndexes[0] === $collectionArraysCounts[0])) {
  802. $currentCombination = array_map(function ($value, $keys, $index) {
  803. return $value[$keys[$index]];
  804. }, $collectionArrays, $collectionArraysKeys, $currentIndexes);
  805. if ($filter === null || $filter($currentCombination)) {
  806. $result[] = ($operation === null) ? $currentCombination : $operation($currentCombination);
  807. }
  808. $currentIndexes[$lastIndex]++;
  809. for ($changeIndex = $lastIndex; $currentIndexes[$changeIndex] === $collectionArraysCounts[$changeIndex] && $changeIndex > 0; $changeIndex--) {
  810. $currentIndexes[$changeIndex] = 0;
  811. $currentIndexes[$changeIndex - 1]++;
  812. }
  813. }
  814. return new Collection($result);
  815. }
  816. /**
  817. * {@inheritDoc}
  818. *
  819. * @return \Cake\Collection\CollectionInterface
  820. * @throws \LogicException
  821. */
  822. public function transpose()
  823. {
  824. $arrayValue = $this->toList();
  825. $length = count(current($arrayValue));
  826. $result = [];
  827. foreach ($arrayValue as $column => $row) {
  828. if (count($row) != $length) {
  829. throw new LogicException('Child arrays do not have even length');
  830. }
  831. }
  832. for ($column = 0; $column < $length; $column++) {
  833. $result[] = array_column($arrayValue, $column);
  834. }
  835. return new Collection($result);
  836. }
  837. /**
  838. * {@inheritDoc}
  839. *
  840. * @return int
  841. */
  842. public function count()
  843. {
  844. $traversable = $this->optimizeUnwrap();
  845. if (is_array($traversable)) {
  846. return count($traversable);
  847. }
  848. return iterator_count($traversable);
  849. }
  850. /**
  851. * {@inheritDoc}
  852. *
  853. * @return int
  854. */
  855. public function countKeys()
  856. {
  857. return count($this->toArray());
  858. }
  859. /**
  860. * Unwraps this iterator and returns the simplest
  861. * traversable that can be used for getting the data out
  862. *
  863. * @return \Traversable|array
  864. */
  865. protected function optimizeUnwrap()
  866. {
  867. $iterator = $this->unwrap();
  868. if (get_class($iterator) === ArrayIterator::class) {
  869. $iterator = $iterator->getArrayCopy();
  870. }
  871. return $iterator;
  872. }
  873. }