From c7ed4a06c600182b6272e41ba91f1fedb8dc0bd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joachim=20L=C3=B8vgaard?= Date: Mon, 17 Jun 2024 11:54:10 +0200 Subject: [PATCH] Implemented array access --- src/DataTransferObject/Collection.php | 39 +++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) 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'); + } }