Passed
Pull Request — main (#8)
by Anatoly
11:42
created

ObjectCollection::all()   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
dl 0
loc 3
c 1
b 0
f 0
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php declare(strict_types=1);
2
3
/**
4
 * It's free open-source software released under the MIT License.
5
 *
6
 * @author Anatoly Fenric <[email protected]>
7
 * @copyright Copyright (c) 2021, Anatoly Fenric
8
 * @license https://github.com/sunrise-php/hydrator/blob/master/LICENSE
9
 * @link https://github.com/sunrise-php/hydrator
10
 */
11
12
namespace Sunrise\Hydrator;
13
14
/**
15
 * Import classes
16
 */
17
use InvalidArgumentException;
18
use RuntimeException;
19
20
/**
21
 * Import functions
22
 */
23
use function sprintf;
24
25
/**
26
 * ObjectCollection
27
 */
28
abstract class ObjectCollection implements ObjectCollectionInterface
29
{
30
31
    /**
32
     * The type of objects in the collection
33
     *
34
     * @var class-string<T>
35
     *
36
     * @template T
37
     */
38
    public const T = null;
39
40
    /**
41
     * The collection objects
42
     *
43
     * @var array<int|string, T>
44
     */
45
    private $objects = [];
46
47
    /**
48
     * {@inheritdoc}
49
     *
50
     * @throws RuntimeException
51
     *         If the called class doesn't contain the T constant.
52
     */
53 3
    final public function getItemClassName() : string
54
    {
55 3
        if (null === static::T) {
0 ignored issues
show
introduced by
The condition null === static::T is always true.
Loading history...
56
            throw new RuntimeException(sprintf(
57
                'The <%s> collection must contain the <T> constant.',
58
                static::class
59
            ));
60
        }
61
62 3
        return static::T;
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 3
    final public function add($key, object $object) : void
69
    {
70 3
        $type = $this->getItemClassName();
71
72 3
        if (!($object instanceof $type)) {
73 1
            throw new InvalidArgumentException(sprintf(
74 1
                'The <%s> collection must contain the <%s> objects only.',
75 1
                static::class,
76 1
                $type
77
            ));
78
        }
79
80 2
        $this->objects[$key] = $object;
81 2
    }
82
83
    /**
84
     * {@inheritdoc}
85
     */
86 1
    final public function get($key) : ?object
87
    {
88 1
        return $this->objects[$key] ?? null;
89
    }
90
91
    /**
92
     * {@inheritdoc}
93
     */
94 1
    final public function all() : array
95
    {
96 1
        return $this->objects;
97
    }
98
}
99