| 1: | <?php declare(strict_types=1); |
| 2: | |
| 3: | namespace Salient\Collection; |
| 4: | |
| 5: | use Salient\Contract\Core\Arrayable; |
| 6: | |
| 7: | /** |
| 8: | * @api |
| 9: | * |
| 10: | * @template TKey of array-key |
| 11: | * @template TValue |
| 12: | */ |
| 13: | trait ReadOnlyCollectionTrait |
| 14: | { |
| 15: | /** @use HasItems<TKey,TValue> */ |
| 16: | use HasItems; |
| 17: | |
| 18: | /** |
| 19: | * @inheritDoc |
| 20: | */ |
| 21: | public function __construct($items = []) |
| 22: | { |
| 23: | $this->Items = $this->getItemsArray($items); |
| 24: | } |
| 25: | |
| 26: | /** |
| 27: | * @param Arrayable<TKey,TValue>|iterable<TKey,TValue> $items |
| 28: | * @return array<TKey,TValue> |
| 29: | */ |
| 30: | private function getItemsArray($items): array |
| 31: | { |
| 32: | $items = $this->getItems($items); |
| 33: | return is_array($items) |
| 34: | ? $items |
| 35: | : iterator_to_array($items); |
| 36: | } |
| 37: | |
| 38: | /** |
| 39: | * @param Arrayable<TKey,TValue>|iterable<TKey,TValue> $items |
| 40: | * @return iterable<TKey,TValue> |
| 41: | */ |
| 42: | private function getItems($items): iterable |
| 43: | { |
| 44: | if ($items instanceof self) { |
| 45: | /** @var array<TKey,TValue> */ |
| 46: | $items = $items->Items; |
| 47: | } elseif ($items instanceof Arrayable) { |
| 48: | /** @var array<TKey,TValue> */ |
| 49: | $items = $items->toArray(); |
| 50: | } |
| 51: | return $this->filterItems($items); |
| 52: | } |
| 53: | |
| 54: | /** |
| 55: | * Override to normalise items applied to the collection |
| 56: | * |
| 57: | * @param iterable<TKey,TValue> $items |
| 58: | * @return iterable<TKey,TValue> |
| 59: | */ |
| 60: | private function filterItems(iterable $items): iterable |
| 61: | { |
| 62: | return $items; |
| 63: | } |
| 64: | } |
| 65: |