AbstractCollection::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.4746

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 12
ccs 5
cts 8
cp 0.625
crap 3.4746
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpCfdi\SatCatalogosPopulate;
6
7
use ArrayIterator;
8
use Countable;
9
use InvalidArgumentException;
10
use IteratorAggregate;
11
12
/**
13
 * @template T
14
 * @implements IteratorAggregate<T>
15
 */
16
abstract class AbstractCollection implements Countable, IteratorAggregate
17
{
18
    /** @var array<int, T> */
19
    private array $members;
20
21
    private readonly int $count;
22
23
    abstract public function isValidMember(mixed $member): bool;
24
25
    /**
26
     * @param array<T> $members
27
     */
28 15
    public function __construct(array $members)
29
    {
30 15
        foreach ($members as $index => $member) {
31 15
            if (! $this->isValidMember($member)) {
32
                throw new InvalidArgumentException(
33
                    "The member $index contains an object that is not valid for this collection"
34
                );
35
            }
36
        }
37
38 15
        $this->members = array_values($members);
39 15
        $this->count = count($members);
0 ignored issues
show
Bug introduced by
The property count is declared read-only in PhpCfdi\SatCatalogosPopulate\AbstractCollection.
Loading history...
40
    }
41
42
    /**
43
     * @param T $member
44
     */
45 1
    public function contains($member): bool
46
    {
47 1
        return in_array($member, $this->members, true);
48
    }
49
50
    /**
51
     * @return T
52
     */
53
    public function get(int $index)
54
    {
55
        if (! isset($this->members[$index])) {
56
            throw new InvalidArgumentException(
57
                "The collection does not contain the index $index"
58
            );
59
        }
60
61
        return $this->members[$index];
62
    }
63
64
    /**
65
     * @return array<int, T>
66
     */
67 10
    public function all(): array
68
    {
69 10
        return $this->members;
70
    }
71
72
    /** @return T */
73
    public function first()
74
    {
75
        return $this->members[0];
76
    }
77
78
    /** @return T */
79
    public function last()
80
    {
81
        return $this->members[$this->count - 1];
82
    }
83
84
    /** @return ArrayIterator<int, T> */
85 6
    public function getIterator(): ArrayIterator
86
    {
87 6
        return new ArrayIterator($this->members);
88
    }
89
90 14
    public function count(): int
91
    {
92 14
        return $this->count;
93
    }
94
}
95