Collection.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. <?php
  2. declare(strict_types=1);
  3. namespace Yansongda\Supports;
  4. use ArrayAccess;
  5. use ArrayIterator;
  6. use Countable;
  7. use InvalidArgumentException;
  8. use IteratorAggregate;
  9. use JsonSerializable;
  10. use Traversable;
  11. use Yansongda\Supports\Traits\Accessable;
  12. use Yansongda\Supports\Traits\Arrayable;
  13. use Yansongda\Supports\Traits\Serializable;
  14. class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
  15. {
  16. use Serializable;
  17. use Accessable;
  18. use Arrayable;
  19. protected array $items = [];
  20. public function __construct(mixed $items = [])
  21. {
  22. foreach ($this->getArrayableItems($items) as $key => $value) {
  23. $this->set($key, $value);
  24. }
  25. }
  26. public static function wrap(mixed $value): self
  27. {
  28. return $value instanceof self ? new static($value) : new static(Arr::wrap($value));
  29. }
  30. public static function wrapJson(string $json): self
  31. {
  32. return new static(Arr::wrapJson($json));
  33. }
  34. public static function wrapXml(string $xml): self
  35. {
  36. return new static(Arr::wrapXml($xml));
  37. }
  38. public static function wrapQuery(string $query, bool $raw = false, bool $spaceToPlus = false): self
  39. {
  40. return new static(Arr::wrapQuery($query, $raw, $spaceToPlus));
  41. }
  42. public static function unwrap(array|Collection $value): array
  43. {
  44. return $value instanceof self ? $value->all() : $value;
  45. }
  46. public function all(): array
  47. {
  48. return $this->items;
  49. }
  50. public function only(array $keys): array
  51. {
  52. $return = [];
  53. foreach ($keys as $key) {
  54. $value = $this->get($key);
  55. if (!is_null($value)) {
  56. $return[$key] = $value;
  57. }
  58. }
  59. return $return;
  60. }
  61. public function except(mixed $keys): self
  62. {
  63. $keys = is_array($keys) ? $keys : func_get_args();
  64. return new static(Arr::except($this->items, $keys));
  65. }
  66. public function filter(?callable $callback = null): self
  67. {
  68. if ($callback) {
  69. return new static(Arr::where($this->items, $callback));
  70. }
  71. return new static(array_filter($this->items));
  72. }
  73. public function merge(mixed $items): self
  74. {
  75. return new static(array_merge($this->items, $this->getArrayableItems($items)));
  76. }
  77. public function has(int|string $key): bool
  78. {
  79. return !is_null(Arr::get($this->items, $key));
  80. }
  81. public function first(): mixed
  82. {
  83. return reset($this->items);
  84. }
  85. public function last(): mixed
  86. {
  87. $end = end($this->items);
  88. reset($this->items);
  89. return $end;
  90. }
  91. public function add(null|int|string $key, mixed $value): void
  92. {
  93. Arr::set($this->items, $key, $value);
  94. }
  95. public function set(null|int|string $key, mixed $value): void
  96. {
  97. Arr::set($this->items, $key, $value);
  98. }
  99. public function get(null|int|string $key = null, mixed $default = null): mixed
  100. {
  101. return Arr::get($this->items, $key, $default);
  102. }
  103. public function forget(int|string $key): void
  104. {
  105. Arr::forget($this->items, $key);
  106. }
  107. public function flatten(float|int $depth = INF): self
  108. {
  109. return new static(Arr::flatten($this->items, $depth));
  110. }
  111. public function map(callable $callback): self
  112. {
  113. $keys = array_keys($this->items);
  114. $items = array_map($callback, $this->items, $keys);
  115. return new static(array_combine($keys, $items));
  116. }
  117. public function pop(): mixed
  118. {
  119. return array_pop($this->items);
  120. }
  121. public function prepend(mixed $value, mixed $key = null): self
  122. {
  123. $this->items = Arr::prepend($this->items, $value, $key);
  124. return $this;
  125. }
  126. public function push(mixed $value): self
  127. {
  128. $this->offsetSet(null, $value);
  129. return $this;
  130. }
  131. public function pull(mixed $key, mixed $default = null): mixed
  132. {
  133. return Arr::pull($this->items, $key, $default);
  134. }
  135. public function put(mixed $key, mixed $value): self
  136. {
  137. $this->offsetSet($key, $value);
  138. return $this;
  139. }
  140. /**
  141. * @throws InvalidArgumentException
  142. */
  143. public function random(?int $number = null): self
  144. {
  145. return new static(Arr::random($this->items, $number ?? 1));
  146. }
  147. public function reduce(callable $callback, mixed $initial = null): mixed
  148. {
  149. return array_reduce($this->items, $callback, $initial);
  150. }
  151. public function values(): self
  152. {
  153. return new static(array_values($this->items));
  154. }
  155. public function every(callable|string $key): bool
  156. {
  157. $callback = $this->valueRetriever($key);
  158. foreach ($this->items as $k => $v) {
  159. if (!$callback($v, $k)) {
  160. return false;
  161. }
  162. }
  163. return true;
  164. }
  165. public function chunk(int $size): self
  166. {
  167. if ($size <= 0) {
  168. return new static();
  169. }
  170. $chunks = [];
  171. foreach (array_chunk($this->items, $size, true) as $chunk) {
  172. $chunks[] = new static($chunk);
  173. }
  174. return new static($chunks);
  175. }
  176. public function sort(?callable $callback = null): self
  177. {
  178. $items = $this->items;
  179. $callback ? uasort($items, $callback) : asort($items);
  180. return new static($items);
  181. }
  182. public function sortBy(callable|string $callback, int $options = SORT_REGULAR, bool $descending = false): self
  183. {
  184. $results = [];
  185. $callback = $this->valueRetriever($callback);
  186. // First we will loop through the items and get the comparator from a callback
  187. // function which we were given. Then, we will sort the returned values
  188. // and grab the corresponding values for the sorted keys from this array.
  189. foreach ($this->items as $key => $value) {
  190. $results[$key] = $callback($value, $key);
  191. }
  192. $descending ? arsort($results, $options) : asort($results, $options);
  193. // Once we have sorted all the keys in the array, we will loop through them
  194. // and grab the corresponding model, so we can set the underlying items list
  195. // to the sorted version. Then we'll just return the collection instance.
  196. foreach (array_keys($results) as $key) {
  197. $results[$key] = $this->items[$key];
  198. }
  199. return new static($results);
  200. }
  201. public function sortByDesc(callable|string $callback, int $options = SORT_REGULAR): self
  202. {
  203. return $this->sortBy($callback, $options, true);
  204. }
  205. public function sortKeys(int $options = SORT_REGULAR, bool $descending = false): self
  206. {
  207. $items = $this->items;
  208. $descending ? krsort($items, $options) : ksort($items, $options);
  209. return new static($items);
  210. }
  211. public function sortKeysDesc(int $options = SORT_REGULAR): self
  212. {
  213. return $this->sortKeys($options, true);
  214. }
  215. public function query(int $encodingType = PHP_QUERY_RFC1738): string
  216. {
  217. return Arr::query($this->all(), $encodingType);
  218. }
  219. public function toString(string $separator = '&'): string
  220. {
  221. return Arr::toString($this->all(), $separator);
  222. }
  223. public function toArray(): array
  224. {
  225. return $this->all();
  226. }
  227. public function toXml(): string
  228. {
  229. $xml = '<xml>';
  230. foreach ($this->all() as $key => $val) {
  231. $xml .= is_numeric($val) ? '<'.$key.'>'.$val.'</'.$key.'>' :
  232. '<'.$key.'><![CDATA['.$val.']]></'.$key.'>';
  233. }
  234. $xml .= '</xml>';
  235. return $xml;
  236. }
  237. public function getIterator(): Traversable
  238. {
  239. return new ArrayIterator($this->items);
  240. }
  241. public function count(): int
  242. {
  243. return count($this->items);
  244. }
  245. public function isEmpty(): bool
  246. {
  247. return empty($this->items);
  248. }
  249. public function isNotEmpty(): bool
  250. {
  251. return !$this->isEmpty();
  252. }
  253. public function offsetUnset(mixed $offset): void
  254. {
  255. if ($this->offsetExists($offset)) {
  256. $this->forget($offset);
  257. }
  258. }
  259. protected function useAsCallable(mixed $value): bool
  260. {
  261. return !is_string($value) && is_callable($value);
  262. }
  263. protected function valueRetriever(mixed $value): callable
  264. {
  265. if ($this->useAsCallable($value)) {
  266. return $value;
  267. }
  268. return function ($item) use ($value) {
  269. return data_get($item, $value);
  270. };
  271. }
  272. protected function getArrayableItems(mixed $items): array
  273. {
  274. if (is_array($items)) {
  275. return $items;
  276. }
  277. if ($items instanceof self) {
  278. return $items->all();
  279. }
  280. if ($items instanceof JsonSerializable) {
  281. return $items->jsonSerialize();
  282. }
  283. return (array) $items;
  284. }
  285. }