Passed
Pull Request — master (#6)
by
unknown
02:09
created

OrderedContainer::getItems()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Everlution\Navigation\Container;
6
7
use Everlution\Navigation\Container\ContainerInterface;
8
use Everlution\Navigation\Item\ItemInterface;
9
use Everlution\Navigation\Item\SortableInterface;
10
11
/**
12
 * Class OrderedContainer.
13
 *
14
 * @author Ivan Barlog <[email protected]>
15
 */
16
class OrderedContainer implements ContainerInterface
17
{
18
    /** @var ContainerInterface */
19
    private $container;
20
    /** @var ItemInterface[] */
21
    private $items;
22
23
    public function __construct(ContainerInterface $container)
24
    {
25
        $this->container = $container;
26
    }
27
28
    /**
29
     * @return ItemInterface[]
30
     */
31
    public function getItems(): array
32
    {
33
        if (empty($this->items)) {
34
            $items = $this->container->getItems();
35
36
            $sortable = [];
37
            foreach ($items as $key => $item) {
38
                if ($item instanceof SortableInterface) {
39
                    $sortable[$key] = $item;
40
                    unset($items[$key]);
41
                }
42
            }
43
44
            uasort($sortable, [$this, 'ascending']);
45
            $this->items = array_merge($sortable, $items);
46
        }
47
48
        return $this->items;
49
    }
50
51
    public function get(string $name): ItemInterface
52
    {
53
        return $this->items[$name];
54
    }
55
56
    private function ascending(SortableInterface $first, SortableInterface $second)
57
    {
58
        return $first->getOrder() <=> $second->getOrder();
59
    }
60
}
61