CollectionTrait.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  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 (new static([
  209. $values[$middle - 1], $values[$middle],
  210. ]))->avg();
  211. }
  212. /**
  213. * {@inheritDoc}
  214. */
  215. public function sortBy($callback, $dir = SORT_DESC, $type = SORT_NUMERIC)
  216. {
  217. return new SortIterator($this->unwrap(), $callback, $dir, $type);
  218. }
  219. /**
  220. * {@inheritDoc}
  221. */
  222. public function groupBy($callback)
  223. {
  224. $callback = $this->_propertyExtractor($callback);
  225. $group = [];
  226. foreach ($this->optimizeUnwrap() as $value) {
  227. $group[$callback($value)][] = $value;
  228. }
  229. return new Collection($group);
  230. }
  231. /**
  232. * {@inheritDoc}
  233. */
  234. public function indexBy($callback)
  235. {
  236. $callback = $this->_propertyExtractor($callback);
  237. $group = [];
  238. foreach ($this->optimizeUnwrap() as $value) {
  239. $group[$callback($value)] = $value;
  240. }
  241. return new Collection($group);
  242. }
  243. /**
  244. * {@inheritDoc}
  245. */
  246. public function countBy($callback)
  247. {
  248. $callback = $this->_propertyExtractor($callback);
  249. $mapper = function ($value, $key, $mr) use ($callback) {
  250. $mr->emitIntermediate($value, $callback($value));
  251. };
  252. $reducer = function ($values, $key, $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->unwrap(), $from, $size));
  294. }
  295. /**
  296. * {@inheritDoc}
  297. */
  298. public function skip($howMany)
  299. {
  300. return new Collection(new LimitIterator($this->unwrap(), $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. foreach ($this->take(1) as $result) {
  322. return $result;
  323. }
  324. }
  325. /**
  326. * {@inheritDoc}
  327. */
  328. public function last()
  329. {
  330. $iterator = $this->unwrap();
  331. $count = $iterator instanceof Countable ?
  332. count($iterator) :
  333. iterator_count($iterator);
  334. if ($count === 0) {
  335. return null;
  336. }
  337. foreach ($this->take(1, $count - 1) as $last) {
  338. return $last;
  339. }
  340. }
  341. /**
  342. * {@inheritDoc}
  343. */
  344. public function append($items)
  345. {
  346. $list = new AppendIterator();
  347. $list->append($this->unwrap());
  348. $list->append((new Collection($items))->unwrap());
  349. return new Collection($list);
  350. }
  351. /**
  352. * {@inheritDoc}
  353. */
  354. public function combine($keyPath, $valuePath, $groupPath = null)
  355. {
  356. $options = [
  357. 'keyPath' => $this->_propertyExtractor($keyPath),
  358. 'valuePath' => $this->_propertyExtractor($valuePath),
  359. 'groupPath' => $groupPath ? $this->_propertyExtractor($groupPath) : null
  360. ];
  361. $mapper = function ($value, $key, $mapReduce) use ($options) {
  362. $rowKey = $options['keyPath'];
  363. $rowVal = $options['valuePath'];
  364. if (!$options['groupPath']) {
  365. $mapReduce->emit($rowVal($value, $key), $rowKey($value, $key));
  366. return null;
  367. }
  368. $key = $options['groupPath']($value, $key);
  369. $mapReduce->emitIntermediate(
  370. [$rowKey($value, $key) => $rowVal($value, $key)],
  371. $key
  372. );
  373. };
  374. $reducer = function ($values, $key, $mapReduce) {
  375. $result = [];
  376. foreach ($values as $value) {
  377. $result += $value;
  378. }
  379. $mapReduce->emit($result, $key);
  380. };
  381. return new Collection(new MapReduce($this->unwrap(), $mapper, $reducer));
  382. }
  383. /**
  384. * {@inheritDoc}
  385. */
  386. public function nest($idPath, $parentPath, $nestingKey = 'children')
  387. {
  388. $parents = [];
  389. $idPath = $this->_propertyExtractor($idPath);
  390. $parentPath = $this->_propertyExtractor($parentPath);
  391. $isObject = true;
  392. $mapper = function ($row, $key, $mapReduce) use (&$parents, $idPath, $parentPath, $nestingKey) {
  393. $row[$nestingKey] = [];
  394. $id = $idPath($row, $key);
  395. $parentId = $parentPath($row, $key);
  396. $parents[$id] =& $row;
  397. $mapReduce->emitIntermediate($id, $parentId);
  398. };
  399. $reducer = function ($values, $key, $mapReduce) use (&$parents, &$isObject, $nestingKey) {
  400. static $foundOutType = false;
  401. if (!$foundOutType) {
  402. $isObject = is_object(current($parents));
  403. $foundOutType = true;
  404. }
  405. if (empty($key) || !isset($parents[$key])) {
  406. foreach ($values as $id) {
  407. $parents[$id] = $isObject ? $parents[$id] : new ArrayIterator($parents[$id], 1);
  408. $mapReduce->emit($parents[$id]);
  409. }
  410. return null;
  411. }
  412. $children = [];
  413. foreach ($values as $id) {
  414. $children[] =& $parents[$id];
  415. }
  416. $parents[$key][$nestingKey] = $children;
  417. };
  418. return (new Collection(new MapReduce($this->unwrap(), $mapper, $reducer)))
  419. ->map(function ($value) use (&$isObject) {
  420. return $isObject ? $value : $value->getArrayCopy();
  421. });
  422. }
  423. /**
  424. * {@inheritDoc}
  425. *
  426. * @return \Cake\Collection\Iterator\InsertIterator
  427. */
  428. public function insert($path, $values)
  429. {
  430. return new InsertIterator($this->unwrap(), $path, $values);
  431. }
  432. /**
  433. * {@inheritDoc}
  434. */
  435. public function toArray($preserveKeys = true)
  436. {
  437. $iterator = $this->unwrap();
  438. if ($iterator instanceof ArrayIterator) {
  439. $items = $iterator->getArrayCopy();
  440. return $preserveKeys ? $items : array_values($items);
  441. }
  442. // RecursiveIteratorIterator can return duplicate key values causing
  443. // data loss when converted into an array
  444. if ($preserveKeys && get_class($iterator) === 'RecursiveIteratorIterator') {
  445. $preserveKeys = false;
  446. }
  447. return iterator_to_array($this, $preserveKeys);
  448. }
  449. /**
  450. * {@inheritDoc}
  451. */
  452. public function toList()
  453. {
  454. return $this->toArray(false);
  455. }
  456. /**
  457. * {@inheritDoc}
  458. */
  459. public function jsonSerialize()
  460. {
  461. return $this->toArray();
  462. }
  463. /**
  464. * {@inheritDoc}
  465. */
  466. public function compile($preserveKeys = true)
  467. {
  468. return new Collection($this->toArray($preserveKeys));
  469. }
  470. /**
  471. * {@inheritDoc}
  472. *
  473. * @return \Cake\Collection\Iterator\BufferedIterator
  474. */
  475. public function buffered()
  476. {
  477. return new BufferedIterator($this->unwrap());
  478. }
  479. /**
  480. * {@inheritDoc}
  481. *
  482. * @return \Cake\Collection\Iterator\TreeIterator
  483. */
  484. public function listNested($dir = 'desc', $nestingKey = 'children')
  485. {
  486. $dir = strtolower($dir);
  487. $modes = [
  488. 'desc' => TreeIterator::SELF_FIRST,
  489. 'asc' => TreeIterator::CHILD_FIRST,
  490. 'leaves' => TreeIterator::LEAVES_ONLY
  491. ];
  492. return new TreeIterator(
  493. new NestIterator($this, $nestingKey),
  494. isset($modes[$dir]) ? $modes[$dir] : $dir
  495. );
  496. }
  497. /**
  498. * {@inheritDoc}
  499. *
  500. * @return \Cake\Collection\Iterator\StoppableIterator
  501. */
  502. public function stopWhen($condition)
  503. {
  504. if (!is_callable($condition)) {
  505. $condition = $this->_createMatcherFilter($condition);
  506. }
  507. return new StoppableIterator($this->unwrap(), $condition);
  508. }
  509. /**
  510. * {@inheritDoc}
  511. */
  512. public function unfold(callable $transformer = null)
  513. {
  514. if ($transformer === null) {
  515. $transformer = function ($item) {
  516. return $item;
  517. };
  518. }
  519. return new Collection(
  520. new RecursiveIteratorIterator(
  521. new UnfoldIterator($this->unwrap(), $transformer),
  522. RecursiveIteratorIterator::LEAVES_ONLY
  523. )
  524. );
  525. }
  526. /**
  527. * {@inheritDoc}
  528. */
  529. public function through(callable $handler)
  530. {
  531. $result = $handler($this);
  532. return $result instanceof CollectionInterface ? $result : new Collection($result);
  533. }
  534. /**
  535. * {@inheritDoc}
  536. */
  537. public function zip($items)
  538. {
  539. return new ZipIterator(array_merge([$this->unwrap()], func_get_args()));
  540. }
  541. /**
  542. * {@inheritDoc}
  543. */
  544. public function zipWith($items, $callable)
  545. {
  546. if (func_num_args() > 2) {
  547. $items = func_get_args();
  548. $callable = array_pop($items);
  549. } else {
  550. $items = [$items];
  551. }
  552. return new ZipIterator(array_merge([$this->unwrap()], $items), $callable);
  553. }
  554. /**
  555. * {@inheritDoc}
  556. */
  557. public function chunk($chunkSize)
  558. {
  559. return $this->map(function ($v, $k, $iterator) use ($chunkSize) {
  560. $values = [$v];
  561. for ($i = 1; $i < $chunkSize; $i++) {
  562. $iterator->next();
  563. if (!$iterator->valid()) {
  564. break;
  565. }
  566. $values[] = $iterator->current();
  567. }
  568. return $values;
  569. });
  570. }
  571. /**
  572. * {@inheritDoc}
  573. */
  574. public function chunkWithKeys($chunkSize, $preserveKeys = true)
  575. {
  576. return $this->map(function ($v, $k, $iterator) use ($chunkSize, $preserveKeys) {
  577. $key = 0;
  578. if ($preserveKeys) {
  579. $key = $k;
  580. }
  581. $values = [$key => $v];
  582. for ($i = 1; $i < $chunkSize; $i++) {
  583. $iterator->next();
  584. if (!$iterator->valid()) {
  585. break;
  586. }
  587. if ($preserveKeys) {
  588. $values[$iterator->key()] = $iterator->current();
  589. } else {
  590. $values[] = $iterator->current();
  591. }
  592. }
  593. return $values;
  594. });
  595. }
  596. /**
  597. * {@inheritDoc}
  598. */
  599. public function isEmpty()
  600. {
  601. foreach ($this as $el) {
  602. return false;
  603. }
  604. return true;
  605. }
  606. /**
  607. * {@inheritDoc}
  608. */
  609. public function unwrap()
  610. {
  611. $iterator = $this;
  612. while (get_class($iterator) === 'Cake\Collection\Collection') {
  613. $iterator = $iterator->getInnerIterator();
  614. }
  615. if ($iterator !== $this && $iterator instanceof CollectionInterface) {
  616. $iterator = $iterator->unwrap();
  617. }
  618. return $iterator;
  619. }
  620. /**
  621. * Backwards compatible wrapper for unwrap()
  622. *
  623. * @return \Iterator
  624. * @deprecated
  625. */
  626. // @codingStandardsIgnoreLine
  627. public function _unwrap()
  628. {
  629. return $this->unwrap();
  630. }
  631. /**
  632. * {@inheritDoc}
  633. *
  634. * @return \Cake\Collection\CollectionInterface
  635. */
  636. public function cartesianProduct(callable $operation = null, callable $filter = null)
  637. {
  638. if ($this->isEmpty()) {
  639. return new Collection([]);
  640. }
  641. $collectionArrays = [];
  642. $collectionArraysKeys = [];
  643. $collectionArraysCounts = [];
  644. foreach ($this->toList() as $value) {
  645. $valueCount = count($value);
  646. if ($valueCount !== count($value, COUNT_RECURSIVE)) {
  647. throw new LogicException('Cannot find the cartesian product of a multidimensional array');
  648. }
  649. $collectionArraysKeys[] = array_keys($value);
  650. $collectionArraysCounts[] = $valueCount;
  651. $collectionArrays[] = $value;
  652. }
  653. $result = [];
  654. $lastIndex = count($collectionArrays) - 1;
  655. // holds the indexes of the arrays that generate the current combination
  656. $currentIndexes = array_fill(0, $lastIndex + 1, 0);
  657. $changeIndex = $lastIndex;
  658. while (!($changeIndex === 0 && $currentIndexes[0] === $collectionArraysCounts[0])) {
  659. $currentCombination = array_map(function ($value, $keys, $index) {
  660. return $value[$keys[$index]];
  661. }, $collectionArrays, $collectionArraysKeys, $currentIndexes);
  662. if ($filter === null || $filter($currentCombination)) {
  663. $result[] = ($operation === null) ? $currentCombination : $operation($currentCombination);
  664. }
  665. $currentIndexes[$lastIndex]++;
  666. for ($changeIndex = $lastIndex; $currentIndexes[$changeIndex] === $collectionArraysCounts[$changeIndex] && $changeIndex > 0; $changeIndex--) {
  667. $currentIndexes[$changeIndex] = 0;
  668. $currentIndexes[$changeIndex - 1]++;
  669. }
  670. }
  671. return new Collection($result);
  672. }
  673. /**
  674. * {@inheritDoc}
  675. *
  676. * @return \Cake\Collection\CollectionInterface
  677. */
  678. public function transpose()
  679. {
  680. $arrayValue = $this->toList();
  681. $length = count(current($arrayValue));
  682. $result = [];
  683. foreach ($arrayValue as $column => $row) {
  684. if (count($row) != $length) {
  685. throw new LogicException('Child arrays do not have even length');
  686. }
  687. }
  688. for ($column = 0; $column < $length; $column++) {
  689. $result[] = array_column($arrayValue, $column);
  690. }
  691. return new Collection($result);
  692. }
  693. /**
  694. * Unwraps this iterator and returns the simplest
  695. * traversable that can be used for getting the data out
  696. *
  697. * @return \Traversable|array
  698. */
  699. protected function optimizeUnwrap()
  700. {
  701. $iterator = $this->unwrap();
  702. if ($iterator instanceof ArrayIterator) {
  703. $iterator = $iterator->getArrayCopy();
  704. }
  705. return $iterator;
  706. }
  707. }