| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535 |
- <?php
- /**
- * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
- * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
- *
- * Licensed under The MIT License
- * For full copyright and license information, please see the LICENSE.txt
- * Redistributions of files must retain the above copyright notice.
- *
- * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
- * @link http://cakephp.org CakePHP(tm) Project
- * @since 3.0.0
- * @license http://www.opensource.org/licenses/mit-license.php MIT License
- */
- namespace Cake\Collection;
- use AppendIterator;
- use ArrayIterator;
- use Cake\Collection\Collection;
- use Cake\Collection\Iterator\BufferedIterator;
- use Cake\Collection\Iterator\ExtractIterator;
- use Cake\Collection\Iterator\FilterIterator;
- use Cake\Collection\Iterator\InsertIterator;
- use Cake\Collection\Iterator\MapReduce;
- use Cake\Collection\Iterator\NestIterator;
- use Cake\Collection\Iterator\ReplaceIterator;
- use Cake\Collection\Iterator\SortIterator;
- use Cake\Collection\Iterator\StoppableIterator;
- use Cake\Collection\Iterator\TreeIterator;
- use Cake\Collection\Iterator\UnfoldIterator;
- use Iterator;
- use LimitIterator;
- use RecursiveIteratorIterator;
- /**
- * Offers a handful of method to manipulate iterators
- */
- trait CollectionTrait
- {
- use ExtractTrait;
- /**
- * {@inheritDoc}
- *
- */
- public function each(callable $c)
- {
- foreach ($this->_unwrap() as $k => $v) {
- $c($v, $k);
- }
- return $this;
- }
- /**
- * {@inheritDoc}
- *
- * @return \Cake\Collection\Iterator\FilterIterator
- */
- public function filter(callable $c = null)
- {
- if ($c === null) {
- $c = function ($v) {
- return (bool)$v;
- };
- }
- return new FilterIterator($this->_unwrap(), $c);
- }
- /**
- * {@inheritDoc}
- *
- * @return \Cake\Collection\Iterator\FilterIterator
- */
- public function reject(callable $c)
- {
- return new FilterIterator($this->_unwrap(), function ($key, $value, $items) use ($c) {
- return !$c($key, $value, $items);
- });
- }
- /**
- * {@inheritDoc}
- *
- */
- public function every(callable $c)
- {
- foreach ($this->_unwrap() as $key => $value) {
- if (!$c($value, $key)) {
- return false;
- }
- }
- return true;
- }
- /**
- * {@inheritDoc}
- *
- */
- public function some(callable $c)
- {
- foreach ($this->_unwrap() as $key => $value) {
- if ($c($value, $key) === true) {
- return true;
- }
- }
- return false;
- }
- /**
- * {@inheritDoc}
- *
- */
- public function contains($value)
- {
- foreach ($this->_unwrap() as $v) {
- if ($value === $v) {
- return true;
- }
- }
- return false;
- }
- /**
- * {@inheritDoc}
- *
- * @return \Cake\Collection\Iterator\ReplaceIterator
- */
- public function map(callable $c)
- {
- return new ReplaceIterator($this->_unwrap(), $c);
- }
- /**
- * {@inheritDoc}
- *
- */
- public function reduce(callable $c, $zero = null)
- {
- $isFirst = false;
- if (func_num_args() < 2) {
- $isFirst = true;
- }
- $result = $zero;
- foreach ($this->_unwrap() as $k => $value) {
- if ($isFirst) {
- $result = $value;
- $isFirst = false;
- continue;
- }
- $result = $c($result, $value, $k);
- }
- return $result;
- }
- /**
- * {@inheritDoc}
- *
- * @return \Cake\Collection\Iterator\ExtractIterator
- */
- public function extract($matcher)
- {
- return new ExtractIterator($this->_unwrap(), $matcher);
- }
- /**
- * {@inheritDoc}
- *
- */
- public function max($callback, $type = SORT_NUMERIC)
- {
- return (new SortIterator($this->_unwrap(), $callback, SORT_DESC, $type))->first();
- }
- /**
- * {@inheritDoc}
- *
- */
- public function min($callback, $type = SORT_NUMERIC)
- {
- return (new SortIterator($this->_unwrap(), $callback, SORT_ASC, $type))->first();
- }
- /**
- * {@inheritDoc}
- *
- */
- public function sortBy($callback, $dir = SORT_DESC, $type = SORT_NUMERIC)
- {
- return new SortIterator($this->_unwrap(), $callback, $dir, $type);
- }
- /**
- * {@inheritDoc}
- *
- */
- public function groupBy($callback)
- {
- $callback = $this->_propertyExtractor($callback);
- $group = [];
- foreach ($this as $value) {
- $group[$callback($value)][] = $value;
- }
- return new Collection($group);
- }
- /**
- * {@inheritDoc}
- *
- */
- public function indexBy($callback)
- {
- $callback = $this->_propertyExtractor($callback);
- $group = [];
- foreach ($this as $value) {
- $group[$callback($value)] = $value;
- }
- return new Collection($group);
- }
- /**
- * {@inheritDoc}
- *
- */
- public function countBy($callback)
- {
- $callback = $this->_propertyExtractor($callback);
- $mapper = function ($value, $key, $mr) use ($callback) {
- $mr->emitIntermediate($value, $callback($value));
- };
- $reducer = function ($values, $key, $mr) {
- $mr->emit(count($values), $key);
- };
- return new Collection(new MapReduce($this->_unwrap(), $mapper, $reducer));
- }
- /**
- * {@inheritDoc}
- *
- */
- public function sumOf($matcher)
- {
- $callback = $this->_propertyExtractor($matcher);
- $sum = 0;
- foreach ($this as $k => $v) {
- $sum += $callback($v, $k);
- }
- return $sum;
- }
- /**
- * {@inheritDoc}
- *
- */
- public function shuffle()
- {
- $elements = $this->toArray();
- shuffle($elements);
- return new Collection($elements);
- }
- /**
- * {@inheritDoc}
- *
- */
- public function sample($size = 10)
- {
- return new Collection(new LimitIterator($this->shuffle(), 0, $size));
- }
- /**
- * {@inheritDoc}
- *
- */
- public function take($size = 1, $from = 0)
- {
- return new Collection(new LimitIterator($this->_unwrap(), $from, $size));
- }
- /**
- * {@inheritDoc}
- *
- */
- public function match(array $conditions)
- {
- return $this->filter($this->_createMatcherFilter($conditions));
- }
- /**
- * {@inheritDoc}
- *
- */
- public function firstMatch(array $conditions)
- {
- return $this->match($conditions)->first();
- }
- /**
- * {@inheritDoc}
- *
- */
- public function first()
- {
- foreach ($this->take(1) as $result) {
- return $result;
- }
- }
- /**
- * {@inheritDoc}
- *
- */
- public function append($items)
- {
- $items = $items instanceof Iterator ? $items : new Collection($items);
- $list = new AppendIterator;
- $list->append($this);
- $list->append($items->_unwrap());
- return new Collection($list);
- }
- /**
- * {@inheritDoc}
- *
- */
- public function combine($keyPath, $valuePath, $groupPath = null)
- {
- $options = [
- 'keyPath' => $this->_propertyExtractor($keyPath),
- 'valuePath' => $this->_propertyExtractor($valuePath),
- 'groupPath' => $groupPath ? $this->_propertyExtractor($groupPath) : null
- ];
- $mapper = function ($value, $key, $mapReduce) use ($options) {
- $rowKey = $options['keyPath'];
- $rowVal = $options['valuePath'];
- if (!($options['groupPath'])) {
- $mapReduce->emit($rowVal($value, $key), $rowKey($value, $key));
- return;
- }
- $key = $options['groupPath']($value, $key);
- $mapReduce->emitIntermediate(
- [$rowKey($value, $key) => $rowVal($value, $key)],
- $key
- );
- };
- $reducer = function ($values, $key, $mapReduce) {
- $result = [];
- foreach ($values as $value) {
- $result += $value;
- }
- $mapReduce->emit($result, $key);
- };
- return new Collection(new MapReduce($this->_unwrap(), $mapper, $reducer));
- }
- /**
- * {@inheritDoc}
- *
- */
- public function nest($idPath, $parentPath)
- {
- $parents = [];
- $idPath = $this->_propertyExtractor($idPath);
- $parentPath = $this->_propertyExtractor($parentPath);
- $isObject = !is_array((new Collection($this))->first());
- $mapper = function ($row, $key, $mapReduce) use (&$parents, $idPath, $parentPath) {
- $row['children'] = [];
- $id = $idPath($row, $key);
- $parentId = $parentPath($row, $key);
- $parents[$id] =& $row;
- $mapReduce->emitIntermediate($id, $parentId);
- };
- $reducer = function ($values, $key, $mapReduce) use (&$parents, $isObject) {
- if (empty($key) || !isset($parents[$key])) {
- foreach ($values as $id) {
- $parents[$id] = $isObject ? $parents[$id] : new ArrayIterator($parents[$id], 1);
- $mapReduce->emit($parents[$id]);
- }
- return;
- }
- foreach ($values as $id) {
- $parents[$key]['children'][] =& $parents[$id];
- }
- };
- $collection = new MapReduce($this, $mapper, $reducer);
- if (!$isObject) {
- $collection = (new Collection($collection))->map(function ($value) {
- return $value->getArrayCopy();
- });
- }
- return new Collection($collection);
- }
- /**
- * {@inheritDoc}
- *
- * @return \Cake\Collection\Iterator\InsertIterator
- */
- public function insert($path, $values)
- {
- return new InsertIterator($this->_unwrap(), $path, $values);
- }
- /**
- * {@inheritDoc}
- *
- */
- public function toArray($preserveKeys = true)
- {
- $iterator = $this->_unwrap();
- if ($iterator instanceof ArrayIterator) {
- $items = $iterator->getArrayCopy();
- return $preserveKeys ? $items : array_values($items);
- }
- return iterator_to_array($this, $preserveKeys);
- }
- /**
- * {@inheritDoc}
- *
- */
- public function toList()
- {
- return $this->toArray(false);
- }
- /**
- * {@inheritDoc}
- *
- */
- public function jsonSerialize()
- {
- return $this->toArray();
- }
- /**
- * {@inheritDoc}
- *
- */
- public function compile($preserveKeys = true)
- {
- return new Collection($this->toArray($preserveKeys));
- }
- /**
- * {@inheritDoc}
- *
- * @return \Cake\Collection\Iterator\BufferedIterator
- */
- public function buffered()
- {
- return new BufferedIterator($this);
- }
- /**
- * {@inheritDoc}
- *
- * @return \Cake\Collection\Iterator\TreeIterator
- */
- public function listNested($dir = 'desc', $nestingKey = 'children')
- {
- $dir = strtolower($dir);
- $modes = [
- 'desc' => TreeIterator::SELF_FIRST,
- 'asc' => TreeIterator::CHILD_FIRST,
- 'leaves' => TreeIterator::LEAVES_ONLY
- ];
- return new TreeIterator(
- new NestIterator($this, $nestingKey),
- isset($modes[$dir]) ? $modes[$dir] : $dir
- );
- }
- /**
- * {@inheritDoc}
- *
- * @return \Cake\Collection\Iterator\StoppableIterator
- */
- public function stopWhen($condition)
- {
- if (!is_callable($condition)) {
- $condition = $this->_createMatcherFilter($condition);
- }
- return new StoppableIterator($this, $condition);
- }
- /**
- * {@inheritDoc}
- *
- */
- public function unfold(callable $transformer = null)
- {
- if ($transformer === null) {
- $transformer = function ($item) {
- return $item;
- };
- }
- return new Collection(
- new RecursiveIteratorIterator(
- new UnfoldIterator($this, $transformer),
- RecursiveIteratorIterator::LEAVES_ONLY
- )
- );
- }
- /**
- * Returns the closest nested iterator that can be safely traversed without
- * losing any possible transformations.
- *
- * @return \Iterator
- */
- protected function _unwrap()
- {
- $iterator = $this;
- while (get_class($iterator) === 'Cake\Collection\Collection') {
- $iterator = $iterator->getInnerIterator();
- }
- return $iterator;
- }
- }
|