|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Nuxtifyts\PhpDto\Support; |
| 4 | + |
| 5 | +/** |
| 6 | + * @template TKey of array-key |
| 7 | + * @template TValue of mixed |
| 8 | + */ |
| 9 | +class Collection |
| 10 | +{ |
| 11 | + /** @var array<TKey, TValue> */ |
| 12 | + protected array $items = []; |
| 13 | + |
| 14 | + /** |
| 15 | + * @param array<TKey, TValue> $items |
| 16 | + */ |
| 17 | + public function __construct(array $items = []) |
| 18 | + { |
| 19 | + $this->items = $items; |
| 20 | + } |
| 21 | + |
| 22 | + /** |
| 23 | + * @param TValue $item |
| 24 | + * |
| 25 | + * @return self<TKey, TValue> |
| 26 | + */ |
| 27 | + public function push(mixed $item): self |
| 28 | + { |
| 29 | + $this->items[] = $item; |
| 30 | + return $this; |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * @param TKey $key |
| 35 | + * @param TValue $value |
| 36 | + * |
| 37 | + * @return self<TKey, TValue> |
| 38 | + */ |
| 39 | + public function put(mixed $key, mixed $value): self |
| 40 | + { |
| 41 | + $this->items[$key] = $value; |
| 42 | + return $this; |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * @param ?callable(TValue $item): bool $callable |
| 47 | + * |
| 48 | + * @return ?TValue |
| 49 | + */ |
| 50 | + public function first(?callable $callable = null): mixed |
| 51 | + { |
| 52 | + return is_null($callable) |
| 53 | + ? reset($this->items) ?: null |
| 54 | + : array_find($this->items, $callable); |
| 55 | + } |
| 56 | + |
| 57 | + public function isNotEmpty(): bool |
| 58 | + { |
| 59 | + return !empty($this->items); |
| 60 | + } |
| 61 | + |
| 62 | + public function isEmpty(): bool |
| 63 | + { |
| 64 | + return !$this->isNotEmpty(); |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * @param callable(TValue $item): bool $callable |
| 69 | + */ |
| 70 | + public function every(callable $callable): bool |
| 71 | + { |
| 72 | + return array_all($this->items, $callable); |
| 73 | + } |
| 74 | + |
| 75 | + /** |
| 76 | + * @param callable(TValue $item): bool $callable |
| 77 | + */ |
| 78 | + public function some(callable $callable): bool |
| 79 | + { |
| 80 | + return array_any($this->items, $callable); |
| 81 | + } |
| 82 | +} |
0 commit comments