Skip to content

Commit

Permalink
Implemented array access
Browse files Browse the repository at this point in the history
  • Loading branch information
loevgaard committed Jun 17, 2024
1 parent d399959 commit c7ed4a0
Showing 1 changed file with 37 additions and 2 deletions.
39 changes: 37 additions & 2 deletions src/DataTransferObject/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
* @template T of AbstractDataTransferObject
*
* @implements \IteratorAggregate<int, T>
* @implements \ArrayAccess<int, T>
*/
final class Collection implements \IteratorAggregate, \Countable
final class Collection implements \IteratorAggregate, \Countable, \ArrayAccess
{
/** @var list<T> */
private array $items;
Expand All @@ -28,7 +29,7 @@ public function empty(): bool
}

/**
* @return \ArrayIterator<int<0, max>, T>
* @return \ArrayIterator<int<0,max>, T>
*/
public function getIterator(): \ArrayIterator
{
Expand Down Expand Up @@ -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');
}
}

0 comments on commit c7ed4a0

Please sign in to comment.