CollectionTrait.php 22 KB

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