diff --git a/src/DataTransferObject/Collection.php b/src/DataTransferObject/Collection.php index 6e53121..01232df 100644 --- a/src/DataTransferObject/Collection.php +++ b/src/DataTransferObject/Collection.php @@ -8,8 +8,9 @@ * @template T of AbstractDataTransferObject * * @implements \IteratorAggregate + * @implements \ArrayAccess */ -final class Collection implements \IteratorAggregate, \Countable +final class Collection implements \IteratorAggregate, \Countable, \ArrayAccess { /** @var list */ private array $items; @@ -28,7 +29,7 @@ public function empty(): bool } /** - * @return \ArrayIterator, T> + * @return \ArrayIterator, T> */ public function getIterator(): \ArrayIterator { @@ -57,4 +58,38 @@ public function toArray(): array { return $this->items; } + + /** + * @psalm-assert-if-true T $this->items[$offset] + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->items[$offset]); + } + + /** + * @return T + */ + public function offsetGet(mixed $offset): object + { + if (!is_int($offset)) { + throw new \InvalidArgumentException('The offset must be an integer'); + } + + if (!$this->offsetExists($offset)) { + throw new \OutOfBoundsException(sprintf('The offset %s does not exist', $offset)); + } + + return $this->items[$offset]; + } + + public function offsetSet(mixed $offset, mixed $value): void + { + throw new \BadMethodCallException('You cannot set an item in a collection'); + } + + public function offsetUnset(mixed $offset): void + { + throw new \BadMethodCallException('You cannot unset an item in a collection'); + } }