Completed
Push — master ( 02b993...3405ac )
by Mikołaj
02:38
created

MenuItemCollection::sort()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Rudolf\Component\Helpers\Navigation;
4
5
class MenuItemCollection
6
{
7
    /**
8
     * @var MenuItem[]
9
     */
10
    private $collection;
11
12
    /**
13
     * @param MenuItem $item
14
     * @return int|null
15
     */
16
    public function add(MenuItem $item)
17
    {
18
        if (null == $item->getId()) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $item->getId() of type integer|null against null; this is ambiguous if the integer can be zero. Consider using a strict comparison === instead.
Loading history...
19
            $item->setId(count($this->collection) + 1);
20
        }
21
22
        $this->collection[] = $item;
23
24
        return $item->getId();
25
    }
26
27
    /**
28
     * @return MenuItem[]
29
     */
30
    public function getAll()
31
    {
32
        return $this->collection;
33
    }
34
35
    /**
36
     * Get menu items by type.
37
     *
38
     * @param string $type
39
     *
40
     * @return array of MenuItem
41
     */
42
    public function getByType($type)
43
    {
44
        if (empty($this->collection)) {
45
            return null;
46
        }
47
        $items = [];
48
49
        foreach ($this->collection as $key => $item) {
50
            if ($type === $item->getType()) {
51
                $items[] = $item;
52
            }
53
        }
54
        usort($items, [$this, 'sort']);
55
56
        return $items;
57
    }
58
59
    /**
60
     * @param MenuItem $a
61
     * @param MenuItem $b
62
     * @return int
63
     */
64
    private function sort($a, $b)
65
    {
66
        return strcmp($a->getPosition(), $b->getPosition());
67
    }
68
}
69