Collection.php 51 KB

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