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

AbstractCollection::contains()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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