Completed
Branch master (eb975e)
by Basarab
06:37 queued 04:53
created

ItemList::getDimensionCount()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
4
namespace Hexogen\KDTree;
5
6
use Hexogen\KDTree\Exception\ValidationException;
7
8
class ItemList
9
{
10
    private $dimensions;
11
    private $items;
12
    private $ids;
13
    private $lastId;
14
15
    /**
16
     * ItemList constructor.
17
     * @param int $dimensions
18
     * @throws ValidationException
19
     */
20 27
    public function __construct(int $dimensions)
21
    {
22 27
        if ($dimensions <= 0) {
23 3
            throw new ValidationException('$dimensions should be bigger than 0');
24
        }
25
26 27
        $this->lastId = 0;
27 27
        $this->dimensions = $dimensions;
28 27
        $this->items = [];
29 27
        $this->ids = [];
30 27
    }
31
32
    /**
33
     * Add or replace an item in the item list
34
     *
35
     * @param ItemInterface $item
36
     */
37 18
    public function addItem(ItemInterface $item)
38
    {
39 18
        $this->validateItem($item);
40 15
        $id = $item->getId();
41
42 15
        if (isset($this->ids[$id])) {
43 3
            $index = $this->ids[$id];
44 3
            $this->items[$index] = $item;
45
        } else {
46 15
            $this->items[] = $item;
47 15
            $this->ids[$id] = $this->lastId++;
48
        }
49 15
    }
50
51
    /**
52
     * @return ItemInterface[]
53
     */
54 45
    public function getItems(): array
55
    {
56 45
        return $this->items;
57
    }
58
59
    /**
60
     * @return int number of dimensions in item
61
     */
62 45
    public function getDimensionCount(): int
63
    {
64 45
        return $this->dimensions;
65
    }
66
67
    /**
68
     * @param ItemInterface $item
69
     * @throws ValidationException
70
     */
71 18
    private function validateItem(ItemInterface $item)
72
    {
73 18
        if ($item->getDimensionsCount() !== $this->dimensions) {
74 3
            throw new ValidationException('$dValues number dimensions should be equal to ' . $this->dimensions);
75
        }
76 15
    }
77
}
78