Collection.php 48 KB

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