Passed
Push — master ( b97c32...e7e450 )
by Carlos C
10:36 queued 12s
created

AbstractCollection::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.2098

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 12
ccs 5
cts 7
cp 0.7143
rs 10
cc 3
nc 3
nop 1
crap 3.2098
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 int $count;
22
23
    abstract public function isValidMember(mixed $member): bool;
24
25
    /**
26
     * @param array<T> $members
27
     */
28 10
    public function __construct(array $members)
29
    {
30 10
        foreach ($members as $index => $member) {
31 10
            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 10
        $this->members = array_values($members);
39 10
        $this->count = count($members);
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 5
    public function all(): array
68
    {
69 5
        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 9
    public function count(): int
91
    {
92 9
        return $this->count;
93
    }
94
}
95