Collection.php 46 KB

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