3 namespace WPML\Collect\Support;
11 use IteratorAggregate;
12 use InvalidArgumentException;
13 use WPML\Collect\Support\Traits\Macroable;
14 use WPML\Collect\Contracts\Support\Jsonable;
15 use WPML\Collect\Contracts\Support\Arrayable;
17 class Collection implements ArrayAccess, Arrayable, Countable, IteratorAggregate, Jsonable, JsonSerializable
22 * The items contained in the collection.
26 protected $items = [];
29 * Create a new collection.
34 public function __construct($items = [])
36 $this->items = $this->getArrayableItems($items);
40 * Create a new collection instance if the value isn't one already.
45 public static function make($items = [])
47 return new static($items);
51 * Get all of the items in the collection.
61 * Get the average value of a given key.
63 * @param callable|string|null $callback
66 public function avg($callback = null)
68 if ($count = $this->count()) {
69 return $this->sum($callback) / $count;
74 * Alias for the "avg" method.
76 * @param callable|string|null $callback
79 public function average($callback = null)
81 return $this->avg($callback);
85 * Get the median of a given key.
90 public function median($key = null)
92 $count = $this->count();
98 $values = with(isset($key) ? $this->pluck($key) : $this)
101 $middle = (int) ($count / 2);
104 return $values->get($middle);
108 $values->get($middle - 1), $values->get($middle),
113 * Get the mode of a given key.
118 public function mode($key = null)
120 $count = $this->count();
126 $collection = isset($key) ? $this->pluck($key) : $this;
130 $collection->each(function ($value) use ($counts) {
131 $counts[$value] = isset($counts[$value]) ? $counts[$value] + 1 : 1;
134 $sorted = $counts->sort();
136 $highestValue = $sorted->last();
138 return $sorted->filter(function ($value) use ($highestValue) {
139 return $value == $highestValue;
140 })->sort()->keys()->all();
144 * Collapse the collection of items into a single array.
148 public function collapse()
150 return new static(Arr::collapse($this->items));
154 * Determine if an item exists in the collection.
157 * @param mixed $value
160 public function contains($key, $value = null)
162 if (func_num_args() == 2) {
163 return $this->contains(function ($item) use ($key, $value) {
164 return data_get($item, $key) == $value;
168 if ($this->useAsCallable($key)) {
169 return ! is_null($this->first($key));
172 return in_array($key, $this->items);
176 * Determine if an item exists in the collection using strict comparison.
179 * @param mixed $value
182 public function containsStrict($key, $value = null)
184 if (func_num_args() == 2) {
185 return $this->contains(function ($item) use ($key, $value) {
186 return data_get($item, $key) === $value;
190 if ($this->useAsCallable($key)) {
191 return ! is_null($this->first($key));
194 return in_array($key, $this->items, true);
198 * Get the items in the collection that are not present in the given items.
200 * @param mixed $items
203 public function diff($items)
205 return new static(array_diff($this->items, $this->getArrayableItems($items)));
209 * Get the items in the collection whose keys are not present in the given items.
211 * @param mixed $items
214 public function diffKeys($items)
216 return new static(array_diff_key($this->items, $this->getArrayableItems($items)));
220 * Execute a callback over each item.
222 * @param callable $callback
225 public function each(callable $callback)
227 foreach ($this->items as $key => $item) {
228 if ($callback($item, $key) === false) {
237 * Create a new collection consisting of every n-th element.
243 public function every($step, $offset = 0)
249 foreach ($this->items as $item) {
250 if ($position % $step === $offset) {
257 return new static($new);
261 * Get all items except for those with the specified keys.
266 public function except($keys)
268 $keys = is_array($keys) ? $keys : func_get_args();
270 return new static(Arr::except($this->items, $keys));
274 * Run a filter over each of the items.
276 * @param callable|null $callback
279 public function filter(callable $callback = null)
282 return new static(Arr::where($this->items, $callback));
285 return new static(array_filter($this->items));
289 * Filter items by the given key value pair.
292 * @param mixed $operator
293 * @param mixed $value
296 public function where($key, $operator, $value = null)
298 if (func_num_args() == 2) {
304 return $this->filter($this->operatorForWhere($key, $operator, $value));
308 * Get an operator checker callback.
311 * @param string $operator
312 * @param mixed $value
315 protected function operatorForWhere($key, $operator, $value)
317 return function ($item) use ($key, $operator, $value) {
318 $retrieved = data_get($item, $key);
323 case '==': return $retrieved == $value;
325 case '<>': return $retrieved != $value;
326 case '<': return $retrieved < $value;
327 case '>': return $retrieved > $value;
328 case '<=': return $retrieved <= $value;
329 case '>=': return $retrieved >= $value;
330 case '===': return $retrieved === $value;
331 case '!==': return $retrieved !== $value;
337 * Filter items by the given key value pair using strict comparison.
340 * @param mixed $value
343 public function whereStrict($key, $value)
345 return $this->where($key, '===', $value);
349 * Filter items by the given key value pair.
352 * @param mixed $values
353 * @param bool $strict
356 public function whereIn($key, $values, $strict = false)
358 $values = $this->getArrayableItems($values);
360 return $this->filter(function ($item) use ($key, $values, $strict) {
361 return in_array(data_get($item, $key), $values, $strict);
366 * Filter items by the given key value pair using strict comparison.
369 * @param mixed $values
372 public function whereInStrict($key, $values)
374 return $this->whereIn($key, $values, true);
378 * Get the first item from the collection.
380 * @param callable|null $callback
381 * @param mixed $default
384 public function first(callable $callback = null, $default = null)
386 return Arr::first($this->items, $callback, $default);
390 * Get a flattened array of the items in the collection.
395 public function flatten($depth = INF)
397 return new static(Arr::flatten($this->items, $depth));
401 * Flip the items in the collection.
405 public function flip()
407 return new static(array_flip($this->items));
411 * Remove an item from the collection by key.
413 * @param string|array $keys
416 public function forget($keys)
418 foreach ((array) $keys as $key) {
419 $this->offsetUnset($key);
426 * Get an item from the collection by key.
429 * @param mixed $default
432 public function get($key, $default = null)
434 if ($this->offsetExists($key)) {
435 return $this->items[$key];
438 return value($default);
442 * Group an associative array by a field or using a callback.
444 * @param callable|string $groupBy
445 * @param bool $preserveKeys
448 public function groupBy($groupBy, $preserveKeys = false)
450 $groupBy = $this->valueRetriever($groupBy);
454 foreach ($this->items as $key => $value) {
455 $groupKeys = $groupBy($value, $key);
457 if (! is_array($groupKeys)) {
458 $groupKeys = [$groupKeys];
461 foreach ($groupKeys as $groupKey) {
462 if (! array_key_exists($groupKey, $results)) {
463 $results[$groupKey] = new static;
466 $results[$groupKey]->offsetSet($preserveKeys ? $key : null, $value);
470 return new static($results);
474 * Key an associative array by a field or using a callback.
476 * @param callable|string $keyBy
479 public function keyBy($keyBy)
481 $keyBy = $this->valueRetriever($keyBy);
485 foreach ($this->items as $key => $item) {
486 $resolvedKey = $keyBy($item, $key);
488 if (is_object($resolvedKey)) {
489 $resolvedKey = (string) $resolvedKey;
492 $results[$resolvedKey] = $item;
495 return new static($results);
499 * Determine if an item exists in the collection by key.
504 public function has($key)
506 return $this->offsetExists($key);
510 * Concatenate values of a given key as a string.
512 * @param string $value
513 * @param string $glue
516 public function implode($value, $glue = null)
518 $first = $this->first();
520 if (is_array($first) || is_object($first)) {
521 return implode($glue, $this->pluck($value)->all());
524 return implode($value, $this->items);
528 * Intersect the collection with the given items.
530 * @param mixed $items
533 public function intersect($items)
535 return new static(array_intersect($this->items, $this->getArrayableItems($items)));
539 * Determine if the collection is empty or not.
543 public function isEmpty()
545 return empty($this->items);
549 * Determine if the given value is callable, but not a string.
551 * @param mixed $value
554 protected function useAsCallable($value)
556 return ! is_string($value) && is_callable($value);
560 * Get the keys of the collection items.
564 public function keys()
566 return new static(array_keys($this->items));
570 * Get the last item from the collection.
572 * @param callable|null $callback
573 * @param mixed $default
576 public function last(callable $callback = null, $default = null)
578 return Arr::last($this->items, $callback, $default);
582 * Get the values of a given key.
584 * @param string $value
585 * @param string|null $key
588 public function pluck($value, $key = null)
590 return new static(Arr::pluck($this->items, $value, $key));
594 * Run a map over each of the items.
596 * @param callable $callback
599 public function map(callable $callback)
601 $keys = array_keys($this->items);
603 $items = array_map($callback, $this->items, $keys);
605 return new static(array_combine($keys, $items));
609 * Run an associative map over each of the items.
611 * The callback should return an associative array with a single key/value pair.
613 * @param callable $callback
616 public function mapWithKeys(callable $callback)
618 return $this->flatMap($callback);
622 * Map a collection and flatten the result by a single level.
624 * @param callable $callback
627 public function flatMap(callable $callback)
629 return $this->map($callback)->collapse();
633 * Get the max value of a given key.
635 * @param callable|string|null $callback
638 public function max($callback = null)
640 $callback = $this->valueRetriever($callback);
642 return $this->reduce(function ($result, $item) use ($callback) {
643 $value = $callback($item);
645 return is_null($result) || $value > $result ? $value : $result;
650 * Merge the collection with the given items.
652 * @param mixed $items
655 public function merge($items)
657 return new static(array_merge($this->items, $this->getArrayableItems($items)));
661 * Create a collection by using this collection for keys and another for its values.
663 * @param mixed $values
666 public function combine($values)
668 return new static(array_combine($this->all(), $this->getArrayableItems($values)));
672 * Union the collection with the given items.
674 * @param mixed $items
677 public function union($items)
679 return new static($this->items + $this->getArrayableItems($items));
683 * Get the min value of a given key.
685 * @param callable|string|null $callback
688 public function min($callback = null)
690 $callback = $this->valueRetriever($callback);
692 return $this->reduce(function ($result, $item) use ($callback) {
693 $value = $callback($item);
695 return is_null($result) || $value < $result ? $value : $result;
700 * Get the items with the specified keys.
705 public function only($keys)
707 if (is_null($keys)) {
708 return new static($this->items);
711 $keys = is_array($keys) ? $keys : func_get_args();
713 return new static(Arr::only($this->items, $keys));
717 * "Paginate" the collection by slicing it into a smaller collection.
720 * @param int $perPage
723 public function forPage($page, $perPage)
725 return $this->slice(($page - 1) * $perPage, $perPage);
729 * Partition the collection into two arrays using the given callback or key.
731 * @param callable|string $key
732 * @param mixed $operator
733 * @param mixed $value
736 public function partition($key, $operator = null, $value = null)
738 $partitions = [new static, new static];
740 $callback = func_num_args() === 1
741 ? $this->valueRetriever($key)
742 : $this->operatorForWhere(...func_get_args());
744 foreach ($this->items as $key => $item) {
745 $partitions[(int) ! $callback($item, $key)][$key] = $item;
748 return new static($partitions);
751 * Pass the collection to the given callback and return the result.
753 * @param callable $callback
756 public function pipe(callable $callback)
758 return $callback($this);
762 * Get and remove the last item from the collection.
766 public function pop()
768 return array_pop($this->items);
772 * Push an item onto the beginning of the collection.
774 * @param mixed $value
778 public function prepend($value, $key = null)
780 $this->items = Arr::prepend($this->items, $value, $key);
786 * Push an item onto the end of the collection.
788 * @param mixed $value
791 public function push($value)
793 $this->offsetSet(null, $value);
799 * Get and remove an item from the collection.
802 * @param mixed $default
805 public function pull($key, $default = null)
807 return Arr::pull($this->items, $key, $default);
811 * Put an item in the collection by key.
814 * @param mixed $value
817 public function put($key, $value)
819 $this->offsetSet($key, $value);
825 * Get one or more items randomly from the collection.
830 * @throws \InvalidArgumentException
832 public function random($amount = 1)
834 if ($amount > ($count = $this->count())) {
835 throw new InvalidArgumentException("You requested {$amount} items, but there are only {$count} items in the collection");
838 $keys = array_rand($this->items, $amount);
841 return $this->items[$keys];
844 return new static(array_intersect_key($this->items, array_flip($keys)));
848 * Reduce the collection to a single value.
850 * @param callable $callback
851 * @param mixed $initial
854 public function reduce(callable $callback, $initial = null)
856 return array_reduce($this->items, $callback, $initial);
860 * Create a collection of all elements that do not pass a given truth test.
862 * @param callable|mixed $callback
865 public function reject($callback)
867 if ($this->useAsCallable($callback)) {
868 return $this->filter(function ($value, $key) use ($callback) {
869 return ! $callback($value, $key);
873 return $this->filter(function ($item) use ($callback) {
874 return $item != $callback;
879 * Reverse items order.
883 public function reverse()
885 return new static(array_reverse($this->items, true));
889 * Search the collection for a given value and return the corresponding key if successful.
891 * @param mixed $value
892 * @param bool $strict
895 public function search($value, $strict = false)
897 if (! $this->useAsCallable($value)) {
898 return array_search($value, $this->items, $strict);
901 foreach ($this->items as $key => $item) {
902 if (call_user_func($value, $item, $key)) {
911 * Get and remove the first item from the collection.
915 public function shift()
917 return array_shift($this->items);
921 * Shuffle the items in the collection.
926 public function shuffle($seed = null)
928 $items = $this->items;
930 if (is_null($seed)) {
935 usort($items, function () {
940 return new static($items);
944 * Slice the underlying collection array.
950 public function slice($offset, $length = null)
952 return new static(array_slice($this->items, $offset, $length, true));
956 * Split a collection into a certain number of groups.
958 * @param int $numberOfGroups
961 public function split($numberOfGroups)
963 if ($this->isEmpty()) {
967 $groupSize = ceil($this->count() / $numberOfGroups);
969 return $this->chunk($groupSize);
973 * Chunk the underlying collection array.
978 public function chunk($size)
982 foreach (array_chunk($this->items, $size, true) as $chunk) {
983 $chunks[] = new static($chunk);
986 return new static($chunks);
990 * Sort through each item with a callback.
992 * @param callable|null $callback
995 public function sort(callable $callback = null)
997 $items = $this->items;
1000 ? uasort($items, $callback)
1003 return new static($items);
1007 * Sort the collection using the given callback.
1009 * @param callable|string $callback
1010 * @param int $options
1011 * @param bool $descending
1014 public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
1018 $callback = $this->valueRetriever($callback);
1020 // First we will loop through the items and get the comparator from a callback
1021 // function which we were given. Then, we will sort the returned values and
1022 // and grab the corresponding values for the sorted keys from this array.
1023 foreach ($this->items as $key => $value) {
1024 $results[$key] = $callback($value, $key);
1027 $descending ? arsort($results, $options)
1028 : asort($results, $options);
1030 // Once we have sorted all of the keys in the array, we will loop through them
1031 // and grab the corresponding model so we can set the underlying items list
1032 // to the sorted version. Then we'll just return the collection instance.
1033 foreach (array_keys($results) as $key) {
1034 $results[$key] = $this->items[$key];
1037 return new static($results);
1041 * Sort the collection in descending order using the given callback.
1043 * @param callable|string $callback
1044 * @param int $options
1047 public function sortByDesc($callback, $options = SORT_REGULAR)
1049 return $this->sortBy($callback, $options, true);
1053 * Splice a portion of the underlying collection array.
1055 * @param int $offset
1056 * @param int|null $length
1057 * @param mixed $replacement
1060 public function splice($offset, $length = null, $replacement = [])
1062 if (func_num_args() == 1) {
1063 return new static(array_splice($this->items, $offset));
1066 return new static(array_splice($this->items, $offset, $length, $replacement));
1070 * Get the sum of the given values.
1072 * @param callable|string|null $callback
1075 public function sum($callback = null)
1077 if (is_null($callback)) {
1078 return array_sum($this->items);
1081 $callback = $this->valueRetriever($callback);
1083 return $this->reduce(function ($result, $item) use ($callback) {
1084 return $result + $callback($item);
1089 * Take the first or last {$limit} items.
1094 public function take($limit)
1097 return $this->slice($limit, abs($limit));
1100 return $this->slice(0, $limit);
1104 * Transform each item in the collection using a callback.
1106 * @param callable $callback
1109 public function transform(callable $callback)
1111 $this->items = $this->map($callback)->all();
1117 * Return only unique items from the collection array.
1119 * @param string|callable|null $key
1120 * @param bool $strict
1124 public function unique($key = null, $strict = false)
1126 if (is_null($key)) {
1127 return new static(array_unique($this->items, SORT_REGULAR));
1130 $key = $this->valueRetriever($key);
1134 return $this->reject(function ($item) use ($key, $strict, &$exists) {
1135 if (in_array($id = $key($item), $exists, $strict)) {
1144 * Return only unique items from the collection array using strict comparison.
1146 * @param string|callable|null $key
1149 public function uniqueStrict($key = null)
1151 return $this->unique($key, true);
1155 * Reset the keys on the underlying array.
1159 public function values()
1161 return new static(array_values($this->items));
1165 * Get a value retrieving callback.
1167 * @param string $value
1170 protected function valueRetriever($value)
1172 if ($this->useAsCallable($value)) {
1176 return function ($item) use ($value) {
1177 return data_get($item, $value);
1182 * Zip the collection together with one or more arrays.
1184 * e.g. new Collection([1, 2, 3])->zip([4, 5, 6]);
1185 * => [[1, 4], [2, 5], [3, 6]]
1187 * @param mixed ...$items
1190 public function zip($items)
1192 $arrayableItems = array_map(function ($items) {
1193 return $this->getArrayableItems($items);
1194 }, func_get_args());
1196 $params = array_merge([function () {
1197 return new static(func_get_args());
1198 }, $this->items], $arrayableItems);
1200 return new static(call_user_func_array('array_map', $params));
1204 * Get the collection of items as a plain array.
1208 public function toArray()
1210 return array_map(function ($value) {
1211 return $value instanceof Arrayable ? $value->toArray() : $value;
1216 * Convert the object into something JSON serializable.
1220 public function jsonSerialize()
1222 return array_map(function ($value) {
1223 if ($value instanceof JsonSerializable) {
1224 return $value->jsonSerialize();
1225 } elseif ($value instanceof Jsonable) {
1226 return json_decode($value->toJson(), true);
1227 } elseif ($value instanceof Arrayable) {
1228 return $value->toArray();
1236 * Get the collection of items as JSON.
1238 * @param int $options
1241 public function toJson($options = 0)
1243 return json_encode($this->jsonSerialize(), $options);
1247 * Get an iterator for the items.
1249 * @return \ArrayIterator
1251 public function getIterator()
1253 return new ArrayIterator($this->items);
1257 * Get a CachingIterator instance.
1260 * @return \CachingIterator
1262 public function getCachingIterator($flags = CachingIterator::CALL_TOSTRING)
1264 return new CachingIterator($this->getIterator(), $flags);
1268 * Count the number of items in the collection.
1272 public function count()
1274 return count($this->items);
1278 * Get a base Support collection instance from this collection.
1280 * @return \WPML\Collect\Support\Collection
1282 public function toBase()
1284 return new self($this);
1288 * Determine if an item exists at an offset.
1293 public function offsetExists($key)
1295 return array_key_exists($key, $this->items);
1299 * Get an item at a given offset.
1304 public function offsetGet($key)
1306 return $this->items[$key];
1310 * Set the item at a given offset.
1313 * @param mixed $value
1316 public function offsetSet($key, $value)
1318 if (is_null($key)) {
1319 $this->items[] = $value;
1321 $this->items[$key] = $value;
1326 * Unset the item at a given offset.
1328 * @param string $key
1331 public function offsetUnset($key)
1333 unset($this->items[$key]);
1337 * Convert the collection to its string representation.
1341 public function __toString()
1343 return $this->toJson();
1347 * Results array of items from Collection or Arrayable.
1349 * @param mixed $items
1352 protected function getArrayableItems($items)
1354 if (is_array($items)) {
1356 } elseif ($items instanceof self) {
1357 return $items->all();
1358 } elseif ($items instanceof Arrayable) {
1359 return $items->toArray();
1360 } elseif ($items instanceof Jsonable) {
1361 return json_decode($items->toJson(), true);
1362 } elseif ($items instanceof JsonSerializable) {
1363 return $items->jsonSerialize();
1364 } elseif ($items instanceof Traversable) {
1365 return iterator_to_array($items);
1368 return (array) $items;
1371 /** Those methods exist in the latest version of the library and have been copied here */
1374 * Run a dictionary map over the items.
1376 * The callback should return an associative array with a single key/value pair.
1378 * @param callable $callback
1381 public function mapToDictionary(callable $callback)
1385 foreach ($this->items as $key => $item) {
1386 $pair = $callback($item, $key);
1390 $value = reset($pair);
1392 if (! isset($dictionary[$key])) {
1393 $dictionary[$key] = [];
1396 $dictionary[$key][] = $value;
1399 return new static($dictionary);
1403 * Run a grouping map over the items.
1405 * The callback should return an associative array with a single key/value pair.
1407 * @param callable $callback
1410 public function mapToGroups(callable $callback)
1412 $groups = $this->mapToDictionary($callback);
1414 return $groups->map([$this, 'make']);
1418 * Move the items meeting the condition to the front of the collection
1420 * @param callable $condition
1422 * @return Collection - A new collection
1424 public function prioritize( callable $condition ) {
1425 $nonPrioritized = $this->reject( $condition );
1428 ->filter( $condition )
1430 ->merge( $nonPrioritized );
1434 * Convert an associative array of key => value to array of pairs [ key, value ].
1436 * @return Collection
1438 public function assocToPair() {
1439 return $this->map( function ( $item, $key ) {
1440 return [ $key, $item ];
1445 * Convert an array of pairs [ key, value ] to an associative array of key => value.
1447 * @return Collection
1449 public function pairToAssoc() {
1450 return $this->mapWithKeys( function ( $pair ) {
1451 return [ $pair[0] => $pair[1] ];
1456 * Executes the given function for each item while the total execution time is less than the time out.
1457 * Returns the unprocessed items if a timeout occurred.
1459 * @param callable $fn Function to all for each item.
1460 * @param int $timeout Timeout in seconds.
1462 * @return Collection
1464 public function eachWithTimeout( callable $fn, $timeout ) {
1465 $endTime = time() + $timeout;
1467 return $this->reduce( function ( Collection $unProcessed, $item ) use ( $endTime, $fn ) {
1468 if ( time() > $endTime ) {
1469 $unProcessed->push( $item );
1474 return $unProcessed;
1475 }, wpml_collect() );
1479 * Determine if the collection is not empty.
1483 public function isNotEmpty()
1485 return ! empty($this->items);
1489 * Cross join with the given lists, returning all possible permutations.
1491 * @param mixed ...$lists
1494 public function crossJoin(...$lists)
1496 return new static(Arr::crossJoin(
1497 $this->items, ...array_map([$this, 'getArrayableItems'], $lists)