CollectionTrait.php 27 KB

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