CollectionTrait.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  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. $mr->emitIntermediate($value, $callback($value));
  249. };
  250. $reducer = function ($values, $key, $mr) {
  251. $mr->emit(count($values), $key);
  252. };
  253. return new Collection(new MapReduce($this->unwrap(), $mapper, $reducer));
  254. }
  255. /**
  256. * {@inheritDoc}
  257. */
  258. public function sumOf($matcher = null)
  259. {
  260. if ($matcher === null) {
  261. return array_sum($this->toList());
  262. }
  263. $callback = $this->_propertyExtractor($matcher);
  264. $sum = 0;
  265. foreach ($this->optimizeUnwrap() as $k => $v) {
  266. $sum += $callback($v, $k);
  267. }
  268. return $sum;
  269. }
  270. /**
  271. * {@inheritDoc}
  272. */
  273. public function shuffle()
  274. {
  275. $elements = $this->toArray();
  276. shuffle($elements);
  277. return new Collection($elements);
  278. }
  279. /**
  280. * {@inheritDoc}
  281. */
  282. public function sample($size = 10)
  283. {
  284. return new Collection(new LimitIterator($this->shuffle(), 0, $size));
  285. }
  286. /**
  287. * {@inheritDoc}
  288. */
  289. public function take($size = 1, $from = 0)
  290. {
  291. return new Collection(new LimitIterator($this, $from, $size));
  292. }
  293. /**
  294. * {@inheritDoc}
  295. */
  296. public function skip($howMany)
  297. {
  298. return new Collection(new LimitIterator($this, $howMany));
  299. }
  300. /**
  301. * {@inheritDoc}
  302. */
  303. public function match(array $conditions)
  304. {
  305. return $this->filter($this->_createMatcherFilter($conditions));
  306. }
  307. /**
  308. * {@inheritDoc}
  309. */
  310. public function firstMatch(array $conditions)
  311. {
  312. return $this->match($conditions)->first();
  313. }
  314. /**
  315. * {@inheritDoc}
  316. */
  317. public function first()
  318. {
  319. $iterator = new LimitIterator($this, 0, 1);
  320. foreach ($iterator as $result) {
  321. return $result;
  322. }
  323. }
  324. /**
  325. * {@inheritDoc}
  326. */
  327. public function last()
  328. {
  329. $iterator = $this->optimizeUnwrap();
  330. if (is_array($iterator)) {
  331. return array_pop($iterator);
  332. }
  333. if ($iterator instanceof Countable) {
  334. $count = count($iterator);
  335. if ($count === 0) {
  336. return null;
  337. }
  338. $iterator = new LimitIterator($iterator, $count - 1, 1);
  339. }
  340. $result = null;
  341. foreach ($iterator as $result) {
  342. // No-op
  343. }
  344. return $result;
  345. }
  346. /**
  347. * {@inheritDoc}
  348. */
  349. public function takeLast($howMany)
  350. {
  351. if ($howMany < 1) {
  352. throw new \InvalidArgumentException("The takeLast method requires a number greater than 0.");
  353. }
  354. $iterator = $this->optimizeUnwrap();
  355. if (is_array($iterator)) {
  356. return new Collection(array_slice($iterator, $howMany * -1));
  357. }
  358. if ($iterator instanceof Countable) {
  359. $count = count($iterator);
  360. if ($count === 0) {
  361. return new Collection([]);
  362. }
  363. $iterator = new LimitIterator($iterator, max(0, $count - $howMany), $howMany);
  364. return new Collection($iterator);
  365. }
  366. $generator = function ($iterator, $howMany) {
  367. $result = [];
  368. $bucket = 0;
  369. $offset = 0;
  370. /**
  371. * Consider the collection of elements [1, 2, 3, 4, 5, 6, 7, 8, 9], in order
  372. * to get the last 4 elements, we can keep a buffer of 4 elements and
  373. * fill it circularly using modulo logic, we use the $bucket variable
  374. * to track the position to fill next in the buffer. This how the buffer
  375. * looks like after 4 iterations:
  376. *
  377. * 0) 1 2 3 4 -- $bucket now goes back to 0, we have filled 4 elementes
  378. * 1) 5 2 3 4 -- 5th iteration
  379. * 2) 5 6 3 4 -- 6th iteration
  380. * 3) 5 6 7 4 -- 7th iteration
  381. * 4) 5 6 7 8 -- 8th iteration
  382. * 5) 9 6 7 8
  383. *
  384. * We can see that at the end of the iterations, the buffer contains all
  385. * the last four elements, just in the wrong order. How do we keep the
  386. * original order? Well, it turns out that the number of iteration also
  387. * give us a clue on what's going on, Let's add a marker for it now:
  388. *
  389. * 0) 1 2 3 4
  390. * ^ -- The 0) above now becomes the $offset variable
  391. * 1) 5 2 3 4
  392. * ^ -- $offset = 1
  393. * 2) 5 6 3 4
  394. * ^ -- $offset = 2
  395. * 3) 5 6 7 4
  396. * ^ -- $offset = 3
  397. * 4) 5 6 7 8
  398. * ^ -- We use module logic for $offset too
  399. * and as you can see each time $offset is 0, then the buffer
  400. * is sorted exactly as we need.
  401. * 5) 9 6 7 8
  402. * ^ -- $offset = 1
  403. *
  404. * The $offset variable is a marker for splitting the buffer in two,
  405. * elements to the right for the marker are the head of the final result,
  406. * whereas the elements at the left are the tail. For example consider step 5)
  407. * which has an offset of 1:
  408. *
  409. * - $head = elements to the right = [6, 7, 8]
  410. * - $tail = elements to the left = [9]
  411. * - $result = $head + $tail = [6, 7, 8, 9]
  412. *
  413. * The logic above applies to collections of any size.
  414. */
  415. foreach ($iterator as $k => $item) {
  416. $result[$bucket] = [$k, $item];
  417. $bucket = (++$bucket) % $howMany;
  418. $offset++;
  419. }
  420. $offset = $offset % $howMany;
  421. $head = array_slice($result, $offset);
  422. $tail = array_slice($result, 0, $offset);
  423. foreach ($head as $v) {
  424. yield $v[0] => $v[1];
  425. }
  426. foreach ($tail as $v) {
  427. yield $v[0] => $v[1];
  428. }
  429. };
  430. return new Collection($generator($iterator, $howMany));
  431. }
  432. /**
  433. * {@inheritDoc}
  434. */
  435. public function append($items)
  436. {
  437. $list = new AppendIterator();
  438. $list->append($this->unwrap());
  439. $list->append((new Collection($items))->unwrap());
  440. return new Collection($list);
  441. }
  442. /**
  443. * {@inheritDoc}
  444. */
  445. public function appendItem($item, $key = null)
  446. {
  447. if ($key !== null) {
  448. $data = [$key => $item];
  449. } else {
  450. $data = [$item];
  451. }
  452. return $this->append($data);
  453. }
  454. /**
  455. * {@inheritDoc}
  456. */
  457. public function prepend($items)
  458. {
  459. return (new Collection($items))->append($this);
  460. }
  461. /**
  462. * {@inheritDoc}
  463. */
  464. public function prependItem($item, $key = null)
  465. {
  466. if ($key !== null) {
  467. $data = [$key => $item];
  468. } else {
  469. $data = [$item];
  470. }
  471. return $this->prepend($data);
  472. }
  473. /**
  474. * {@inheritDoc}
  475. */
  476. public function combine($keyPath, $valuePath, $groupPath = null)
  477. {
  478. $options = [
  479. 'keyPath' => $this->_propertyExtractor($keyPath),
  480. 'valuePath' => $this->_propertyExtractor($valuePath),
  481. 'groupPath' => $groupPath ? $this->_propertyExtractor($groupPath) : null
  482. ];
  483. $mapper = function ($value, $key, $mapReduce) use ($options) {
  484. $rowKey = $options['keyPath'];
  485. $rowVal = $options['valuePath'];
  486. if (!$options['groupPath']) {
  487. $mapReduce->emit($rowVal($value, $key), $rowKey($value, $key));
  488. return null;
  489. }
  490. $key = $options['groupPath']($value, $key);
  491. $mapReduce->emitIntermediate(
  492. [$rowKey($value, $key) => $rowVal($value, $key)],
  493. $key
  494. );
  495. };
  496. $reducer = function ($values, $key, $mapReduce) {
  497. $result = [];
  498. foreach ($values as $value) {
  499. $result += $value;
  500. }
  501. $mapReduce->emit($result, $key);
  502. };
  503. return new Collection(new MapReduce($this->unwrap(), $mapper, $reducer));
  504. }
  505. /**
  506. * {@inheritDoc}
  507. */
  508. public function nest($idPath, $parentPath, $nestingKey = 'children')
  509. {
  510. $parents = [];
  511. $idPath = $this->_propertyExtractor($idPath);
  512. $parentPath = $this->_propertyExtractor($parentPath);
  513. $isObject = true;
  514. $mapper = function ($row, $key, $mapReduce) use (&$parents, $idPath, $parentPath, $nestingKey) {
  515. $row[$nestingKey] = [];
  516. $id = $idPath($row, $key);
  517. $parentId = $parentPath($row, $key);
  518. $parents[$id] =& $row;
  519. $mapReduce->emitIntermediate($id, $parentId);
  520. };
  521. $reducer = function ($values, $key, $mapReduce) use (&$parents, &$isObject, $nestingKey) {
  522. static $foundOutType = false;
  523. if (!$foundOutType) {
  524. $isObject = is_object(current($parents));
  525. $foundOutType = true;
  526. }
  527. if (empty($key) || !isset($parents[$key])) {
  528. foreach ($values as $id) {
  529. $parents[$id] = $isObject ? $parents[$id] : new ArrayIterator($parents[$id], 1);
  530. $mapReduce->emit($parents[$id]);
  531. }
  532. return null;
  533. }
  534. $children = [];
  535. foreach ($values as $id) {
  536. $children[] =& $parents[$id];
  537. }
  538. $parents[$key][$nestingKey] = $children;
  539. };
  540. return (new Collection(new MapReduce($this->unwrap(), $mapper, $reducer)))
  541. ->map(function ($value) use (&$isObject) {
  542. return $isObject ? $value : $value->getArrayCopy();
  543. });
  544. }
  545. /**
  546. * {@inheritDoc}
  547. *
  548. * @return \Cake\Collection\Iterator\InsertIterator
  549. */
  550. public function insert($path, $values)
  551. {
  552. return new InsertIterator($this->unwrap(), $path, $values);
  553. }
  554. /**
  555. * {@inheritDoc}
  556. */
  557. public function toArray($preserveKeys = true)
  558. {
  559. $iterator = $this->unwrap();
  560. if ($iterator instanceof ArrayIterator) {
  561. $items = $iterator->getArrayCopy();
  562. return $preserveKeys ? $items : array_values($items);
  563. }
  564. // RecursiveIteratorIterator can return duplicate key values causing
  565. // data loss when converted into an array
  566. if ($preserveKeys && get_class($iterator) === 'RecursiveIteratorIterator') {
  567. $preserveKeys = false;
  568. }
  569. return iterator_to_array($this, $preserveKeys);
  570. }
  571. /**
  572. * {@inheritDoc}
  573. */
  574. public function toList()
  575. {
  576. return $this->toArray(false);
  577. }
  578. /**
  579. * {@inheritDoc}
  580. */
  581. public function jsonSerialize()
  582. {
  583. return $this->toArray();
  584. }
  585. /**
  586. * {@inheritDoc}
  587. */
  588. public function compile($preserveKeys = true)
  589. {
  590. return new Collection($this->toArray($preserveKeys));
  591. }
  592. /**
  593. * {@inheritDoc}
  594. *
  595. * @return \Cake\Collection\Iterator\BufferedIterator
  596. */
  597. public function buffered()
  598. {
  599. return new BufferedIterator($this->unwrap());
  600. }
  601. /**
  602. * {@inheritDoc}
  603. *
  604. * @return \Cake\Collection\Iterator\TreeIterator
  605. */
  606. public function listNested($dir = 'desc', $nestingKey = 'children')
  607. {
  608. $dir = strtolower($dir);
  609. $modes = [
  610. 'desc' => TreeIterator::SELF_FIRST,
  611. 'asc' => TreeIterator::CHILD_FIRST,
  612. 'leaves' => TreeIterator::LEAVES_ONLY
  613. ];
  614. return new TreeIterator(
  615. new NestIterator($this, $nestingKey),
  616. isset($modes[$dir]) ? $modes[$dir] : $dir
  617. );
  618. }
  619. /**
  620. * {@inheritDoc}
  621. *
  622. * @return \Cake\Collection\Iterator\StoppableIterator
  623. */
  624. public function stopWhen($condition)
  625. {
  626. if (!is_callable($condition)) {
  627. $condition = $this->_createMatcherFilter($condition);
  628. }
  629. return new StoppableIterator($this->unwrap(), $condition);
  630. }
  631. /**
  632. * {@inheritDoc}
  633. */
  634. public function unfold(callable $transformer = null)
  635. {
  636. if ($transformer === null) {
  637. $transformer = function ($item) {
  638. return $item;
  639. };
  640. }
  641. return new Collection(
  642. new RecursiveIteratorIterator(
  643. new UnfoldIterator($this->unwrap(), $transformer),
  644. RecursiveIteratorIterator::LEAVES_ONLY
  645. )
  646. );
  647. }
  648. /**
  649. * {@inheritDoc}
  650. */
  651. public function through(callable $handler)
  652. {
  653. $result = $handler($this);
  654. return $result instanceof CollectionInterface ? $result : new Collection($result);
  655. }
  656. /**
  657. * {@inheritDoc}
  658. */
  659. public function zip($items)
  660. {
  661. return new ZipIterator(array_merge([$this->unwrap()], func_get_args()));
  662. }
  663. /**
  664. * {@inheritDoc}
  665. */
  666. public function zipWith($items, $callable)
  667. {
  668. if (func_num_args() > 2) {
  669. $items = func_get_args();
  670. $callable = array_pop($items);
  671. } else {
  672. $items = [$items];
  673. }
  674. return new ZipIterator(array_merge([$this->unwrap()], $items), $callable);
  675. }
  676. /**
  677. * {@inheritDoc}
  678. */
  679. public function chunk($chunkSize)
  680. {
  681. return $this->map(function ($v, $k, $iterator) use ($chunkSize) {
  682. $values = [$v];
  683. for ($i = 1; $i < $chunkSize; $i++) {
  684. $iterator->next();
  685. if (!$iterator->valid()) {
  686. break;
  687. }
  688. $values[] = $iterator->current();
  689. }
  690. return $values;
  691. });
  692. }
  693. /**
  694. * {@inheritDoc}
  695. */
  696. public function chunkWithKeys($chunkSize, $preserveKeys = true)
  697. {
  698. return $this->map(function ($v, $k, $iterator) use ($chunkSize, $preserveKeys) {
  699. $key = 0;
  700. if ($preserveKeys) {
  701. $key = $k;
  702. }
  703. $values = [$key => $v];
  704. for ($i = 1; $i < $chunkSize; $i++) {
  705. $iterator->next();
  706. if (!$iterator->valid()) {
  707. break;
  708. }
  709. if ($preserveKeys) {
  710. $values[$iterator->key()] = $iterator->current();
  711. } else {
  712. $values[] = $iterator->current();
  713. }
  714. }
  715. return $values;
  716. });
  717. }
  718. /**
  719. * {@inheritDoc}
  720. */
  721. public function isEmpty()
  722. {
  723. foreach ($this as $el) {
  724. return false;
  725. }
  726. return true;
  727. }
  728. /**
  729. * {@inheritDoc}
  730. */
  731. public function unwrap()
  732. {
  733. $iterator = $this;
  734. while (get_class($iterator) === 'Cake\Collection\Collection') {
  735. $iterator = $iterator->getInnerIterator();
  736. }
  737. if ($iterator !== $this && $iterator instanceof CollectionInterface) {
  738. $iterator = $iterator->unwrap();
  739. }
  740. return $iterator;
  741. }
  742. /**
  743. * Backwards compatible wrapper for unwrap()
  744. *
  745. * @return \Traversable
  746. * @deprecated 3.0.10 Will be removed in 4.0.0
  747. */
  748. // @codingStandardsIgnoreLine
  749. public function _unwrap()
  750. {
  751. deprecationWarning('CollectionTrait::_unwrap() is deprecated. Use CollectionTrait::unwrap() instead.');
  752. return $this->unwrap();
  753. }
  754. /**
  755. * {@inheritDoc}
  756. *
  757. * @return \Cake\Collection\CollectionInterface
  758. */
  759. public function cartesianProduct(callable $operation = null, callable $filter = null)
  760. {
  761. if ($this->isEmpty()) {
  762. return new Collection([]);
  763. }
  764. $collectionArrays = [];
  765. $collectionArraysKeys = [];
  766. $collectionArraysCounts = [];
  767. foreach ($this->toList() as $value) {
  768. $valueCount = count($value);
  769. if ($valueCount !== count($value, COUNT_RECURSIVE)) {
  770. throw new LogicException('Cannot find the cartesian product of a multidimensional array');
  771. }
  772. $collectionArraysKeys[] = array_keys($value);
  773. $collectionArraysCounts[] = $valueCount;
  774. $collectionArrays[] = $value;
  775. }
  776. $result = [];
  777. $lastIndex = count($collectionArrays) - 1;
  778. // holds the indexes of the arrays that generate the current combination
  779. $currentIndexes = array_fill(0, $lastIndex + 1, 0);
  780. $changeIndex = $lastIndex;
  781. while (!($changeIndex === 0 && $currentIndexes[0] === $collectionArraysCounts[0])) {
  782. $currentCombination = array_map(function ($value, $keys, $index) {
  783. return $value[$keys[$index]];
  784. }, $collectionArrays, $collectionArraysKeys, $currentIndexes);
  785. if ($filter === null || $filter($currentCombination)) {
  786. $result[] = ($operation === null) ? $currentCombination : $operation($currentCombination);
  787. }
  788. $currentIndexes[$lastIndex]++;
  789. for ($changeIndex = $lastIndex; $currentIndexes[$changeIndex] === $collectionArraysCounts[$changeIndex] && $changeIndex > 0; $changeIndex--) {
  790. $currentIndexes[$changeIndex] = 0;
  791. $currentIndexes[$changeIndex - 1]++;
  792. }
  793. }
  794. return new Collection($result);
  795. }
  796. /**
  797. * {@inheritDoc}
  798. *
  799. * @return \Cake\Collection\CollectionInterface
  800. */
  801. public function transpose()
  802. {
  803. $arrayValue = $this->toList();
  804. $length = count(current($arrayValue));
  805. $result = [];
  806. foreach ($arrayValue as $column => $row) {
  807. if (count($row) != $length) {
  808. throw new LogicException('Child arrays do not have even length');
  809. }
  810. }
  811. for ($column = 0; $column < $length; $column++) {
  812. $result[] = array_column($arrayValue, $column);
  813. }
  814. return new Collection($result);
  815. }
  816. /**
  817. * {@inheritDoc}
  818. *
  819. * @return int
  820. */
  821. public function count()
  822. {
  823. $traversable = $this->optimizeUnwrap();
  824. if (is_array($traversable)) {
  825. return count($traversable);
  826. }
  827. return iterator_count($traversable);
  828. }
  829. /**
  830. * {@inheritDoc}
  831. *
  832. * @return int
  833. */
  834. public function countKeys()
  835. {
  836. return count($this->toArray());
  837. }
  838. /**
  839. * Unwraps this iterator and returns the simplest
  840. * traversable that can be used for getting the data out
  841. *
  842. * @return \Traversable|array
  843. */
  844. protected function optimizeUnwrap()
  845. {
  846. $iterator = $this->unwrap();
  847. if (get_class($iterator) === ArrayIterator::class) {
  848. $iterator = $iterator->getArrayCopy();
  849. }
  850. return $iterator;
  851. }
  852. }