Collection.php 51 KB

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