Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
ArrayIteratorNonNegIntKeys
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
3 / 3
6
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 validateKey
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 offsetSet
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3namespace pvc\struct\collection;
4
5use ArrayIterator;
6use pvc\struct\collection\err\InvalidKeyException;
7
8/**
9 * @template ElementType
10 * @extends ArrayIterator<non-negative-int, ElementType>
11 */
12class ArrayIteratorNonNegIntKeys extends ArrayIterator
13{
14    /**
15     * @param  array<non-negative-int, ElementType>  $array
16     */
17    public function __construct(array $array = [])
18    {
19        foreach ($array as $key => $element) {
20            $this->validateKey($key);
21        }
22        parent::__construct($array);
23    }
24
25    /**
26     * validateKey encapsulates the logic that all keys must be non-negative integers
27     *
28     * @param  array-key  $key
29     *
30     * @return void
31     */
32    protected function validateKey(int|string $key)
33    {
34        if (!is_int($key) || $key < 0) {
35            throw new InvalidKeyException($key);
36        }
37    }
38
39    /**
40     * @param  array-key  $key
41     * @param  mixed  $value
42     *
43     * @return void
44     * @throws InvalidKeyException
45     * even though this library is written with phpstan as a tool, this puts
46     * a hard exception in  place if the key is invalid
47     */
48    public function offsetSet(mixed $key, mixed $value): void
49    {
50        $this->validateKey($key);
51        parent::offsetSet($key, $value);
52    }
53}