TypedCollection::offsetGet()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
3
namespace JimmyOak\Collection;
4
5
use JimmyOak\Exception\Collection\NotValidObjectTypeException;
6
use JimmyOak\Exception\Collection\UndefinedOffsetException;
7
use Traversable;
8
9
class TypedCollection extends Collection
10
{
11
    /**
12
     * @var string
13
     */
14
    private $objectType;
15
16
    /**
17
     * @param string $objectType
18
     */
19
    public function __construct($objectType)
20
    {
21
        $this->setObjectType($objectType);
22
    }
23
24
    /**
25
     * @return string
26
     */
27
    public function getObjectType()
28
    {
29
        return $this->objectType;
30
    }
31
32
    /**
33
     * @param string $objectType
34
     *
35
     * @return $this
36
     */
37
    protected function setObjectType($objectType)
38
    {
39
        $this->objectType = $objectType;
40
41
        return $this;
42
    }
43
44
    public function offsetSet($offset, $value)
45
    {
46
        $this->guardAgainstNotValidObjectType($value);
47
48
        parent::offsetSet($offset, $value);
49
    }
50
51
    public function offsetGet($offset)
52
    {
53
        if (!isset($this->collection[$offset])) {
54
            throw new UndefinedOffsetException();
55
        }
56
57
        return parent::offsetGet($offset);
58
    }
59
60
    /**
61
     * @param $value
62
     *
63
     * @throws NotValidObjectTypeException
64
     */
65
    private function guardAgainstNotValidObjectType($value)
66
    {
67
        if (!$value instanceof $this->objectType) {
68
            throw new NotValidObjectTypeException();
69
        }
70
    }
71
}
72