CollectionTrait.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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 http://www.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. */
  45. public function each(callable $c)
  46. {
  47. foreach ($this->unwrap() as $k => $v) {
  48. $c($v, $k);
  49. }
  50. return $this;
  51. }
  52. /**
  53. * {@inheritDoc}
  54. *
  55. * @return \Cake\Collection\Iterator\FilterIterator
  56. */
  57. public function filter(callable $c = null)
  58. {
  59. if ($c === null) {
  60. $c = function ($v) {
  61. return (bool)$v;
  62. };
  63. }
  64. return new FilterIterator($this->unwrap(), $c);
  65. }
  66. /**
  67. * {@inheritDoc}
  68. *
  69. * @return \Cake\Collection\Iterator\FilterIterator
  70. */
  71. public function reject(callable $c)
  72. {
  73. return new FilterIterator($this->unwrap(), function ($key, $value, $items) use ($c) {
  74. return !$c($key, $value, $items);
  75. });
  76. }
  77. /**
  78. * {@inheritDoc}
  79. *
  80. */
  81. public function every(callable $c)
  82. {
  83. $return = false;
  84. foreach ($this->unwrap() as $key => $value) {
  85. $return = true;
  86. if (!$c($value, $key)) {
  87. return false;
  88. }
  89. }
  90. return $return;
  91. }
  92. /**
  93. * {@inheritDoc}
  94. *
  95. */
  96. public function some(callable $c)
  97. {
  98. foreach ($this->unwrap() as $key => $value) {
  99. if ($c($value, $key) === true) {
  100. return true;
  101. }
  102. }
  103. return false;
  104. }
  105. /**
  106. * {@inheritDoc}
  107. *
  108. */
  109. public function contains($value)
  110. {
  111. foreach ($this->unwrap() as $v) {
  112. if ($value === $v) {
  113. return true;
  114. }
  115. }
  116. return false;
  117. }
  118. /**
  119. * {@inheritDoc}
  120. *
  121. * @return \Cake\Collection\Iterator\ReplaceIterator
  122. */
  123. public function map(callable $c)
  124. {
  125. return new ReplaceIterator($this->unwrap(), $c);
  126. }
  127. /**
  128. * {@inheritDoc}
  129. *
  130. */
  131. public function reduce(callable $c, $zero = null)
  132. {
  133. $isFirst = false;
  134. if (func_num_args() < 2) {
  135. $isFirst = true;
  136. }
  137. $result = $zero;
  138. foreach ($this->unwrap() as $k => $value) {
  139. if ($isFirst) {
  140. $result = $value;
  141. $isFirst = false;
  142. continue;
  143. }
  144. $result = $c($result, $value, $k);
  145. }
  146. return $result;
  147. }
  148. /**
  149. * {@inheritDoc}
  150. *
  151. */
  152. public function extract($matcher)
  153. {
  154. $extractor = new ExtractIterator($this->unwrap(), $matcher);
  155. if (is_string($matcher) && strpos($matcher, '{*}') !== false) {
  156. $extractor = $extractor
  157. ->filter(function ($data) {
  158. return $data !== null && ($data instanceof Traversable || is_array($data));
  159. })
  160. ->unfold();
  161. }
  162. return $extractor;
  163. }
  164. /**
  165. * {@inheritDoc}
  166. *
  167. */
  168. public function max($callback, $type = SORT_NUMERIC)
  169. {
  170. return (new SortIterator($this->unwrap(), $callback, SORT_DESC, $type))->first();
  171. }
  172. /**
  173. * {@inheritDoc}
  174. *
  175. */
  176. public function min($callback, $type = SORT_NUMERIC)
  177. {
  178. return (new SortIterator($this->unwrap(), $callback, SORT_ASC, $type))->first();
  179. }
  180. /**
  181. * {@inheritDoc}
  182. *
  183. */
  184. public function sortBy($callback, $dir = SORT_DESC, $type = SORT_NUMERIC)
  185. {
  186. return new SortIterator($this->unwrap(), $callback, $dir, $type);
  187. }
  188. /**
  189. * {@inheritDoc}
  190. *
  191. */
  192. public function groupBy($callback)
  193. {
  194. $callback = $this->_propertyExtractor($callback);
  195. $group = [];
  196. foreach ($this as $value) {
  197. $group[$callback($value)][] = $value;
  198. }
  199. return new Collection($group);
  200. }
  201. /**
  202. * {@inheritDoc}
  203. *
  204. */
  205. public function indexBy($callback)
  206. {
  207. $callback = $this->_propertyExtractor($callback);
  208. $group = [];
  209. foreach ($this as $value) {
  210. $group[$callback($value)] = $value;
  211. }
  212. return new Collection($group);
  213. }
  214. /**
  215. * {@inheritDoc}
  216. *
  217. */
  218. public function countBy($callback)
  219. {
  220. $callback = $this->_propertyExtractor($callback);
  221. $mapper = function ($value, $key, $mr) use ($callback) {
  222. $mr->emitIntermediate($value, $callback($value));
  223. };
  224. $reducer = function ($values, $key, $mr) {
  225. $mr->emit(count($values), $key);
  226. };
  227. return new Collection(new MapReduce($this->unwrap(), $mapper, $reducer));
  228. }
  229. /**
  230. * {@inheritDoc}
  231. *
  232. */
  233. public function sumOf($matcher = null)
  234. {
  235. if ($matcher === null) {
  236. return array_sum($this->toList());
  237. }
  238. $callback = $this->_propertyExtractor($matcher);
  239. $sum = 0;
  240. foreach ($this as $k => $v) {
  241. $sum += $callback($v, $k);
  242. }
  243. return $sum;
  244. }
  245. /**
  246. * {@inheritDoc}
  247. *
  248. */
  249. public function shuffle()
  250. {
  251. $elements = $this->toArray();
  252. shuffle($elements);
  253. return new Collection($elements);
  254. }
  255. /**
  256. * {@inheritDoc}
  257. *
  258. */
  259. public function sample($size = 10)
  260. {
  261. return new Collection(new LimitIterator($this->shuffle(), 0, $size));
  262. }
  263. /**
  264. * {@inheritDoc}
  265. *
  266. */
  267. public function take($size = 1, $from = 0)
  268. {
  269. return new Collection(new LimitIterator($this->unwrap(), $from, $size));
  270. }
  271. /**
  272. * {@inheritDoc}
  273. *
  274. */
  275. public function skip($howMany)
  276. {
  277. return new Collection(new LimitIterator($this->unwrap(), $howMany));
  278. }
  279. /**
  280. * {@inheritDoc}
  281. *
  282. */
  283. public function match(array $conditions)
  284. {
  285. return $this->filter($this->_createMatcherFilter($conditions));
  286. }
  287. /**
  288. * {@inheritDoc}
  289. *
  290. */
  291. public function firstMatch(array $conditions)
  292. {
  293. return $this->match($conditions)->first();
  294. }
  295. /**
  296. * {@inheritDoc}
  297. *
  298. */
  299. public function first()
  300. {
  301. foreach ($this->take(1) as $result) {
  302. return $result;
  303. }
  304. }
  305. /**
  306. * {@inheritDoc}
  307. *
  308. */
  309. public function last()
  310. {
  311. $iterator = $this->unwrap();
  312. $count = $iterator instanceof Countable ?
  313. count($iterator) :
  314. iterator_count($iterator);
  315. if ($count === 0) {
  316. return null;
  317. }
  318. foreach ($this->take(1, $count - 1) as $last) {
  319. return $last;
  320. }
  321. }
  322. /**
  323. * {@inheritDoc}
  324. *
  325. */
  326. public function append($items)
  327. {
  328. $list = new AppendIterator;
  329. $list->append($this->unwrap());
  330. $list->append((new Collection($items))->unwrap());
  331. return new Collection($list);
  332. }
  333. /**
  334. * {@inheritDoc}
  335. *
  336. */
  337. public function combine($keyPath, $valuePath, $groupPath = null)
  338. {
  339. $options = [
  340. 'keyPath' => $this->_propertyExtractor($keyPath),
  341. 'valuePath' => $this->_propertyExtractor($valuePath),
  342. 'groupPath' => $groupPath ? $this->_propertyExtractor($groupPath) : null
  343. ];
  344. $mapper = function ($value, $key, $mapReduce) use ($options) {
  345. $rowKey = $options['keyPath'];
  346. $rowVal = $options['valuePath'];
  347. if (!($options['groupPath'])) {
  348. $mapReduce->emit($rowVal($value, $key), $rowKey($value, $key));
  349. return null;
  350. }
  351. $key = $options['groupPath']($value, $key);
  352. $mapReduce->emitIntermediate(
  353. [$rowKey($value, $key) => $rowVal($value, $key)],
  354. $key
  355. );
  356. };
  357. $reducer = function ($values, $key, $mapReduce) {
  358. $result = [];
  359. foreach ($values as $value) {
  360. $result += $value;
  361. }
  362. $mapReduce->emit($result, $key);
  363. };
  364. return new Collection(new MapReduce($this->unwrap(), $mapper, $reducer));
  365. }
  366. /**
  367. * {@inheritDoc}
  368. *
  369. */
  370. public function nest($idPath, $parentPath, $nestingKey = 'children')
  371. {
  372. $parents = [];
  373. $idPath = $this->_propertyExtractor($idPath);
  374. $parentPath = $this->_propertyExtractor($parentPath);
  375. $isObject = true;
  376. $mapper = function ($row, $key, $mapReduce) use (&$parents, $idPath, $parentPath, $nestingKey) {
  377. $row[$nestingKey] = [];
  378. $id = $idPath($row, $key);
  379. $parentId = $parentPath($row, $key);
  380. $parents[$id] =& $row;
  381. $mapReduce->emitIntermediate($id, $parentId);
  382. };
  383. $reducer = function ($values, $key, $mapReduce) use (&$parents, &$isObject, $nestingKey) {
  384. static $foundOutType = false;
  385. if (!$foundOutType) {
  386. $isObject = is_object(current($parents));
  387. $foundOutType = true;
  388. }
  389. if (empty($key) || !isset($parents[$key])) {
  390. foreach ($values as $id) {
  391. $parents[$id] = $isObject ? $parents[$id] : new ArrayIterator($parents[$id], 1);
  392. $mapReduce->emit($parents[$id]);
  393. }
  394. return null;
  395. }
  396. $children = [];
  397. foreach ($values as $id) {
  398. $children[] =& $parents[$id];
  399. }
  400. $parents[$key][$nestingKey] = $children;
  401. };
  402. return (new Collection(new MapReduce($this->unwrap(), $mapper, $reducer)))
  403. ->map(function ($value) use (&$isObject) {
  404. return $isObject ? $value : $value->getArrayCopy();
  405. });
  406. }
  407. /**
  408. * {@inheritDoc}
  409. *
  410. * @return \Cake\Collection\Iterator\InsertIterator
  411. */
  412. public function insert($path, $values)
  413. {
  414. return new InsertIterator($this->unwrap(), $path, $values);
  415. }
  416. /**
  417. * {@inheritDoc}
  418. *
  419. */
  420. public function toArray($preserveKeys = true)
  421. {
  422. $iterator = $this->unwrap();
  423. if ($iterator instanceof ArrayIterator) {
  424. $items = $iterator->getArrayCopy();
  425. return $preserveKeys ? $items : array_values($items);
  426. }
  427. // RecursiveIteratorIterator can return duplicate key values causing
  428. // data loss when converted into an array
  429. if ($preserveKeys && get_class($iterator) === 'RecursiveIteratorIterator') {
  430. $preserveKeys = false;
  431. }
  432. return iterator_to_array($this, $preserveKeys);
  433. }
  434. /**
  435. * {@inheritDoc}
  436. *
  437. */
  438. public function toList()
  439. {
  440. return $this->toArray(false);
  441. }
  442. /**
  443. * {@inheritDoc}
  444. *
  445. */
  446. public function jsonSerialize()
  447. {
  448. return $this->toArray();
  449. }
  450. /**
  451. * {@inheritDoc}
  452. *
  453. */
  454. public function compile($preserveKeys = true)
  455. {
  456. return new Collection($this->toArray($preserveKeys));
  457. }
  458. /**
  459. * {@inheritDoc}
  460. *
  461. * @return \Cake\Collection\Iterator\BufferedIterator
  462. */
  463. public function buffered()
  464. {
  465. return new BufferedIterator($this);
  466. }
  467. /**
  468. * {@inheritDoc}
  469. *
  470. * @return \Cake\Collection\Iterator\TreeIterator
  471. */
  472. public function listNested($dir = 'desc', $nestingKey = 'children')
  473. {
  474. $dir = strtolower($dir);
  475. $modes = [
  476. 'desc' => TreeIterator::SELF_FIRST,
  477. 'asc' => TreeIterator::CHILD_FIRST,
  478. 'leaves' => TreeIterator::LEAVES_ONLY
  479. ];
  480. return new TreeIterator(
  481. new NestIterator($this, $nestingKey),
  482. isset($modes[$dir]) ? $modes[$dir] : $dir
  483. );
  484. }
  485. /**
  486. * {@inheritDoc}
  487. *
  488. * @return \Cake\Collection\Iterator\StoppableIterator
  489. */
  490. public function stopWhen($condition)
  491. {
  492. if (!is_callable($condition)) {
  493. $condition = $this->_createMatcherFilter($condition);
  494. }
  495. return new StoppableIterator($this, $condition);
  496. }
  497. /**
  498. * {@inheritDoc}
  499. *
  500. */
  501. public function unfold(callable $transformer = null)
  502. {
  503. if ($transformer === null) {
  504. $transformer = function ($item) {
  505. return $item;
  506. };
  507. }
  508. return new Collection(
  509. new RecursiveIteratorIterator(
  510. new UnfoldIterator($this, $transformer),
  511. RecursiveIteratorIterator::LEAVES_ONLY
  512. )
  513. );
  514. }
  515. /**
  516. * {@inheritDoc}
  517. *
  518. */
  519. public function through(callable $handler)
  520. {
  521. $result = $handler($this);
  522. return $result instanceof CollectionInterface ? $result : new Collection($result);
  523. }
  524. /**
  525. * {@inheritDoc}
  526. *
  527. */
  528. public function zip($items)
  529. {
  530. return new ZipIterator(array_merge([$this], func_get_args()));
  531. }
  532. /**
  533. * {@inheritDoc}
  534. *
  535. */
  536. public function zipWith($items, $callable)
  537. {
  538. if (func_num_args() > 2) {
  539. $items = func_get_args();
  540. $callable = array_pop($items);
  541. } else {
  542. $items = [$items];
  543. }
  544. return new ZipIterator(array_merge([$this], $items), $callable);
  545. }
  546. /**
  547. * {@inheritDoc}
  548. *
  549. */
  550. public function chunk($chunkSize)
  551. {
  552. return $this->map(function ($v, $k, $iterator) use ($chunkSize) {
  553. $values = [$v];
  554. for ($i = 1; $i < $chunkSize; $i++) {
  555. $iterator->next();
  556. if (!$iterator->valid()) {
  557. break;
  558. }
  559. $values[] = $iterator->current();
  560. }
  561. return $values;
  562. });
  563. }
  564. /**
  565. * {@inheritDoc}
  566. *
  567. */
  568. public function isEmpty()
  569. {
  570. foreach ($this->unwrap() as $el) {
  571. return false;
  572. }
  573. return true;
  574. }
  575. /**
  576. * {@inheritDoc}
  577. *
  578. */
  579. public function unwrap()
  580. {
  581. $iterator = $this;
  582. while (get_class($iterator) === 'Cake\Collection\Collection') {
  583. $iterator = $iterator->getInnerIterator();
  584. }
  585. return $iterator;
  586. }
  587. /**
  588. * Backwards compatible wrapper for unwrap()
  589. *
  590. * @return \Iterator
  591. * @deprecated
  592. */
  593. public function _unwrap()
  594. {
  595. return $this->unwrap();
  596. }
  597. /**
  598. * {@inheritDoc}
  599. *
  600. * @return \Cake\Collection\CollectionInterface
  601. */
  602. public function cartesianProduct(callable $operation = null, callable $filter = null)
  603. {
  604. if ($this->isEmpty()) {
  605. return new Collection([]);
  606. }
  607. $result = [];
  608. $counts = $this->map(function ($arr) {
  609. return count($arr);
  610. })->toList();
  611. $allArr = $this->toList();
  612. $lastIndex = count($allArr) - 1;
  613. // holds the indexes of the arrays that generate the current combination
  614. $currentIndexes = array_fill(0, $lastIndex + 1, 0);
  615. $changeIndex = $lastIndex;
  616. while (!($changeIndex === 0 && $currentIndexes[0] === $counts[0])) {
  617. $currentCombination = array_map(function ($arr, $index) {
  618. return $arr[$index];
  619. }, $allArr, $currentIndexes);
  620. if ($filter === null || $filter(...$currentCombination)) {
  621. $result[] = ($operation === null) ? $currentCombination : $operation(...$currentCombination);
  622. }
  623. $currentIndexes[$lastIndex]++;
  624. for ($changeIndex = $lastIndex; $currentIndexes[$changeIndex] === $counts[$changeIndex] && $changeIndex > 0; $changeIndex--) {
  625. $currentIndexes[$changeIndex] = 0;
  626. $currentIndexes[$changeIndex - 1]++;
  627. }
  628. }
  629. return new Collection($result);
  630. }
  631. /**
  632. * {@inheritDoc}
  633. *
  634. * @return \Cake\Collection\CollectionInterface
  635. */
  636. public function transpose()
  637. {
  638. $arrayValue = $this->toList();
  639. $length = count(current($arrayValue));
  640. $result = [];
  641. foreach ($arrayValue as $column => $row) {
  642. if (count($row) != $length) {
  643. throw new LogicException('Child arrays do not have even length');
  644. }
  645. $result[] = array_column($arrayValue, $column);
  646. }
  647. return new Collection($result);
  648. }
  649. }