Passed
Pull Request — master (#99)
by
unknown
02:46
created

RepresentationCollection::getIterator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php declare(strict_types=1);
2
3
namespace hiqdev\php\billing\product\invoice;
4
5
use hiqdev\php\billing\product\price\PriceTypeDefinition;
6
use hiqdev\php\billing\product\trait\HasLock;
7
use hiqdev\php\billing\product\trait\HasLockInterface;
8
use IteratorAggregate;
9
use Traversable;
10
11
/**
12
 * @template T of PriceTypeDefinition
13
 * @implements IteratorAggregate<int, RepresentationInterface>
14
 */
15
class RepresentationCollection implements IteratorAggregate, HasLockInterface
16
{
17
    use HasLock;
18
19
    private array $representations = [];
20
21
    private RepresentationUniquenessGuard $uniquenessGuard;
22
23
    public function __construct(private readonly PriceTypeDefinition $priceTypeDefinition)
24
    {
25
        $this->uniquenessGuard = new RepresentationUniquenessGuard();
26
    }
27
28
    /**
29
     * @return Traversable<int, RepresentationInterface>
30
     */
31
    public function getIterator(): Traversable
32
    {
33
        return new \ArrayIterator($this->representations);
34
    }
35
36
    public function attach(RepresentationInterface $representation): self
37
    {
38
        $this->ensureNotLocked();
39
40
        $representation->setType($this->priceTypeDefinition->type());
41
42
        $this->uniquenessGuard->ensureUnique($representation);
43
44
        $this->representations[] = $representation;
45
46
        return $this;
47
    }
48
49
    /**
50
     * @psalm-return T
51
     */
52
    public function end(): PriceTypeDefinition
53
    {
54
        return $this->priceTypeDefinition;
55
    }
56
57
    public function filterByType(string $className): array
58
    {
59
        return array_filter($this->representations, fn($r) => $r instanceof $className);
60
    }
61
}
62