LeftMenuBuilder   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 22
c 1
b 0
f 0
dl 0
loc 42
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A createMenu() 0 32 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace LAG\AdminBundle\Bridge\KnpMenu\Builder;
6
7
use Knp\Menu\FactoryInterface;
8
use Knp\Menu\ItemInterface;
9
use LAG\AdminBundle\Event\Events\MenuCreatedEvent;
10
use LAG\AdminBundle\Event\Events\MenuCreateEvent;
11
use LAG\AdminBundle\Event\MenuEvents;
12
use LAG\AdminBundle\Metadata\Index;
13
use LAG\AdminBundle\Resource\Registry\ResourceRegistryInterface;
14
use LAG\AdminBundle\Routing\Route\RouteNameGeneratorInterface;
15
use Symfony\Component\String\Inflector\EnglishInflector;
16
17
use function Symfony\Component\String\u;
18
19
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
20
21
class LeftMenuBuilder
22
{
23
    public function __construct(
24
        private FactoryInterface $factory,
25
        private ResourceRegistryInterface $resourceRegistry,
26
        private RouteNameGeneratorInterface $routeNameGenerator,
27
        private EventDispatcherInterface $eventDispatcher,
28
    ) {
29
    }
30
31
    public function createMenu(array $options = []): ItemInterface
32
    {
33
        $menu = $this->factory->createItem('root', $options);
34
        $this->eventDispatcher->dispatch($event = new MenuCreateEvent($menu), MenuEvents::MENU_CREATE);
35
        $this->eventDispatcher->dispatch($event = new MenuCreateEvent($event->getMenu()), sprintf(
36
            MenuEvents::NAMED_EVENT_PATTERN,
37
            'left',
38
        ));
39
        $menu = $event->getMenu();
40
41
        foreach ($this->resourceRegistry->all() as $resource) {
42
            foreach ($resource->getOperations() as $operation) {
43
                if (!$operation instanceof Index) {
44
                    continue;
45
                }
46
                $inflector = new EnglishInflector();
47
                $label = $inflector->pluralize(u($resource->getName())->snake()->toString())[0];
48
                $menu
49
                    ->addChild($label, [
50
                        'route' => $this->routeNameGenerator->generateRouteName($resource, $operation),
51
                    ])
52
                    ->setLabel('lag_admin.menu.'.$label)
53
                ;
54
            }
55
        }
56
        $this->eventDispatcher->dispatch(new MenuCreatedEvent($menu), MenuEvents::MENU_CREATED);
57
        $this->eventDispatcher->dispatch(new MenuCreatedEvent($menu), sprintf(
58
            MenuEvents::NAMED_EVENT_PATTERN,
59
            'left',
60
        ));
61
62
        return $menu;
63
    }
64
}
65