LazyCollection.php 54 KB

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