MenuBuilder::setParentActive()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 12
rs 9.4285
cc 3
eloc 7
nc 4
nop 1
1
<?php
2
3
namespace Alpixel\Bundle\AdminMenuBundle\Menu;
4
5
use Knp\Menu\FactoryInterface;
6
use Knp\Menu\MenuItem;
7
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
8
use Symfony\Bundle\FrameworkBundle\Routing\Router;
9
use Symfony\Component\HttpFoundation\RequestStack;
10
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
11
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
12
use Symfony\Component\Yaml\Parser;
13
14
/**
15
 * @author Benjamin HUBERT <[email protected]>
16
 */
17
class MenuBuilder
18
{
19
    use \Symfony\Component\DependencyInjection\ContainerAwareTrait;
20
21
    /**
22
     * @var \Symfony\Bundle\FrameworkBundle\Routing\Router
23
     */
24
    protected $router;
25
    /**
26
     * @var \Knp\Menu\FactoryInterface
27
     */
28
    protected $factory;
29
    /**
30
     * @var \Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser
31
     */
32
    protected $parser;
33
    /**
34
     * @var mixed|null
35
     */
36
    protected $user;
37
38
    /**
39
     * @var \Symfony\Component\Security\Core\Authorization\AuthorizationChecker
40
     */
41
    protected $authorizationChecker;
42
43
    /**
44
     * MenuBuilder constructor.
45
     * @param \Knp\Menu\FactoryInterface $factory
46
     * @param \Symfony\Bundle\FrameworkBundle\Routing\Router $router
47
     * @param \Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser $parser
48
     * @param \Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage $tokenStorage
49
     * @param \Symfony\Component\Security\Core\Authorization\AuthorizationChecker $authorizationChecker
50
     */
51
    public function __construct(
52
        FactoryInterface $factory,
53
        Router $router,
54
        ControllerNameParser $parser,
55
        TokenStorage $tokenStorage,
56
        AuthorizationChecker $authorizationChecker
57
    ) {
58
        $this->factory = $factory;
59
        $this->router = $router;
60
        $this->parser = $parser;
61
        $this->user = ($tokenStorage->getToken() !== null) ? $tokenStorage->getToken()->getUser() : null;
62
        $this->authorizationChecker = $authorizationChecker;
63
    }
64
65
    /**
66
     * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
67
     * @param $kernelRootDir
68
     * @return \Knp\Menu\ItemInterface
69
     */
70
    public function createMainMenu(RequestStack $requestStack, $kernelRootDir)
71
    {
72
        $routes = $this->router->getRouteCollection();
73
74
        foreach ($routes as $route) {
75
            $this->convertController($route);
76
        }
77
78
        $request = $requestStack->getCurrentRequest();
79
80
        $menu = $this->factory->createItem(
81
            'root',
82
            [
83
                'childrenAttributes' => [
84
                    'class' => 'sidebar-menu',
85
                ],
86
            ]
87
        );
88
89
        $parser = new Parser();
90
        $items = $parser->parse(file_get_contents($kernelRootDir.'/config/menu.yml'));
91
        $currentUri = $request->getRequestUri();
92
93
        foreach ($items['mainMenu'] as $label => $item) {
94
            $this->addItem($currentUri, $menu, $label, $item);
95
        }
96
97
        return $menu;
98
    }
99
100
    /**
101
     * @param \Symfony\Component\Routing\Route $route
102
     */
103
    protected function convertController(\Symfony\Component\Routing\Route $route)
104
    {
105
        if ($route->hasDefault('_controller')) {
106
            try {
107
                $route->setDefault('_controller', $this->parser->build($route->getDefault('_controller')));
108
            } catch (\InvalidArgumentException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
109
            }
110
        }
111
    }
112
113
    /**
114
     * @param $currentUri
115
     * @param $menu
116
     * @param $label
117
     * @param $item
118
     * @param null $parent
119
     * @return mixed
120
     */
121
    protected function addItem($currentUri, &$menu, $label, $item, $parent = null)
122
    {
123
124
        if (isset($item['visibility'])) {
125
            if (isset($item['visibility']['exclude'])) {
126
                $permission = $this->authorizationChecker->isGranted($item['visibility']['exclude'], $this->user);
127
                if ($permission === true) {
128
                    return;
129
                }
130
            } else {
131
                $permission = $this->authorizationChecker->isGranted($item['visibility'], $this->user);
132
                if ($permission === false) {
133
                    return;
134
                }
135
            }
136
        }
137
138
        if (isset($item['type']) && isset($item['route']) && $item['type'] == 'route') {
139
            $params = [
140
                'route' => $item['route'],
141
            ];
142
            if (isset($item['parameters'])) {
143
                $params['routeParameters'] = $item['parameters'];
144
            }
145
        } else {
146
            $params = [];
147
        }
148
149
        if ($parent !== null) {
150
            $menuItem = $parent->addChild($label, $params);
0 ignored issues
show
Bug introduced by
The method addChild cannot be called on $parent (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
151
        } else {
152
            $menuItem = $menu->addChild($label, $params);
153
        }
154
155
        if (isset($item['badge']) && isset($this->container)) {
156
            $badge = $this->container->get($item['badge']);
157
            $menuItem->setAttribute('badge', $badge->getCount());
158
        }
159
160
        if (!isset($item['route'])) {
161
            $menuItem->setUri('#');
162
        }
163
164
        if (!empty($item['icon'])) {
165
            $menuItem->setAttribute('icon', $item['icon']);
166
        }
167
168
        if (isset($item['children'])) {
169
            $menuItem->setAttribute('class', 'treeview');
170
            foreach ($item['children'] as $childLabel => $childItem) {
171
                $child = $this->addItem($currentUri, $menu, $childLabel, $childItem, $menuItem);
172
                if ($child !== null && $currentUri == $child->getUri()) {
173
                    $this->setParentActive($child->getParent());
174
                }
175
            }
176
        }
177
178
        return $menuItem;
179
    }
180
181
    /**
182
     * @param \Knp\Menu\MenuItem $item
183
     */
184
    public function setParentActive(MenuItem $item)
185
    {
186
        $cssClass = $item->getAttribute('class');
187
        if (empty($cssClass)) {
188
            $cssClass = '';
189
        }
190
191
        $item->setAttribute('class', $cssClass.' active');
192
        if ($item->getParent() !== null) {
193
            $this->setParentActive($item->getParent());
0 ignored issues
show
Compatibility introduced by
$item->getParent() of type object<Knp\Menu\ItemInterface> is not a sub-type of object<Knp\Menu\MenuItem>. It seems like you assume a concrete implementation of the interface Knp\Menu\ItemInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
194
        }
195
    }
196
}
197