Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.00% covered (success)
90.00%
9 / 10
80.00% covered (warning)
80.00%
4 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
TraitArrayAccess
90.00% covered (success)
90.00%
9 / 10
80.00% covered (warning)
80.00%
4 / 5
10.10
0.00% covered (danger)
0.00%
0 / 1
 offsetExists
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
3
 offsetGet
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 offsetSet
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 offsetUnset
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 validOffset
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
1<?php
2
3// ╔════════════════════════════════════════════════════════════╗
4// ║ MIT Licence (#Expat) - https://opensource.org/licenses/MIT ║
5// ║ Copyright 2026 Frederic Poeydomenge <dyno@phexium.com>     ║
6// ╚════════════════════════════════════════════════════════════╝
7
8declare(strict_types=1);
9
10namespace Phexium\Domain\Collection\Trait;
11
12use InvalidArgumentException;
13
14trait TraitArrayAccess
15{
16    public function offsetExists(mixed $offset): bool
17    {
18        return (is_int($offset) || is_string($offset)) && array_key_exists($offset, $this->collection);
19    }
20
21    public function offsetGet(mixed $offset): mixed
22    {
23        return $this->collection[self::validOffset($offset)] ?? null;
24    }
25
26    public function offsetSet(mixed $offset, mixed $value): void
27    {
28        if ($offset === null) {
29            $this->collection[] = $value;
30
31            return;
32        }
33
34        $this->collection[self::validOffset($offset)] = $value;
35    }
36
37    public function offsetUnset(mixed $offset): void
38    {
39        unset($this->collection[self::validOffset($offset)]);
40    }
41
42    private static function validOffset(mixed $offset): int|string
43    {
44        if (!is_int($offset) && !is_string($offset)) {
45            throw new InvalidArgumentException('Collection offset must be an int or a string.');
46        }
47
48        return $offset;
49    }
50}