Collection.php 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672
  1. <?php
  2. namespace Illuminate\Support;
  3. use ArrayAccess;
  4. use ArrayIterator;
  5. use Illuminate\Contracts\Support\CanBeEscapedWhenCastToString;
  6. use Illuminate\Support\Traits\EnumeratesValues;
  7. use Illuminate\Support\Traits\Macroable;
  8. use stdClass;
  9. class Collection implements ArrayAccess, CanBeEscapedWhenCastToString, Enumerable
  10. {
  11. use EnumeratesValues, Macroable;
  12. /**
  13. * The items contained in the collection.
  14. *
  15. * @var array
  16. */
  17. protected $items = [];
  18. /**
  19. * Create a new collection.
  20. *
  21. * @param mixed $items
  22. * @return void
  23. */
  24. public function __construct($items = [])
  25. {
  26. $this->items = $this->getArrayableItems($items);
  27. }
  28. /**
  29. * Create a collection with the given range.
  30. *
  31. * @param int $from
  32. * @param int $to
  33. * @return static
  34. */
  35. public static function range($from, $to)
  36. {
  37. return new static(range($from, $to));
  38. }
  39. /**
  40. * Get all of the items in the collection.
  41. *
  42. * @return array
  43. */
  44. public function all()
  45. {
  46. return $this->items;
  47. }
  48. /**
  49. * Get a lazy collection for the items in this collection.
  50. *
  51. * @return \Illuminate\Support\LazyCollection
  52. */
  53. public function lazy()
  54. {
  55. return new LazyCollection($this->items);
  56. }
  57. /**
  58. * Get the average value of a given key.
  59. *
  60. * @param callable|string|null $callback
  61. * @return mixed
  62. */
  63. public function avg($callback = null)
  64. {
  65. $callback = $this->valueRetriever($callback);
  66. $items = $this->map(function ($value) use ($callback) {
  67. return $callback($value);
  68. })->filter(function ($value) {
  69. return ! is_null($value);
  70. });
  71. if ($count = $items->count()) {
  72. return $items->sum() / $count;
  73. }
  74. }
  75. /**
  76. * Get the median of a given key.
  77. *
  78. * @param string|array|null $key
  79. * @return mixed
  80. */
  81. public function median($key = null)
  82. {
  83. $values = (isset($key) ? $this->pluck($key) : $this)
  84. ->filter(function ($item) {
  85. return ! is_null($item);
  86. })->sort()->values();
  87. $count = $values->count();
  88. if ($count === 0) {
  89. return;
  90. }
  91. $middle = (int) ($count / 2);
  92. if ($count % 2) {
  93. return $values->get($middle);
  94. }
  95. return (new static([
  96. $values->get($middle - 1), $values->get($middle),
  97. ]))->average();
  98. }
  99. /**
  100. * Get the mode of a given key.
  101. *
  102. * @param string|array|null $key
  103. * @return array|null
  104. */
  105. public function mode($key = null)
  106. {
  107. if ($this->count() === 0) {
  108. return;
  109. }
  110. $collection = isset($key) ? $this->pluck($key) : $this;
  111. $counts = new static;
  112. $collection->each(function ($value) use ($counts) {
  113. $counts[$value] = isset($counts[$value]) ? $counts[$value] + 1 : 1;
  114. });
  115. $sorted = $counts->sort();
  116. $highestValue = $sorted->last();
  117. return $sorted->filter(function ($value) use ($highestValue) {
  118. return $value == $highestValue;
  119. })->sort()->keys()->all();
  120. }
  121. /**
  122. * Collapse the collection of items into a single array.
  123. *
  124. * @return static
  125. */
  126. public function collapse()
  127. {
  128. return new static(Arr::collapse($this->items));
  129. }
  130. /**
  131. * Determine if an item exists in the collection.
  132. *
  133. * @param mixed $key
  134. * @param mixed $operator
  135. * @param mixed $value
  136. * @return bool
  137. */
  138. public function contains($key, $operator = null, $value = null)
  139. {
  140. if (func_num_args() === 1) {
  141. if ($this->useAsCallable($key)) {
  142. $placeholder = new stdClass;
  143. return $this->first($key, $placeholder) !== $placeholder;
  144. }
  145. return in_array($key, $this->items);
  146. }
  147. return $this->contains($this->operatorForWhere(...func_get_args()));
  148. }
  149. /**
  150. * Determine if an item is not contained in the collection.
  151. *
  152. * @param mixed $key
  153. * @param mixed $operator
  154. * @param mixed $value
  155. * @return bool
  156. */
  157. public function doesntContain($key, $operator = null, $value = null)
  158. {
  159. return ! $this->contains(...func_get_args());
  160. }
  161. /**
  162. * Cross join with the given lists, returning all possible permutations.
  163. *
  164. * @param mixed ...$lists
  165. * @return static
  166. */
  167. public function crossJoin(...$lists)
  168. {
  169. return new static(Arr::crossJoin(
  170. $this->items, ...array_map([$this, 'getArrayableItems'], $lists)
  171. ));
  172. }
  173. /**
  174. * Get the items in the collection that are not present in the given items.
  175. *
  176. * @param mixed $items
  177. * @return static
  178. */
  179. public function diff($items)
  180. {
  181. return new static(array_diff($this->items, $this->getArrayableItems($items)));
  182. }
  183. /**
  184. * Get the items in the collection that are not present in the given items, using the callback.
  185. *
  186. * @param mixed $items
  187. * @param callable $callback
  188. * @return static
  189. */
  190. public function diffUsing($items, callable $callback)
  191. {
  192. return new static(array_udiff($this->items, $this->getArrayableItems($items), $callback));
  193. }
  194. /**
  195. * Get the items in the collection whose keys and values are not present in the given items.
  196. *
  197. * @param mixed $items
  198. * @return static
  199. */
  200. public function diffAssoc($items)
  201. {
  202. return new static(array_diff_assoc($this->items, $this->getArrayableItems($items)));
  203. }
  204. /**
  205. * Get the items in the collection whose keys and values are not present in the given items, using the callback.
  206. *
  207. * @param mixed $items
  208. * @param callable $callback
  209. * @return static
  210. */
  211. public function diffAssocUsing($items, callable $callback)
  212. {
  213. return new static(array_diff_uassoc($this->items, $this->getArrayableItems($items), $callback));
  214. }
  215. /**
  216. * Get the items in the collection whose keys are not present in the given items.
  217. *
  218. * @param mixed $items
  219. * @return static
  220. */
  221. public function diffKeys($items)
  222. {
  223. return new static(array_diff_key($this->items, $this->getArrayableItems($items)));
  224. }
  225. /**
  226. * Get the items in the collection whose keys are not present in the given items, using the callback.
  227. *
  228. * @param mixed $items
  229. * @param callable $callback
  230. * @return static
  231. */
  232. public function diffKeysUsing($items, callable $callback)
  233. {
  234. return new static(array_diff_ukey($this->items, $this->getArrayableItems($items), $callback));
  235. }
  236. /**
  237. * Retrieve duplicate items from the collection.
  238. *
  239. * @param callable|string|null $callback
  240. * @param bool $strict
  241. * @return static
  242. */
  243. public function duplicates($callback = null, $strict = false)
  244. {
  245. $items = $this->map($this->valueRetriever($callback));
  246. $uniqueItems = $items->unique(null, $strict);
  247. $compare = $this->duplicateComparator($strict);
  248. $duplicates = new static;
  249. foreach ($items as $key => $value) {
  250. if ($uniqueItems->isNotEmpty() && $compare($value, $uniqueItems->first())) {
  251. $uniqueItems->shift();
  252. } else {
  253. $duplicates[$key] = $value;
  254. }
  255. }
  256. return $duplicates;
  257. }
  258. /**
  259. * Retrieve duplicate items from the collection using strict comparison.
  260. *
  261. * @param callable|string|null $callback
  262. * @return static
  263. */
  264. public function duplicatesStrict($callback = null)
  265. {
  266. return $this->duplicates($callback, true);
  267. }
  268. /**
  269. * Get the comparison function to detect duplicates.
  270. *
  271. * @param bool $strict
  272. * @return \Closure
  273. */
  274. protected function duplicateComparator($strict)
  275. {
  276. if ($strict) {
  277. return function ($a, $b) {
  278. return $a === $b;
  279. };
  280. }
  281. return function ($a, $b) {
  282. return $a == $b;
  283. };
  284. }
  285. /**
  286. * Get all items except for those with the specified keys.
  287. *
  288. * @param \Illuminate\Support\Collection|mixed $keys
  289. * @return static
  290. */
  291. public function except($keys)
  292. {
  293. if ($keys instanceof Enumerable) {
  294. $keys = $keys->all();
  295. } elseif (! is_array($keys)) {
  296. $keys = func_get_args();
  297. }
  298. return new static(Arr::except($this->items, $keys));
  299. }
  300. /**
  301. * Run a filter over each of the items.
  302. *
  303. * @param callable|null $callback
  304. * @return static
  305. */
  306. public function filter(callable $callback = null)
  307. {
  308. if ($callback) {
  309. return new static(Arr::where($this->items, $callback));
  310. }
  311. return new static(array_filter($this->items));
  312. }
  313. /**
  314. * Get the first item from the collection passing the given truth test.
  315. *
  316. * @param callable|null $callback
  317. * @param mixed $default
  318. * @return mixed
  319. */
  320. public function first(callable $callback = null, $default = null)
  321. {
  322. return Arr::first($this->items, $callback, $default);
  323. }
  324. /**
  325. * Get a flattened array of the items in the collection.
  326. *
  327. * @param int $depth
  328. * @return static
  329. */
  330. public function flatten($depth = INF)
  331. {
  332. return new static(Arr::flatten($this->items, $depth));
  333. }
  334. /**
  335. * Flip the items in the collection.
  336. *
  337. * @return static
  338. */
  339. public function flip()
  340. {
  341. return new static(array_flip($this->items));
  342. }
  343. /**
  344. * Remove an item from the collection by key.
  345. *
  346. * @param string|int|array $keys
  347. * @return $this
  348. */
  349. public function forget($keys)
  350. {
  351. foreach ((array) $keys as $key) {
  352. $this->offsetUnset($key);
  353. }
  354. return $this;
  355. }
  356. /**
  357. * Get an item from the collection by key.
  358. *
  359. * @param mixed $key
  360. * @param mixed $default
  361. * @return mixed
  362. */
  363. public function get($key, $default = null)
  364. {
  365. if (array_key_exists($key, $this->items)) {
  366. return $this->items[$key];
  367. }
  368. return value($default);
  369. }
  370. /**
  371. * Get an item from the collection by key or add it to collection if it does not exist.
  372. *
  373. * @param mixed $key
  374. * @param mixed $value
  375. * @return mixed
  376. */
  377. public function getOrPut($key, $value)
  378. {
  379. if (array_key_exists($key, $this->items)) {
  380. return $this->items[$key];
  381. }
  382. $this->offsetSet($key, $value = value($value));
  383. return $value;
  384. }
  385. /**
  386. * Group an associative array by a field or using a callback.
  387. *
  388. * @param array|callable|string $groupBy
  389. * @param bool $preserveKeys
  390. * @return static
  391. */
  392. public function groupBy($groupBy, $preserveKeys = false)
  393. {
  394. if (! $this->useAsCallable($groupBy) && is_array($groupBy)) {
  395. $nextGroups = $groupBy;
  396. $groupBy = array_shift($nextGroups);
  397. }
  398. $groupBy = $this->valueRetriever($groupBy);
  399. $results = [];
  400. foreach ($this->items as $key => $value) {
  401. $groupKeys = $groupBy($value, $key);
  402. if (! is_array($groupKeys)) {
  403. $groupKeys = [$groupKeys];
  404. }
  405. foreach ($groupKeys as $groupKey) {
  406. $groupKey = is_bool($groupKey) ? (int) $groupKey : $groupKey;
  407. if (! array_key_exists($groupKey, $results)) {
  408. $results[$groupKey] = new static;
  409. }
  410. $results[$groupKey]->offsetSet($preserveKeys ? $key : null, $value);
  411. }
  412. }
  413. $result = new static($results);
  414. if (! empty($nextGroups)) {
  415. return $result->map->groupBy($nextGroups, $preserveKeys);
  416. }
  417. return $result;
  418. }
  419. /**
  420. * Key an associative array by a field or using a callback.
  421. *
  422. * @param callable|string $keyBy
  423. * @return static
  424. */
  425. public function keyBy($keyBy)
  426. {
  427. $keyBy = $this->valueRetriever($keyBy);
  428. $results = [];
  429. foreach ($this->items as $key => $item) {
  430. $resolvedKey = $keyBy($item, $key);
  431. if (is_object($resolvedKey)) {
  432. $resolvedKey = (string) $resolvedKey;
  433. }
  434. $results[$resolvedKey] = $item;
  435. }
  436. return new static($results);
  437. }
  438. /**
  439. * Determine if an item exists in the collection by key.
  440. *
  441. * @param mixed $key
  442. * @return bool
  443. */
  444. public function has($key)
  445. {
  446. $keys = is_array($key) ? $key : func_get_args();
  447. foreach ($keys as $value) {
  448. if (! array_key_exists($value, $this->items)) {
  449. return false;
  450. }
  451. }
  452. return true;
  453. }
  454. /**
  455. * Determine if any of the keys exist in the collection.
  456. *
  457. * @param mixed $key
  458. * @return bool
  459. */
  460. public function hasAny($key)
  461. {
  462. if ($this->isEmpty()) {
  463. return false;
  464. }
  465. $keys = is_array($key) ? $key : func_get_args();
  466. foreach ($keys as $value) {
  467. if ($this->has($value)) {
  468. return true;
  469. }
  470. }
  471. return false;
  472. }
  473. /**
  474. * Concatenate values of a given key as a string.
  475. *
  476. * @param string $value
  477. * @param string|null $glue
  478. * @return string
  479. */
  480. public function implode($value, $glue = null)
  481. {
  482. $first = $this->first();
  483. if (is_array($first) || (is_object($first) && ! $first instanceof Stringable)) {
  484. return implode($glue ?? '', $this->pluck($value)->all());
  485. }
  486. return implode($value ?? '', $this->items);
  487. }
  488. /**
  489. * Intersect the collection with the given items.
  490. *
  491. * @param mixed $items
  492. * @return static
  493. */
  494. public function intersect($items)
  495. {
  496. return new static(array_intersect($this->items, $this->getArrayableItems($items)));
  497. }
  498. /**
  499. * Intersect the collection with the given items by key.
  500. *
  501. * @param mixed $items
  502. * @return static
  503. */
  504. public function intersectByKeys($items)
  505. {
  506. return new static(array_intersect_key(
  507. $this->items, $this->getArrayableItems($items)
  508. ));
  509. }
  510. /**
  511. * Determine if the collection is empty or not.
  512. *
  513. * @return bool
  514. */
  515. public function isEmpty()
  516. {
  517. return empty($this->items);
  518. }
  519. /**
  520. * Determine if the collection contains a single item.
  521. *
  522. * @return bool
  523. */
  524. public function containsOneItem()
  525. {
  526. return $this->count() === 1;
  527. }
  528. /**
  529. * Join all items from the collection using a string. The final items can use a separate glue string.
  530. *
  531. * @param string $glue
  532. * @param string $finalGlue
  533. * @return string
  534. */
  535. public function join($glue, $finalGlue = '')
  536. {
  537. if ($finalGlue === '') {
  538. return $this->implode($glue);
  539. }
  540. $count = $this->count();
  541. if ($count === 0) {
  542. return '';
  543. }
  544. if ($count === 1) {
  545. return $this->last();
  546. }
  547. $collection = new static($this->items);
  548. $finalItem = $collection->pop();
  549. return $collection->implode($glue).$finalGlue.$finalItem;
  550. }
  551. /**
  552. * Get the keys of the collection items.
  553. *
  554. * @return static
  555. */
  556. public function keys()
  557. {
  558. return new static(array_keys($this->items));
  559. }
  560. /**
  561. * Get the last item from the collection.
  562. *
  563. * @param callable|null $callback
  564. * @param mixed $default
  565. * @return mixed
  566. */
  567. public function last(callable $callback = null, $default = null)
  568. {
  569. return Arr::last($this->items, $callback, $default);
  570. }
  571. /**
  572. * Get the values of a given key.
  573. *
  574. * @param string|array|int|null $value
  575. * @param string|null $key
  576. * @return static
  577. */
  578. public function pluck($value, $key = null)
  579. {
  580. return new static(Arr::pluck($this->items, $value, $key));
  581. }
  582. /**
  583. * Run a map over each of the items.
  584. *
  585. * @param callable $callback
  586. * @return static
  587. */
  588. public function map(callable $callback)
  589. {
  590. $keys = array_keys($this->items);
  591. $items = array_map($callback, $this->items, $keys);
  592. return new static(array_combine($keys, $items));
  593. }
  594. /**
  595. * Run a dictionary map over the items.
  596. *
  597. * The callback should return an associative array with a single key/value pair.
  598. *
  599. * @param callable $callback
  600. * @return static
  601. */
  602. public function mapToDictionary(callable $callback)
  603. {
  604. $dictionary = [];
  605. foreach ($this->items as $key => $item) {
  606. $pair = $callback($item, $key);
  607. $key = key($pair);
  608. $value = reset($pair);
  609. if (! isset($dictionary[$key])) {
  610. $dictionary[$key] = [];
  611. }
  612. $dictionary[$key][] = $value;
  613. }
  614. return new static($dictionary);
  615. }
  616. /**
  617. * Run an associative map over each of the items.
  618. *
  619. * The callback should return an associative array with a single key/value pair.
  620. *
  621. * @param callable $callback
  622. * @return static
  623. */
  624. public function mapWithKeys(callable $callback)
  625. {
  626. $result = [];
  627. foreach ($this->items as $key => $value) {
  628. $assoc = $callback($value, $key);
  629. foreach ($assoc as $mapKey => $mapValue) {
  630. $result[$mapKey] = $mapValue;
  631. }
  632. }
  633. return new static($result);
  634. }
  635. /**
  636. * Merge the collection with the given items.
  637. *
  638. * @param mixed $items
  639. * @return static
  640. */
  641. public function merge($items)
  642. {
  643. return new static(array_merge($this->items, $this->getArrayableItems($items)));
  644. }
  645. /**
  646. * Recursively merge the collection with the given items.
  647. *
  648. * @param mixed $items
  649. * @return static
  650. */
  651. public function mergeRecursive($items)
  652. {
  653. return new static(array_merge_recursive($this->items, $this->getArrayableItems($items)));
  654. }
  655. /**
  656. * Create a collection by using this collection for keys and another for its values.
  657. *
  658. * @param mixed $values
  659. * @return static
  660. */
  661. public function combine($values)
  662. {
  663. return new static(array_combine($this->all(), $this->getArrayableItems($values)));
  664. }
  665. /**
  666. * Union the collection with the given items.
  667. *
  668. * @param mixed $items
  669. * @return static
  670. */
  671. public function union($items)
  672. {
  673. return new static($this->items + $this->getArrayableItems($items));
  674. }
  675. /**
  676. * Create a new collection consisting of every n-th element.
  677. *
  678. * @param int $step
  679. * @param int $offset
  680. * @return static
  681. */
  682. public function nth($step, $offset = 0)
  683. {
  684. $new = [];
  685. $position = 0;
  686. foreach ($this->slice($offset)->items as $item) {
  687. if ($position % $step === 0) {
  688. $new[] = $item;
  689. }
  690. $position++;
  691. }
  692. return new static($new);
  693. }
  694. /**
  695. * Get the items with the specified keys.
  696. *
  697. * @param mixed $keys
  698. * @return static
  699. */
  700. public function only($keys)
  701. {
  702. if (is_null($keys)) {
  703. return new static($this->items);
  704. }
  705. if ($keys instanceof Enumerable) {
  706. $keys = $keys->all();
  707. }
  708. $keys = is_array($keys) ? $keys : func_get_args();
  709. return new static(Arr::only($this->items, $keys));
  710. }
  711. /**
  712. * Get and remove the last N items from the collection.
  713. *
  714. * @param int $count
  715. * @return mixed
  716. */
  717. public function pop($count = 1)
  718. {
  719. if ($count === 1) {
  720. return array_pop($this->items);
  721. }
  722. if ($this->isEmpty()) {
  723. return new static;
  724. }
  725. $results = [];
  726. $collectionCount = $this->count();
  727. foreach (range(1, min($count, $collectionCount)) as $item) {
  728. array_push($results, array_pop($this->items));
  729. }
  730. return new static($results);
  731. }
  732. /**
  733. * Push an item onto the beginning of the collection.
  734. *
  735. * @param mixed $value
  736. * @param mixed $key
  737. * @return $this
  738. */
  739. public function prepend($value, $key = null)
  740. {
  741. $this->items = Arr::prepend($this->items, ...func_get_args());
  742. return $this;
  743. }
  744. /**
  745. * Push one or more items onto the end of the collection.
  746. *
  747. * @param mixed $values
  748. * @return $this
  749. */
  750. public function push(...$values)
  751. {
  752. foreach ($values as $value) {
  753. $this->items[] = $value;
  754. }
  755. return $this;
  756. }
  757. /**
  758. * Push all of the given items onto the collection.
  759. *
  760. * @param iterable $source
  761. * @return static
  762. */
  763. public function concat($source)
  764. {
  765. $result = new static($this);
  766. foreach ($source as $item) {
  767. $result->push($item);
  768. }
  769. return $result;
  770. }
  771. /**
  772. * Get and remove an item from the collection.
  773. *
  774. * @param mixed $key
  775. * @param mixed $default
  776. * @return mixed
  777. */
  778. public function pull($key, $default = null)
  779. {
  780. return Arr::pull($this->items, $key, $default);
  781. }
  782. /**
  783. * Put an item in the collection by key.
  784. *
  785. * @param mixed $key
  786. * @param mixed $value
  787. * @return $this
  788. */
  789. public function put($key, $value)
  790. {
  791. $this->offsetSet($key, $value);
  792. return $this;
  793. }
  794. /**
  795. * Get one or a specified number of items randomly from the collection.
  796. *
  797. * @param int|null $number
  798. * @return static|mixed
  799. *
  800. * @throws \InvalidArgumentException
  801. */
  802. public function random($number = null)
  803. {
  804. if (is_null($number)) {
  805. return Arr::random($this->items);
  806. }
  807. return new static(Arr::random($this->items, $number));
  808. }
  809. /**
  810. * Replace the collection items with the given items.
  811. *
  812. * @param mixed $items
  813. * @return static
  814. */
  815. public function replace($items)
  816. {
  817. return new static(array_replace($this->items, $this->getArrayableItems($items)));
  818. }
  819. /**
  820. * Recursively replace the collection items with the given items.
  821. *
  822. * @param mixed $items
  823. * @return static
  824. */
  825. public function replaceRecursive($items)
  826. {
  827. return new static(array_replace_recursive($this->items, $this->getArrayableItems($items)));
  828. }
  829. /**
  830. * Reverse items order.
  831. *
  832. * @return static
  833. */
  834. public function reverse()
  835. {
  836. return new static(array_reverse($this->items, true));
  837. }
  838. /**
  839. * Search the collection for a given value and return the corresponding key if successful.
  840. *
  841. * @param mixed $value
  842. * @param bool $strict
  843. * @return mixed
  844. */
  845. public function search($value, $strict = false)
  846. {
  847. if (! $this->useAsCallable($value)) {
  848. return array_search($value, $this->items, $strict);
  849. }
  850. foreach ($this->items as $key => $item) {
  851. if ($value($item, $key)) {
  852. return $key;
  853. }
  854. }
  855. return false;
  856. }
  857. /**
  858. * Get and remove the first N items from the collection.
  859. *
  860. * @param int $count
  861. * @return mixed
  862. */
  863. public function shift($count = 1)
  864. {
  865. if ($count === 1) {
  866. return array_shift($this->items);
  867. }
  868. if ($this->isEmpty()) {
  869. return new static;
  870. }
  871. $results = [];
  872. $collectionCount = $this->count();
  873. foreach (range(1, min($count, $collectionCount)) as $item) {
  874. array_push($results, array_shift($this->items));
  875. }
  876. return new static($results);
  877. }
  878. /**
  879. * Shuffle the items in the collection.
  880. *
  881. * @param int|null $seed
  882. * @return static
  883. */
  884. public function shuffle($seed = null)
  885. {
  886. return new static(Arr::shuffle($this->items, $seed));
  887. }
  888. /**
  889. * Create chunks representing a "sliding window" view of the items in the collection.
  890. *
  891. * @param int $size
  892. * @param int $step
  893. * @return static
  894. */
  895. public function sliding($size = 2, $step = 1)
  896. {
  897. $chunks = floor(($this->count() - $size) / $step) + 1;
  898. return static::times($chunks, function ($number) use ($size, $step) {
  899. return $this->slice(($number - 1) * $step, $size);
  900. });
  901. }
  902. /**
  903. * Skip the first {$count} items.
  904. *
  905. * @param int $count
  906. * @return static
  907. */
  908. public function skip($count)
  909. {
  910. return $this->slice($count);
  911. }
  912. /**
  913. * Skip items in the collection until the given condition is met.
  914. *
  915. * @param mixed $value
  916. * @return static
  917. */
  918. public function skipUntil($value)
  919. {
  920. return new static($this->lazy()->skipUntil($value)->all());
  921. }
  922. /**
  923. * Skip items in the collection while the given condition is met.
  924. *
  925. * @param mixed $value
  926. * @return static
  927. */
  928. public function skipWhile($value)
  929. {
  930. return new static($this->lazy()->skipWhile($value)->all());
  931. }
  932. /**
  933. * Slice the underlying collection array.
  934. *
  935. * @param int $offset
  936. * @param int|null $length
  937. * @return static
  938. */
  939. public function slice($offset, $length = null)
  940. {
  941. return new static(array_slice($this->items, $offset, $length, true));
  942. }
  943. /**
  944. * Split a collection into a certain number of groups.
  945. *
  946. * @param int $numberOfGroups
  947. * @return static
  948. */
  949. public function split($numberOfGroups)
  950. {
  951. if ($this->isEmpty()) {
  952. return new static;
  953. }
  954. $groups = new static;
  955. $groupSize = floor($this->count() / $numberOfGroups);
  956. $remain = $this->count() % $numberOfGroups;
  957. $start = 0;
  958. for ($i = 0; $i < $numberOfGroups; $i++) {
  959. $size = $groupSize;
  960. if ($i < $remain) {
  961. $size++;
  962. }
  963. if ($size) {
  964. $groups->push(new static(array_slice($this->items, $start, $size)));
  965. $start += $size;
  966. }
  967. }
  968. return $groups;
  969. }
  970. /**
  971. * Split a collection into a certain number of groups, and fill the first groups completely.
  972. *
  973. * @param int $numberOfGroups
  974. * @return static
  975. */
  976. public function splitIn($numberOfGroups)
  977. {
  978. return $this->chunk(ceil($this->count() / $numberOfGroups));
  979. }
  980. /**
  981. * Get the first item in the collection, but only if exactly one item exists. Otherwise, throw an exception.
  982. *
  983. * @param mixed $key
  984. * @param mixed $operator
  985. * @param mixed $value
  986. * @return mixed
  987. *
  988. * @throws \Illuminate\Support\ItemNotFoundException
  989. * @throws \Illuminate\Support\MultipleItemsFoundException
  990. */
  991. public function sole($key = null, $operator = null, $value = null)
  992. {
  993. $filter = func_num_args() > 1
  994. ? $this->operatorForWhere(...func_get_args())
  995. : $key;
  996. $items = $this->when($filter)->filter($filter);
  997. if ($items->isEmpty()) {
  998. throw new ItemNotFoundException;
  999. }
  1000. if ($items->count() > 1) {
  1001. throw new MultipleItemsFoundException;
  1002. }
  1003. return $items->first();
  1004. }
  1005. /**
  1006. * Get the first item in the collection but throw an exception if no matching items exist.
  1007. *
  1008. * @param mixed $key
  1009. * @param mixed $operator
  1010. * @param mixed $value
  1011. * @return mixed
  1012. *
  1013. * @throws \Illuminate\Support\ItemNotFoundException
  1014. */
  1015. public function firstOrFail($key = null, $operator = null, $value = null)
  1016. {
  1017. $filter = func_num_args() > 1
  1018. ? $this->operatorForWhere(...func_get_args())
  1019. : $key;
  1020. $placeholder = new stdClass();
  1021. $item = $this->first($filter, $placeholder);
  1022. if ($item === $placeholder) {
  1023. throw new ItemNotFoundException;
  1024. }
  1025. return $item;
  1026. }
  1027. /**
  1028. * Chunk the collection into chunks of the given size.
  1029. *
  1030. * @param int $size
  1031. * @return static
  1032. */
  1033. public function chunk($size)
  1034. {
  1035. if ($size <= 0) {
  1036. return new static;
  1037. }
  1038. $chunks = [];
  1039. foreach (array_chunk($this->items, $size, true) as $chunk) {
  1040. $chunks[] = new static($chunk);
  1041. }
  1042. return new static($chunks);
  1043. }
  1044. /**
  1045. * Chunk the collection into chunks with a callback.
  1046. *
  1047. * @param callable $callback
  1048. * @return static
  1049. */
  1050. public function chunkWhile(callable $callback)
  1051. {
  1052. return new static(
  1053. $this->lazy()->chunkWhile($callback)->mapInto(static::class)
  1054. );
  1055. }
  1056. /**
  1057. * Sort through each item with a callback.
  1058. *
  1059. * @param callable|int|null $callback
  1060. * @return static
  1061. */
  1062. public function sort($callback = null)
  1063. {
  1064. $items = $this->items;
  1065. $callback && is_callable($callback)
  1066. ? uasort($items, $callback)
  1067. : asort($items, $callback ?? SORT_REGULAR);
  1068. return new static($items);
  1069. }
  1070. /**
  1071. * Sort items in descending order.
  1072. *
  1073. * @param int $options
  1074. * @return static
  1075. */
  1076. public function sortDesc($options = SORT_REGULAR)
  1077. {
  1078. $items = $this->items;
  1079. arsort($items, $options);
  1080. return new static($items);
  1081. }
  1082. /**
  1083. * Sort the collection using the given callback.
  1084. *
  1085. * @param callable|array|string $callback
  1086. * @param int $options
  1087. * @param bool $descending
  1088. * @return static
  1089. */
  1090. public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
  1091. {
  1092. if (is_array($callback) && ! is_callable($callback)) {
  1093. return $this->sortByMany($callback);
  1094. }
  1095. $results = [];
  1096. $callback = $this->valueRetriever($callback);
  1097. // First we will loop through the items and get the comparator from a callback
  1098. // function which we were given. Then, we will sort the returned values and
  1099. // grab all the corresponding values for the sorted keys from this array.
  1100. foreach ($this->items as $key => $value) {
  1101. $results[$key] = $callback($value, $key);
  1102. }
  1103. $descending ? arsort($results, $options)
  1104. : asort($results, $options);
  1105. // Once we have sorted all of the keys in the array, we will loop through them
  1106. // and grab the corresponding model so we can set the underlying items list
  1107. // to the sorted version. Then we'll just return the collection instance.
  1108. foreach (array_keys($results) as $key) {
  1109. $results[$key] = $this->items[$key];
  1110. }
  1111. return new static($results);
  1112. }
  1113. /**
  1114. * Sort the collection using multiple comparisons.
  1115. *
  1116. * @param array $comparisons
  1117. * @return static
  1118. */
  1119. protected function sortByMany(array $comparisons = [])
  1120. {
  1121. $items = $this->items;
  1122. usort($items, function ($a, $b) use ($comparisons) {
  1123. foreach ($comparisons as $comparison) {
  1124. $comparison = Arr::wrap($comparison);
  1125. $prop = $comparison[0];
  1126. $ascending = Arr::get($comparison, 1, true) === true ||
  1127. Arr::get($comparison, 1, true) === 'asc';
  1128. $result = 0;
  1129. if (! is_string($prop) && is_callable($prop)) {
  1130. $result = $prop($a, $b);
  1131. } else {
  1132. $values = [data_get($a, $prop), data_get($b, $prop)];
  1133. if (! $ascending) {
  1134. $values = array_reverse($values);
  1135. }
  1136. $result = $values[0] <=> $values[1];
  1137. }
  1138. if ($result === 0) {
  1139. continue;
  1140. }
  1141. return $result;
  1142. }
  1143. });
  1144. return new static($items);
  1145. }
  1146. /**
  1147. * Sort the collection in descending order using the given callback.
  1148. *
  1149. * @param callable|string $callback
  1150. * @param int $options
  1151. * @return static
  1152. */
  1153. public function sortByDesc($callback, $options = SORT_REGULAR)
  1154. {
  1155. return $this->sortBy($callback, $options, true);
  1156. }
  1157. /**
  1158. * Sort the collection keys.
  1159. *
  1160. * @param int $options
  1161. * @param bool $descending
  1162. * @return static
  1163. */
  1164. public function sortKeys($options = SORT_REGULAR, $descending = false)
  1165. {
  1166. $items = $this->items;
  1167. $descending ? krsort($items, $options) : ksort($items, $options);
  1168. return new static($items);
  1169. }
  1170. /**
  1171. * Sort the collection keys in descending order.
  1172. *
  1173. * @param int $options
  1174. * @return static
  1175. */
  1176. public function sortKeysDesc($options = SORT_REGULAR)
  1177. {
  1178. return $this->sortKeys($options, true);
  1179. }
  1180. /**
  1181. * Sort the collection keys using a callback.
  1182. *
  1183. * @param callable $callback
  1184. * @return static
  1185. */
  1186. public function sortKeysUsing(callable $callback)
  1187. {
  1188. $items = $this->items;
  1189. uksort($items, $callback);
  1190. return new static($items);
  1191. }
  1192. /**
  1193. * Splice a portion of the underlying collection array.
  1194. *
  1195. * @param int $offset
  1196. * @param int|null $length
  1197. * @param mixed $replacement
  1198. * @return static
  1199. */
  1200. public function splice($offset, $length = null, $replacement = [])
  1201. {
  1202. if (func_num_args() === 1) {
  1203. return new static(array_splice($this->items, $offset));
  1204. }
  1205. return new static(array_splice($this->items, $offset, $length, $this->getArrayableItems($replacement)));
  1206. }
  1207. /**
  1208. * Take the first or last {$limit} items.
  1209. *
  1210. * @param int $limit
  1211. * @return static
  1212. */
  1213. public function take($limit)
  1214. {
  1215. if ($limit < 0) {
  1216. return $this->slice($limit, abs($limit));
  1217. }
  1218. return $this->slice(0, $limit);
  1219. }
  1220. /**
  1221. * Take items in the collection until the given condition is met.
  1222. *
  1223. * @param mixed $value
  1224. * @return static
  1225. */
  1226. public function takeUntil($value)
  1227. {
  1228. return new static($this->lazy()->takeUntil($value)->all());
  1229. }
  1230. /**
  1231. * Take items in the collection while the given condition is met.
  1232. *
  1233. * @param mixed $value
  1234. * @return static
  1235. */
  1236. public function takeWhile($value)
  1237. {
  1238. return new static($this->lazy()->takeWhile($value)->all());
  1239. }
  1240. /**
  1241. * Transform each item in the collection using a callback.
  1242. *
  1243. * @param callable $callback
  1244. * @return $this
  1245. */
  1246. public function transform(callable $callback)
  1247. {
  1248. $this->items = $this->map($callback)->all();
  1249. return $this;
  1250. }
  1251. /**
  1252. * Convert a flatten "dot" notation array into an expanded array.
  1253. *
  1254. * @return static
  1255. */
  1256. public function undot()
  1257. {
  1258. return new static(Arr::undot($this->all()));
  1259. }
  1260. /**
  1261. * Return only unique items from the collection array.
  1262. *
  1263. * @param string|callable|null $key
  1264. * @param bool $strict
  1265. * @return static
  1266. */
  1267. public function unique($key = null, $strict = false)
  1268. {
  1269. if (is_null($key) && $strict === false) {
  1270. return new static(array_unique($this->items, SORT_REGULAR));
  1271. }
  1272. $callback = $this->valueRetriever($key);
  1273. $exists = [];
  1274. return $this->reject(function ($item, $key) use ($callback, $strict, &$exists) {
  1275. if (in_array($id = $callback($item, $key), $exists, $strict)) {
  1276. return true;
  1277. }
  1278. $exists[] = $id;
  1279. });
  1280. }
  1281. /**
  1282. * Reset the keys on the underlying array.
  1283. *
  1284. * @return static
  1285. */
  1286. public function values()
  1287. {
  1288. return new static(array_values($this->items));
  1289. }
  1290. /**
  1291. * Zip the collection together with one or more arrays.
  1292. *
  1293. * e.g. new Collection([1, 2, 3])->zip([4, 5, 6]);
  1294. * => [[1, 4], [2, 5], [3, 6]]
  1295. *
  1296. * @param mixed ...$items
  1297. * @return static
  1298. */
  1299. public function zip($items)
  1300. {
  1301. $arrayableItems = array_map(function ($items) {
  1302. return $this->getArrayableItems($items);
  1303. }, func_get_args());
  1304. $params = array_merge([function () {
  1305. return new static(func_get_args());
  1306. }, $this->items], $arrayableItems);
  1307. return new static(array_map(...$params));
  1308. }
  1309. /**
  1310. * Pad collection to the specified length with a value.
  1311. *
  1312. * @param int $size
  1313. * @param mixed $value
  1314. * @return static
  1315. */
  1316. public function pad($size, $value)
  1317. {
  1318. return new static(array_pad($this->items, $size, $value));
  1319. }
  1320. /**
  1321. * Get an iterator for the items.
  1322. *
  1323. * @return \ArrayIterator
  1324. */
  1325. #[\ReturnTypeWillChange]
  1326. public function getIterator()
  1327. {
  1328. return new ArrayIterator($this->items);
  1329. }
  1330. /**
  1331. * Count the number of items in the collection.
  1332. *
  1333. * @return int
  1334. */
  1335. #[\ReturnTypeWillChange]
  1336. public function count()
  1337. {
  1338. return count($this->items);
  1339. }
  1340. /**
  1341. * Count the number of items in the collection by a field or using a callback.
  1342. *
  1343. * @param callable|string $countBy
  1344. * @return static
  1345. */
  1346. public function countBy($countBy = null)
  1347. {
  1348. return new static($this->lazy()->countBy($countBy)->all());
  1349. }
  1350. /**
  1351. * Add an item to the collection.
  1352. *
  1353. * @param mixed $item
  1354. * @return $this
  1355. */
  1356. public function add($item)
  1357. {
  1358. $this->items[] = $item;
  1359. return $this;
  1360. }
  1361. /**
  1362. * Get a base Support collection instance from this collection.
  1363. *
  1364. * @return \Illuminate\Support\Collection
  1365. */
  1366. public function toBase()
  1367. {
  1368. return new self($this);
  1369. }
  1370. /**
  1371. * Determine if an item exists at an offset.
  1372. *
  1373. * @param mixed $key
  1374. * @return bool
  1375. */
  1376. #[\ReturnTypeWillChange]
  1377. public function offsetExists($key)
  1378. {
  1379. return isset($this->items[$key]);
  1380. }
  1381. /**
  1382. * Get an item at a given offset.
  1383. *
  1384. * @param mixed $key
  1385. * @return mixed
  1386. */
  1387. #[\ReturnTypeWillChange]
  1388. public function offsetGet($key)
  1389. {
  1390. return $this->items[$key];
  1391. }
  1392. /**
  1393. * Set the item at a given offset.
  1394. *
  1395. * @param mixed $key
  1396. * @param mixed $value
  1397. * @return void
  1398. */
  1399. #[\ReturnTypeWillChange]
  1400. public function offsetSet($key, $value)
  1401. {
  1402. if (is_null($key)) {
  1403. $this->items[] = $value;
  1404. } else {
  1405. $this->items[$key] = $value;
  1406. }
  1407. }
  1408. /**
  1409. * Unset the item at a given offset.
  1410. *
  1411. * @param mixed $key
  1412. * @return void
  1413. */
  1414. #[\ReturnTypeWillChange]
  1415. public function offsetUnset($key)
  1416. {
  1417. unset($this->items[$key]);
  1418. }
  1419. }