Collection::createImmutableCollection()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Antidot\EventSource\Domain\Model\Collection;
6
7
use Countable;
8
use Generator;
9
use InvalidArgumentException;
10
use IteratorAggregate;
11
use RuntimeException;
12
13
abstract class Collection implements Countable, IteratorAggregate
14
{
15
    protected string $fqcn = '';
16
    protected array $items = [];
17
    protected bool $locked = false;
18
19
    final protected function __construct(array $items = [], bool $locked = true)
20
    {
21
        $this->setFqcn();
22
        /** @var object $item */
23
        foreach ($items as $item) {
24
            $this->addItem($item);
25
        }
26
        $this->locked = $locked;
27
    }
28
29
    /**
30
     * @param array $items
31
     * @return static
32
     */
33
    public static function createImmutableCollection(array $items)
34
    {
35
        return new static($items);
36
    }
37
38
    /**
39
     * @param array $items
40
     * @return static
41
     */
42
    public static function createMutableCollection(array $items = [])
43
    {
44
        return new static($items, false);
45
    }
46
47
    /**
48
     * @return static
49
     */
50
    public static function createEmptyCollection()
51
    {
52
        return new static([], false);
53
    }
54
55
    public function addItem(object $item): void
56
    {
57
        $this->assertIsNotLocked();
58
        $this->assertInstanceOf($item);
59
        $this->items[] = $item;
60
    }
61
62
    public function lock(): void
63
    {
64
        $this->locked = true;
65
    }
66
67
    public function count(): int
68
    {
69
        return count($this->items);
70
    }
71
72
    private function assertInstanceOf(object $object): void
73
    {
74
        if (false === $object instanceof $this->fqcn) {
75
            throw new InvalidArgumentException(sprintf(
76
                'Collection item must be instance of %s class. An instance of %s given.',
77
                get_class($object),
78
                $this->fqcn
79
            ));
80
        }
81
    }
82
83
    private function assertIsNotLocked(): void
84
    {
85
        if (true === $this->locked) {
86
            throw new RuntimeException('Cannot add new items to locked collection.');
87
        }
88
    }
89
90
    public function getIterator(): Generator
91
    {
92
        yield from $this->items;
93
    }
94
95
96
    abstract protected function setFqcn(): void;
97
}
98