Passed
Push — master ( 823aee...b9b37f )
by Alec
13:15 queued 12s
created

FrameCollection   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 17
c 4
b 0
f 0
dl 0
loc 51
rs 10
wmc 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
A lastIndex() 0 6 1
A __construct() 0 4 1
A assertFrame() 0 8 2
A get() 0 3 1
A initialize() 0 6 2
1
<?php
2
3
declare(strict_types=1);
4
// 20.03.23
5
namespace AlecRabbit\Spinner\Core;
6
7
use AlecRabbit\Spinner\Contract\IFrame;
8
use AlecRabbit\Spinner\Contract\IFrameCollection;
9
use AlecRabbit\Spinner\Exception\DomainException;
10
use AlecRabbit\Spinner\Exception\InvalidArgumentException;
11
use ArrayObject;
12
use Traversable;
13
14
/**
15
 * @template T of IFrame
16
 * @extends ArrayObject<int,T>
17
 * @implements IFrameCollection<T>
18
 */
19
final class FrameCollection extends ArrayObject implements IFrameCollection
20
{
21
    /**
22
     * @throws InvalidArgumentException
23
     */
24
    public function __construct(Traversable $frames)
25
    {
26
        parent::__construct();
27
        $this->initialize($frames);
28
    }
29
30
    /**
31
     * @throws InvalidArgumentException
32
     */
33
    private function initialize(Traversable $frames): void
34
    {
35
        /** @var T $frame */
36
        foreach ($frames as $frame) {
37
            self::assertFrame($frame);
38
            $this->append($frame);
39
        }
40
    }
41
42
    /**
43
     * @throws InvalidArgumentException
44
     */
45
    private static function assertFrame(mixed $frame): void
46
    {
47
        if (!$frame instanceof IFrame) {
48
            throw new InvalidArgumentException(
49
                sprintf(
50
                    'Frame must be instance of %s. %s given.', // TODO: clarify message
51
                    IFrame::class,
52
                    get_debug_type($frame)
53
                )
54
            );
55
        }
56
    }
57
58
    /** @inheritdoc */
59
    public function lastIndex(): int
60
    {
61
        return
0 ignored issues
show
Bug Best Practice introduced by
The expression return array_key_last($t...rayCopy()) ?? ThrowNode could return the type string which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
62
            array_key_last($this->getArrayCopy())
63
            ??
64
            throw new DomainException('Empty collection.');
65
    }
66
67
    public function get(int $index): IFrame
68
    {
69
        return $this->offsetGet($index);
70
    }
71
}
72