CollectionTrait.php 20 KB

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