CollectionTrait.php 15 KB

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