Collection.php 45KB

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