EnumeratesValues.php 33 KB

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