EnumeratesValues.php 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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\Traits;
  12. use BackedEnum;
  13. use CachingIterator;
  14. use Closure;
  15. use Exception;
  16. use Hyperf\Collection\Arr;
  17. use Hyperf\Collection\Collection;
  18. use Hyperf\Collection\Enumerable;
  19. use Hyperf\Collection\HigherOrderCollectionProxy;
  20. use Hyperf\Conditionable\Conditionable;
  21. use Hyperf\Contract\Arrayable;
  22. use Hyperf\Contract\Jsonable;
  23. use JsonSerializable;
  24. use RuntimeException;
  25. use Traversable;
  26. use UnexpectedValueException;
  27. use UnitEnum;
  28. use function Hyperf\Collection\data_get;
  29. use function Hyperf\Support\class_basename;
  30. use function Hyperf\Support\value;
  31. /**
  32. * @template TKey of array-key
  33. * @template TTimesValue
  34. *
  35. * @template TValue
  36. * @property HigherOrderCollectionProxy $average
  37. * @property HigherOrderCollectionProxy $avg
  38. * @property HigherOrderCollectionProxy $contains
  39. * @property HigherOrderCollectionProxy $doesntContain
  40. * @property HigherOrderCollectionProxy $each
  41. * @property HigherOrderCollectionProxy $every
  42. * @property HigherOrderCollectionProxy $filter
  43. * @property HigherOrderCollectionProxy $first
  44. * @property HigherOrderCollectionProxy $flatMap
  45. * @property HigherOrderCollectionProxy $groupBy
  46. * @property HigherOrderCollectionProxy $keyBy
  47. * @property HigherOrderCollectionProxy $map
  48. * @property HigherOrderCollectionProxy $max
  49. * @property HigherOrderCollectionProxy $min
  50. * @property HigherOrderCollectionProxy $partition
  51. * @property HigherOrderCollectionProxy $percentage
  52. * @property HigherOrderCollectionProxy $reject
  53. * @property HigherOrderCollectionProxy $skipUntil
  54. * @property HigherOrderCollectionProxy $skipWhile
  55. * @property HigherOrderCollectionProxy $some
  56. * @property HigherOrderCollectionProxy $sortBy
  57. * @property HigherOrderCollectionProxy $sortByDesc
  58. * @property HigherOrderCollectionProxy $sum
  59. * @property HigherOrderCollectionProxy $takeUntil
  60. * @property HigherOrderCollectionProxy $takeWhile
  61. * @property HigherOrderCollectionProxy $unique
  62. * @property HigherOrderCollectionProxy $unless
  63. * @property HigherOrderCollectionProxy $until
  64. * @property HigherOrderCollectionProxy $when
  65. */
  66. trait EnumeratesValues
  67. {
  68. use Conditionable;
  69. /**
  70. * Indicates that the object's string representation should be escaped when __toString is invoked.
  71. *
  72. * @var bool
  73. */
  74. protected $escapeWhenCastingToString = false;
  75. /**
  76. * The methods that can be proxied.
  77. *
  78. * @var array<int, string>
  79. */
  80. protected static $proxies = [
  81. 'average',
  82. 'avg',
  83. 'contains',
  84. 'doesntContain',
  85. 'each',
  86. 'every',
  87. 'filter',
  88. 'first',
  89. 'flatMap',
  90. 'groupBy',
  91. 'keyBy',
  92. 'map',
  93. 'max',
  94. 'min',
  95. 'partition',
  96. 'percentage',
  97. 'reject',
  98. 'skipUntil',
  99. 'skipWhile',
  100. 'some',
  101. 'sortBy',
  102. 'sortByDesc',
  103. 'sum',
  104. 'takeUntil',
  105. 'takeWhile',
  106. 'unique',
  107. 'unless',
  108. 'until',
  109. 'when',
  110. ];
  111. /**
  112. * Convert the collection to its string representation.
  113. */
  114. public function __toString(): string
  115. {
  116. return $this->toJson();
  117. }
  118. /**
  119. * Dynamically access collection proxies.
  120. *
  121. * @param string $key
  122. * @return mixed
  123. *
  124. * @throws Exception
  125. */
  126. public function __get($key)
  127. {
  128. if (! in_array($key, static::$proxies)) {
  129. throw new Exception("Property [{$key}] does not exist on this collection instance.");
  130. }
  131. return new HigherOrderCollectionProxy($this, $key);
  132. }
  133. /**
  134. * Create a new collection instance if the value isn't one already.
  135. *
  136. * @template TMakeKey of array-key
  137. * @template TMakeValue
  138. *
  139. * @param null|Arrayable<TMakeKey, TMakeValue>|iterable<TMakeKey, TMakeValue> $items
  140. * @return static<TMakeKey, TMakeValue>
  141. */
  142. public static function make(mixed $items = []): static
  143. {
  144. return new static($items);
  145. }
  146. /**
  147. * Wrap the given value in a collection if applicable.
  148. *
  149. * @template TWrapValue
  150. *
  151. * @param iterable<array-key, TWrapValue>|TWrapValue $value
  152. * @return static<array-key, TWrapValue>
  153. */
  154. public static function wrap(mixed $value): static
  155. {
  156. return $value instanceof Enumerable
  157. ? new static($value)
  158. : new static(Arr::wrap($value));
  159. }
  160. /**
  161. * Get the underlying items from the given collection if applicable.
  162. *
  163. * @template TUnwrapKey of array-key
  164. * @template TUnwrapValue
  165. *
  166. * @param array<TUnwrapKey, TUnwrapValue>|static<TUnwrapKey, TUnwrapValue> $value
  167. * @return array<TUnwrapKey, TUnwrapValue>
  168. */
  169. public static function unwrap(mixed $value): array
  170. {
  171. return $value instanceof Enumerable ? $value->all() : $value;
  172. }
  173. /**
  174. * Create a new instance with no items.
  175. */
  176. public static function empty(): static
  177. {
  178. return new static([]);
  179. }
  180. /**
  181. * Create a new collection by invoking the callback a given amount of times.
  182. *
  183. * @param null|(callable(int): TTimesValue) $callback
  184. * @return static<int, TTimesValue>
  185. */
  186. public static function times(int $number, ?callable $callback = null): static
  187. {
  188. if ($number < 1) {
  189. return new static();
  190. }
  191. return static::range(1, $number)
  192. ->unless($callback == null)
  193. ->map($callback);
  194. }
  195. /**
  196. * Get the average value of a given key.
  197. *
  198. * @param null|(callable(TValue): float|int)|string $callback
  199. */
  200. public function avg(mixed $callback = null): null|float|int
  201. {
  202. $callback = $this->valueRetriever($callback);
  203. $reduced = $this->reduce(static function (&$reduce, $value) use ($callback) {
  204. if (! is_null($resolved = $callback($value))) {
  205. $reduce[0] += $resolved;
  206. ++$reduce[1];
  207. }
  208. return $reduce;
  209. }, [0, 0]);
  210. return $reduced[1] ? $reduced[0] / $reduced[1] : null;
  211. }
  212. /**
  213. * Alias for the "avg" method.
  214. *
  215. * @param null|(callable(TValue): float|int)|string $callback
  216. */
  217. public function average(mixed $callback = null): null|float|int
  218. {
  219. return $this->avg($callback);
  220. }
  221. /**
  222. * Alias for the "contains" method.
  223. *
  224. * @param (callable(TValue, TKey): bool)|string|TValue $key
  225. * @param mixed $operator
  226. * @param mixed $value
  227. * @return bool
  228. */
  229. public function some($key, $operator = null, $value = null)
  230. {
  231. return $this->contains(...func_get_args());
  232. }
  233. /**
  234. * Dump the given arguments and terminate execution.
  235. *
  236. * @param mixed ...$args
  237. * @return never
  238. */
  239. public function dd(...$args)
  240. {
  241. $this->dump(...$args);
  242. exit(1);
  243. }
  244. /**
  245. * Dump the items.
  246. *
  247. * @param mixed ...$args
  248. * @return $this
  249. */
  250. public function dump(...$args)
  251. {
  252. if (! function_exists('dump')) {
  253. throw new RuntimeException('symfony/var-dumper package required, please require the package via "composer require symfony/var-dumper"');
  254. }
  255. dump($this->all(), ...$args);
  256. return $this;
  257. }
  258. /**
  259. * Execute a callback over each item.
  260. *
  261. * @param callable(TValue, TKey): mixed $callback
  262. */
  263. public function each(callable $callback): static
  264. {
  265. foreach ($this as $key => $item) {
  266. if ($callback($item, $key) === false) {
  267. break;
  268. }
  269. }
  270. return $this;
  271. }
  272. /**
  273. * Execute a callback over each nested chunk of items.
  274. *
  275. * @param callable(...mixed): mixed $callback
  276. */
  277. public function eachSpread(callable $callback): static
  278. {
  279. return $this->each(function ($chunk, $key) use ($callback) {
  280. $chunk[] = $key;
  281. return $callback(...$chunk);
  282. });
  283. }
  284. /**
  285. * Determine if all items pass the given truth test.
  286. *
  287. * @param (callable(TValue, TKey): bool)|string|TValue $key
  288. */
  289. public function every(mixed $key, mixed $operator = null, mixed $value = null): bool
  290. {
  291. if (func_num_args() === 1) {
  292. $callback = $this->valueRetriever($key);
  293. foreach ($this as $k => $v) {
  294. if (! $callback($v, $k)) {
  295. return false;
  296. }
  297. }
  298. return true;
  299. }
  300. return $this->every($this->operatorForWhere(...func_get_args()));
  301. }
  302. /**
  303. * Get the first item by the given key value pair.
  304. *
  305. * @return null|TValue
  306. */
  307. public function firstWhere(callable|string $key, mixed $operator = null, mixed $value = null): mixed
  308. {
  309. return $this->first($this->operatorForWhere(...func_get_args()));
  310. }
  311. /**
  312. * Get a single key's value from the first matching item in the collection.
  313. *
  314. * @template TValueDefault
  315. *
  316. * @param string $key
  317. * @param (Closure(): TValueDefault)|TValueDefault $default
  318. * @return TValue|TValueDefault
  319. */
  320. public function value($key, $default = null)
  321. {
  322. if ($value = $this->firstWhere($key)) {
  323. return data_get($value, $key, $default);
  324. }
  325. return value($default);
  326. }
  327. /**
  328. * Ensure that every item in the collection is of the expected type.
  329. *
  330. * @template TEnsureOfType
  331. *
  332. * @param array<array-key, class-string<TEnsureOfType>>|class-string<TEnsureOfType> $type
  333. * @return static<TKey, TEnsureOfType>
  334. *
  335. * @throws UnexpectedValueException
  336. */
  337. public function ensure($type)
  338. {
  339. $allowedTypes = is_array($type) ? $type : [$type];
  340. return $this->each(function ($item, $index) use ($allowedTypes) {
  341. $itemType = get_debug_type($item);
  342. foreach ($allowedTypes as $allowedType) {
  343. if ($itemType === $allowedType || $item instanceof $allowedType) {
  344. return true;
  345. }
  346. }
  347. throw new UnexpectedValueException(
  348. sprintf("Collection should only include [%s] items, but '%s' found at position %d.", implode(', ', $allowedTypes), $itemType, $index)
  349. );
  350. });
  351. }
  352. /**
  353. * Determine if the collection is not empty.
  354. */
  355. public function isNotEmpty(): bool
  356. {
  357. return ! $this->isEmpty();
  358. }
  359. /**
  360. * Run a map over each nested chunk of items.
  361. *
  362. * @template TMapSpreadValue
  363. *
  364. * @param callable(mixed...): TMapSpreadValue $callback
  365. * @return static<TKey, TMapSpreadValue>
  366. */
  367. public function mapSpread(callable $callback): self|static
  368. {
  369. return $this->map(function ($chunk, $key) use ($callback) {
  370. $chunk[] = $key;
  371. return $callback(...$chunk);
  372. });
  373. }
  374. /**
  375. * Run a grouping map over the items.
  376. *
  377. * The callback should return an associative array with a single key/value pair.
  378. *
  379. * @template TMapToGroupsKey of array-key
  380. * @template TMapToGroupsValue
  381. *
  382. * @param callable(TValue, TKey): array<TMapToGroupsKey, TMapToGroupsValue> $callback
  383. * @return static<TMapToGroupsKey, static<int, TMapToGroupsValue>>
  384. */
  385. public function mapToGroups(callable $callback): self|static
  386. {
  387. $groups = $this->mapToDictionary($callback);
  388. return $groups->map([$this, 'make']);
  389. }
  390. /**
  391. * Map a collection and flatten the result by a single level.
  392. *
  393. * @template TFlatMapKey of array-key
  394. * @template TFlatMapValue
  395. *
  396. * @param callable(TValue, TKey): (array<TFlatMapKey, TFlatMapValue>|Collection<TFlatMapKey, TFlatMapValue>) $callback
  397. * @return static<TFlatMapKey, TFlatMapValue>
  398. */
  399. public function flatMap(callable $callback): self|static
  400. {
  401. return $this->map($callback)->collapse();
  402. }
  403. /**
  404. * Map the values into a new class.
  405. *
  406. * @template TMapIntoValue
  407. * @param class-string<TMapIntoValue> $class
  408. * @return static<TKey, TMapIntoValue>
  409. */
  410. public function mapInto(mixed $class): self|static
  411. {
  412. if (is_subclass_of($class, BackedEnum::class)) {
  413. return $this->map(fn ($value, $key) => $class::from($value));
  414. }
  415. return $this->map(fn ($value, $key) => new $class($value, $key));
  416. }
  417. /**
  418. * Get the min value of a given key.
  419. *
  420. * @param null|(callable(TValue):mixed)|string $callback
  421. */
  422. public function min(mixed $callback = null): mixed
  423. {
  424. $callback = $this->valueRetriever($callback);
  425. return $this->map(fn ($value) => $callback($value))
  426. ->filter(fn ($value) => ! is_null($value))
  427. ->reduce(fn ($result, $value) => is_null($result) || $value < $result ? $value : $result);
  428. }
  429. /**
  430. * Get the max value of a given key.
  431. *
  432. * @param null|(callable(TValue):mixed)|string $callback
  433. */
  434. public function max(mixed $callback = null): mixed
  435. {
  436. $callback = $this->valueRetriever($callback);
  437. return $this->filter(fn ($value) => ! is_null($value))->reduce(function ($result, $item) use ($callback) {
  438. $value = $callback($item);
  439. return is_null($result) || $value > $result ? $value : $result;
  440. });
  441. }
  442. /**
  443. * "Paginate" the collection by slicing it into a smaller collection.
  444. */
  445. public function forPage(int $page, int $perPage): static
  446. {
  447. $offset = max(0, ($page - 1) * $perPage);
  448. return $this->slice($offset, $perPage);
  449. }
  450. /**
  451. * Partition the collection into two arrays using the given callback or key.
  452. *
  453. * @param (callable(TValue, TKey): bool)|string|TValue $key
  454. * @param null|string|TValue $operator
  455. * @param null|TValue $value
  456. * @return static<int<0, 1>, static<TKey, TValue>>
  457. */
  458. public function partition(mixed $key, mixed $operator = null, mixed $value = null): static
  459. {
  460. $passed = [];
  461. $failed = [];
  462. $callback = func_num_args() === 1
  463. ? $this->valueRetriever($key)
  464. : $this->operatorForWhere(...func_get_args());
  465. foreach ($this as $key => $item) {
  466. if ($callback($item, $key)) {
  467. $passed[$key] = $item;
  468. } else {
  469. $failed[$key] = $item;
  470. }
  471. }
  472. return new static([new static($passed), new static($failed)]);
  473. }
  474. /**
  475. * Calculate the percentage of items that pass a given truth test.
  476. *
  477. * @param (callable(TValue, TKey): bool) $callback
  478. * @return null|float
  479. */
  480. public function percentage(callable $callback, int $precision = 2)
  481. {
  482. if ($this->isEmpty()) {
  483. return null;
  484. }
  485. return round(
  486. $this->filter($callback)->count() / $this->count() * 100,
  487. $precision
  488. );
  489. }
  490. /**
  491. * Get the sum of the given values.
  492. *
  493. * @param null|(callable(TValue): mixed)|string $callback
  494. * @return mixed
  495. */
  496. public function sum($callback = null)
  497. {
  498. $callback = is_null($callback)
  499. ? $this->identity()
  500. : $this->valueRetriever($callback);
  501. return $this->reduce(fn ($result, $item) => $result + $callback($item), 0);
  502. }
  503. /**
  504. * Apply the callback if the collection is empty.
  505. *
  506. * @template TWhenEmptyReturnType
  507. *
  508. * @param (callable($this): TWhenEmptyReturnType) $callback
  509. * @param null|(callable($this): TWhenEmptyReturnType) $default
  510. * @return $this|TWhenEmptyReturnType
  511. */
  512. public function whenEmpty(callable $callback, ?callable $default = null)
  513. {
  514. return $this->when($this->isEmpty(), $callback, $default);
  515. }
  516. /**
  517. * Apply the callback if the collection is not empty.
  518. *
  519. * @template TWhenNotEmptyReturnType
  520. *
  521. * @param callable($this): TWhenNotEmptyReturnType $callback
  522. * @param null|(callable($this): TWhenNotEmptyReturnType) $default
  523. * @return $this|TWhenNotEmptyReturnType
  524. */
  525. public function whenNotEmpty(callable $callback, ?callable $default = null)
  526. {
  527. return $this->when($this->isNotEmpty(), $callback, $default);
  528. }
  529. /**
  530. * Apply the callback unless the collection is empty.
  531. *
  532. * @template TUnlessEmptyReturnType
  533. *
  534. * @param callable($this): TUnlessEmptyReturnType $callback
  535. * @param null|(callable($this): TUnlessEmptyReturnType) $default
  536. * @return $this|TUnlessEmptyReturnType
  537. */
  538. public function unlessEmpty(callable $callback, ?callable $default = null)
  539. {
  540. return $this->whenNotEmpty($callback, $default);
  541. }
  542. /**
  543. * Apply the callback unless the collection is not empty.
  544. *
  545. * @template TUnlessNotEmptyReturnType
  546. *
  547. * @param callable($this): TUnlessNotEmptyReturnType $callback
  548. * @param null|(callable($this): TUnlessNotEmptyReturnType) $default
  549. * @return $this|TUnlessNotEmptyReturnType
  550. */
  551. public function unlessNotEmpty(callable $callback, ?callable $default = null)
  552. {
  553. return $this->whenEmpty($callback, $default);
  554. }
  555. /**
  556. * Filter items by the given key value pair.
  557. */
  558. public function where(null|callable|string $key, mixed $operator = null, mixed $value = null): static
  559. {
  560. return $this->filter($this->operatorForWhere(...func_get_args()));
  561. }
  562. /**
  563. * Filter items where the value for the given key is null.
  564. *
  565. * @param null|string $key
  566. * @return static
  567. */
  568. public function whereNull($key = null)
  569. {
  570. return $this->whereStrict($key, null);
  571. }
  572. /**
  573. * Filter items where the value for the given key is not null.
  574. *
  575. * @param null|string $key
  576. * @return static
  577. */
  578. public function whereNotNull($key = null)
  579. {
  580. return $this->where($key, '!==', null);
  581. }
  582. /**
  583. * Filter items by the given key value pair using strict comparison.
  584. */
  585. public function whereStrict(?string $key, mixed $value): static
  586. {
  587. return $this->where($key, '===', $value);
  588. }
  589. /**
  590. * Filter items by the given key value pair.
  591. *
  592. * @param Arrayable|iterable $values
  593. */
  594. public function whereIn(string $key, mixed $values, bool $strict = false): static
  595. {
  596. $values = $this->getArrayableItems($values);
  597. return $this->filter(fn ($item) => in_array(data_get($item, $key), $values, $strict));
  598. }
  599. /**
  600. * Filter items by the given key value pair using strict comparison.
  601. *
  602. * @param Arrayable|iterable $values
  603. */
  604. public function whereInStrict(string $key, mixed $values): static
  605. {
  606. return $this->whereIn($key, $values, true);
  607. }
  608. /**
  609. * Filter items such that the value of the given key is between the given values.
  610. *
  611. * @param string $key
  612. * @param Arrayable|iterable $values
  613. * @return static
  614. */
  615. public function whereBetween($key, $values)
  616. {
  617. return $this->where($key, '>=', reset($values))->where($key, '<=', end($values));
  618. }
  619. /**
  620. * Filter items such that the value of the given key is not between the given values.
  621. *
  622. * @param string $key
  623. * @param Arrayable|iterable $values
  624. * @return static
  625. */
  626. public function whereNotBetween($key, $values)
  627. {
  628. return $this->filter(
  629. fn ($item) => data_get($item, $key) < reset($values) || data_get($item, $key) > end($values)
  630. );
  631. }
  632. /**
  633. * Filter items by the given key value pair.
  634. *
  635. * @param Arrayable|iterable $values
  636. */
  637. public function whereNotIn(string $key, mixed $values, bool $strict = false): static
  638. {
  639. $values = $this->getArrayableItems($values);
  640. return $this->reject(fn ($item) => in_array(data_get($item, $key), $values, $strict));
  641. }
  642. /**
  643. * Filter items by the given key value pair using strict comparison.
  644. *
  645. * @param Arrayable|iterable $values
  646. */
  647. public function whereNotInStrict(string $key, mixed $values): static
  648. {
  649. return $this->whereNotIn($key, $values, true);
  650. }
  651. /**
  652. * Filter the items, removing any items that don't match the given type(s).
  653. *
  654. * @template TWhereInstanceOf
  655. *
  656. * @param array<array-key, class-string<TWhereInstanceOf>>|class-string<TWhereInstanceOf> $type
  657. * @return static<TKey, TWhereInstanceOf>
  658. */
  659. public function whereInstanceOf(array|string $type): static
  660. {
  661. return $this->filter(function ($value) use ($type) {
  662. if (is_array($type)) {
  663. foreach ($type as $classType) {
  664. if ($value instanceof $classType) {
  665. return true;
  666. }
  667. }
  668. return false;
  669. }
  670. return $value instanceof $type;
  671. });
  672. }
  673. /**
  674. * Pass the collection to the given callback and return the result.
  675. *
  676. * @template TPipeReturnType
  677. *
  678. * @param callable($this): TPipeReturnType $callback
  679. * @return TPipeReturnType
  680. */
  681. public function pipe(callable $callback): mixed
  682. {
  683. return $callback($this);
  684. }
  685. /**
  686. * Pass the collection into a new class.
  687. *
  688. * @template TPipeIntoValue
  689. *
  690. * @param class-string<TPipeIntoValue> $class
  691. * @return TPipeIntoValue
  692. */
  693. public function pipeInto($class)
  694. {
  695. return new $class($this);
  696. }
  697. /**
  698. * Pass the collection through a series of callable pipes and return the result.
  699. *
  700. * @param array<callable> $callbacks
  701. * @return mixed
  702. */
  703. public function pipeThrough($callbacks)
  704. {
  705. return Collection::make($callbacks)->reduce(
  706. fn ($carry, $callback) => $callback($carry),
  707. $this,
  708. );
  709. }
  710. /**
  711. * Reduce the collection to a single value.
  712. *
  713. * @template TReduceInitial
  714. * @template TReduceReturnType
  715. *
  716. * @param callable(TReduceInitial|TReduceReturnType, TValue, TKey): TReduceReturnType $callback
  717. * @param TReduceInitial $initial
  718. * @return TReduceReturnType
  719. */
  720. public function reduce(callable $callback, mixed $initial = null): mixed
  721. {
  722. $result = $initial;
  723. foreach ($this as $key => $value) {
  724. $result = $callback($result, $value, $key);
  725. }
  726. return $result;
  727. }
  728. /**
  729. * Reduce the collection to multiple aggregate values.
  730. *
  731. * @param mixed ...$initial
  732. * @return array
  733. *
  734. * @throws UnexpectedValueException
  735. */
  736. public function reduceSpread(callable $callback, ...$initial)
  737. {
  738. $result = $initial;
  739. foreach ($this as $key => $value) {
  740. $result = call_user_func_array($callback, array_merge($result, [$value, $key]));
  741. if (! is_array($result)) {
  742. throw new UnexpectedValueException(sprintf(
  743. "%s::reduceSpread expects reducer to return an array, but got a '%s' instead.",
  744. class_basename(static::class),
  745. gettype($result)
  746. ));
  747. }
  748. }
  749. return $result;
  750. }
  751. /**
  752. * Reduce an associative collection to a single value.
  753. *
  754. * @template TReduceWithKeysInitial
  755. * @template TReduceWithKeysReturnType
  756. *
  757. * @param callable(TReduceWithKeysInitial|TReduceWithKeysReturnType, TValue, TKey): TReduceWithKeysReturnType $callback
  758. * @param TReduceWithKeysInitial $initial
  759. * @return TReduceWithKeysReturnType
  760. */
  761. public function reduceWithKeys(callable $callback, $initial = null)
  762. {
  763. return $this->reduce($callback, $initial);
  764. }
  765. /**
  766. * Create a collection of all elements that do not pass a given truth test.
  767. *
  768. * @param bool|(callable(TValue, TKey): bool)|TValue $callback
  769. */
  770. public function reject(mixed $callback = true): static
  771. {
  772. $useAsCallable = $this->useAsCallable($callback);
  773. return $this->filter(function ($value, $key) use ($callback, $useAsCallable) {
  774. return $useAsCallable
  775. ? ! $callback($value, $key)
  776. : $value != $callback;
  777. });
  778. }
  779. /**
  780. * Pass the collection to the given callback and then return it.
  781. *
  782. * @param callable($this): mixed $callback
  783. * @return $this
  784. */
  785. public function tap(callable $callback): static
  786. {
  787. $callback($this);
  788. return $this;
  789. }
  790. /**
  791. * Return only unique items from the collection array.
  792. *
  793. * @param null|(callable(TValue, TKey): mixed)|string $key
  794. */
  795. public function unique(mixed $key = null, bool $strict = false): static
  796. {
  797. $callback = $this->valueRetriever($key);
  798. $exists = [];
  799. return $this->reject(function ($item, $key) use ($callback, $strict, &$exists) {
  800. if (in_array($id = $callback($item, $key), $exists, $strict)) {
  801. return true;
  802. }
  803. $exists[] = $id;
  804. return false;
  805. });
  806. }
  807. /**
  808. * Return only unique items from the collection array using strict comparison.
  809. *
  810. * @param null|(callable(TValue, TKey): mixed)|string $key
  811. */
  812. public function uniqueStrict(mixed $key = null): static
  813. {
  814. return $this->unique($key, true);
  815. }
  816. /**
  817. * Collect the values into a collection.
  818. *
  819. * @return Collection<TKey, TValue>
  820. */
  821. public function collect(): Collection
  822. {
  823. return new Collection($this->all());
  824. }
  825. /**
  826. * Get the collection of items as a plain array.
  827. *
  828. * @return array<TKey, mixed>
  829. */
  830. public function toArray(): array
  831. {
  832. return $this->map(fn ($value) => $value instanceof Arrayable ? $value->toArray() : $value)->all();
  833. }
  834. /**
  835. * Convert the object into something JSON serializable.
  836. *
  837. * @return array<TKey, mixed>
  838. */
  839. public function jsonSerialize(): array
  840. {
  841. $result = [];
  842. foreach ($this->all() as $key => $value) {
  843. $result[$key] = match (true) {
  844. $value instanceof JsonSerializable => $value->jsonSerialize(),
  845. $value instanceof Jsonable => json_decode($value->__toString(), true),
  846. $value instanceof Arrayable => $value->toArray(),
  847. default => $value
  848. };
  849. }
  850. return $result;
  851. }
  852. /**
  853. * Get the collection of items as JSON.
  854. *
  855. * @return string
  856. */
  857. public function toJson(int $options = 0)
  858. {
  859. return json_encode($this->jsonSerialize(), $options);
  860. }
  861. /**
  862. * Get a CachingIterator instance.
  863. *
  864. * @return CachingIterator
  865. */
  866. public function getCachingIterator(int $flags = CachingIterator::CALL_TOSTRING)
  867. {
  868. /* @phpstan-ignore-next-line */
  869. return new CachingIterator($this->getIterator(), $flags);
  870. }
  871. /**
  872. * Indicate that the model's string representation should be escaped when __toString is invoked.
  873. *
  874. * @param bool $escape
  875. * @return $this
  876. */
  877. public function escapeWhenCastingToString($escape = true)
  878. {
  879. $this->escapeWhenCastingToString = $escape;
  880. return $this;
  881. }
  882. /**
  883. * Add a method to the list of proxied methods.
  884. */
  885. public static function proxy(string $method): void
  886. {
  887. static::$proxies[] = $method;
  888. }
  889. /**
  890. * Results array of items from Collection or Arrayable.
  891. * @param mixed $items
  892. * @return array<TKey,TValue>
  893. */
  894. protected function getArrayableItems($items): array
  895. {
  896. return match (true) {
  897. is_array($items) => $items,
  898. $items instanceof Enumerable => $items->all(),
  899. $items instanceof Arrayable => $items->toArray(),
  900. $items instanceof Jsonable => json_decode($items->__toString(), true),
  901. $items instanceof JsonSerializable => $items->jsonSerialize(),
  902. $items instanceof Traversable => iterator_to_array($items),
  903. $items instanceof UnitEnum => [$items],
  904. default => (array) $items,
  905. };
  906. }
  907. /**
  908. * Get an operator checker callback.
  909. *
  910. * @param callable|string $key
  911. * @param null|string $operator
  912. */
  913. protected function operatorForWhere(mixed $key, mixed $operator = null, mixed $value = null): Closure
  914. {
  915. if ($this->useAsCallable($key)) {
  916. return $key;
  917. }
  918. if (func_num_args() === 1) {
  919. $value = true;
  920. $operator = '=';
  921. }
  922. if (func_num_args() === 2) {
  923. $value = $operator;
  924. $operator = '=';
  925. }
  926. return function ($item) use ($key, $operator, $value) {
  927. $retrieved = data_get($item, $key);
  928. $strings = array_filter([$retrieved, $value], function ($value) {
  929. return is_string($value) || (is_object($value) && method_exists($value, '__toString'));
  930. });
  931. if (count($strings) < 2 && count(array_filter([$retrieved, $value], 'is_object')) == 1) {
  932. return in_array($operator, ['!=', '<>', '!==']);
  933. }
  934. switch ($operator) {
  935. default:
  936. case '=':
  937. case '==':
  938. return $retrieved == $value;
  939. case '!=':
  940. case '<>':
  941. return $retrieved != $value;
  942. case '<':
  943. return $retrieved < $value;
  944. case '>':
  945. return $retrieved > $value;
  946. case '<=':
  947. return $retrieved <= $value;
  948. case '>=':
  949. return $retrieved >= $value;
  950. case '===':
  951. return $retrieved === $value;
  952. case '!==':
  953. return $retrieved !== $value;
  954. case '<=>':
  955. return $retrieved <=> $value;
  956. }
  957. };
  958. }
  959. /**
  960. * Determine if the given value is callable, but not a string.
  961. *
  962. * @param mixed $value
  963. */
  964. protected function useAsCallable($value): bool
  965. {
  966. return ! is_string($value) && is_callable($value);
  967. }
  968. /**
  969. * Get a value retrieving callback.
  970. *
  971. * @param null|callable|string $value
  972. */
  973. protected function valueRetriever($value): callable
  974. {
  975. if ($this->useAsCallable($value)) {
  976. return $value;
  977. }
  978. return fn ($item) => data_get($item, $value);
  979. }
  980. /**
  981. * Make a function to check an item's equality.
  982. *
  983. * @param mixed $value
  984. * @return Closure(mixed): bool
  985. */
  986. protected function equality($value)
  987. {
  988. return fn ($item) => $item === $value;
  989. }
  990. /**
  991. * Make a function using another function, by negating its result.
  992. *
  993. * @return Closure
  994. */
  995. protected function negate(Closure $callback)
  996. {
  997. return fn (...$params) => ! $callback(...$params);
  998. }
  999. /**
  1000. * Make a function that returns what's passed to it.
  1001. *
  1002. * @return Closure(TValue): TValue
  1003. */
  1004. protected function identity()
  1005. {
  1006. return fn ($value) => $value;
  1007. }
  1008. }