Passed
Push — master ( 20e747...679572 )
by Ivan
01:59
created

NavigationItemFactory   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 68
c 0
b 0
f 0
wmc 9
lcom 1
cbo 2
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A addHydrator() 0 6 1
A build() 0 8 2
A create() 0 13 3
A flatten() 0 13 3
getData() 0 1 ?
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace Everlution\Navigation\Factory;
6
7
use Everlution\Navigation\Item;
8
use Everlution\Navigation\NavigationItem;
9
use Everlution\Navigation\Factory\Build\UnsupportedItemClassException;
10
use Everlution\Navigation\Factory\Build\Config;
11
12
/**
13
 * Class NavigationItemFactory.
14
 * @author Ivan Barlog <[email protected]>
15
 */
16
abstract class NavigationItemFactory implements ItemFactory
17
{
18
    const OPTIONS_ITEMS = 'items';
19
20
    /** @var Config[] */
21
    private $hydrators = [];
22
23
    public function addHydrator(Config $config)
24
    {
25
        $this->hydrators[] = $config;
26
27
        return $this;
28
    }
29
30
    /**
31
     * @param NavigationItem $navigation
32
     */
33
    public function build(NavigationItem &$navigation)
34
    {
35
        $data = $this->getData($navigation);
36
        foreach ($data[self::OPTIONS_ITEMS] as $item) {
37
            $item = $this->create($item);
38
            $navigation->addChild($item);
39
        }
40
    }
41
42
    /**
43
     * @param array $item
44
     * @return Item
45
     */
46
    public function create(array $item): Item
47
    {
48
        $instance = null;
49
        foreach ($this->hydrators as $hydrator) {
50
            try {
51
                $instance = $hydrator->toObject($item, $this);
52
            } catch (UnsupportedItemClassException $exception) {
53
                continue;
54
            }
55
        }
56
57
        return $instance;
58
    }
59
60
    /**
61
     * @param NavigationItem $child
62
     * @return array
63
     */
64
    public function flatten(NavigationItem $child): array
65
    {
66
        $items = [];
67
        foreach ($this->hydrators as $hydrator) {
68
            try {
69
                $items[] = $hydrator->toArray($child, $this);
70
            } catch (UnsupportedItemClassException $exception) {
71
                continue;
72
            }
73
        }
74
75
        return $items;
76
    }
77
78
    /**
79
     * @param NavigationItem $navigation
80
     * @return array
81
     */
82
    abstract protected function getData(NavigationItem &$navigation): array;
83
}
84