LazyCollection.php 47 KB

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