Completed
Push — master ( 1fe708...6360f1 )
by Arnaud
16s queued 12s
created

MenuFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 10
ccs 0
cts 5
cp 0
rs 10
cc 1
nc 1
nop 4
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace LAG\AdminBundle\Menu\Factory;
6
7
use Knp\Menu\FactoryInterface;
8
use Knp\Menu\ItemInterface;
9
use LAG\AdminBundle\Event\Events\MenuEvent;
10
use LAG\AdminBundle\Event\MenuEvents;
11
use LAG\AdminBundle\Factory\Configuration\ConfigurationFactoryInterface;
12
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
13
14
class MenuFactory implements MenuFactoryInterface
15
{
16
    private EventDispatcherInterface $eventDispatcher;
17
    private FactoryInterface $factory;
18
    private ConfigurationFactoryInterface $configurationFactory;
19
    private MenuItemFactoryInterface $menuItemFactory;
20
21
    public function __construct(
22
        EventDispatcherInterface $eventDispatcher,
23
        FactoryInterface $factory,
24
        ConfigurationFactoryInterface $configurationFactory,
25
        MenuItemFactoryInterface $menuItemFactory
26
    ) {
27
        $this->eventDispatcher = $eventDispatcher;
28
        $this->factory = $factory;
29
        $this->configurationFactory = $configurationFactory;
30
        $this->menuItemFactory = $menuItemFactory;
31
    }
32
33
    public function create(string $name, array $options = []): ItemInterface
34
    {
35
        $menuConfiguration = $this->configurationFactory->createMenuConfiguration($name, $options)->toArray();
36
        $menu = $this->factory->createItem('root', [
37
            'attributes' => $menuConfiguration['attributes'],
38
            'extras' => $menuConfiguration['extras'],
39
        ]);
40
        $event = new MenuEvent($name, $menu);
41
        $this->eventDispatcher->dispatch($event, MenuEvents::MENU_CREATE);
42
        $this->eventDispatcher->dispatch($event, sprintf(MenuEvents::MENU_CREATE_SPECIFIC, $name));
43
        $children = $menuConfiguration['children'] ?? [];
44
45
        foreach ($children as $child) {
46
            $child = $this->menuItemFactory->create($child['text'], $child);
47
            $menu->addChild($child);
48
        }
49
        $this->eventDispatcher->dispatch($event, MenuEvents::MENU_CREATED);
50
        $this->eventDispatcher->dispatch($event, sprintf(MenuEvents::MENU_CREATED_SPECIFIC, $name));
51
52
        return $menu;
53
    }
54
}
55