AbstractCollection::add()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1
Metric Value
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Jobles\Core;
4
5
abstract class AbstractCollection implements \IteratorAggregate, \Countable
6
{
7
8
    /**
9
     * @var mixed
10
     */
11
    protected $class;
12
13
    /**
14
     * @var array
15
     */
16
    private $data = [];
17
18
    /**
19
     * @var int
20
     */
21
    private $size = 0;
22
23
    /**
24
     * @param $object
25
     */
26 23
    public function add($object)
27
    {
28 23
        $this->validateObjectInstance($object);
29 21
        $this->data[] = $object;
30 21
        $this->size++;
31 21
    }
32
33
    /**
34
     * @param int $position
35
     *
36
     * @return mixed
37
     * @throws \LengthException
38
     */
39 8
    public function pick(int $position)
40
    {
41 8
        if (isset($this->data[$position])) {
42 5
            return $this->data[$position];
43
        }
44
45 3
        throw new \LengthException('Invalid index position: ' . $position);
46
    }
47
48
    /**
49
     * @return int
50
     */
51 6
    public function count() : int
52
    {
53 6
        return $this->size;
54
    }
55
56
    /**
57
     * @return Iterator
58
     */
59 3
    public function getIterator() : Iterator
60
    {
61 3
        return new Iterator($this);
62
    }
63
64
    /**
65
     * @param mixed $object
66
     */
67 23
    private function validateObjectInstance($object)
68
    {
69 23
        if (!$object instanceof $this->class) {
70 2
            throw new \InvalidArgumentException('Object is not an instance of ' . $this->class);
71
        }
72 21
    }
73
}
74