Passed
Pull Request — master (#259)
by Arnaud
08:22
created

MenuItemFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 3
1
<?php
2
3
namespace LAG\AdminBundle\Menu\Factory;
4
5
use Knp\Menu\FactoryInterface;
6
use Knp\Menu\ItemInterface;
7
use LAG\AdminBundle\Admin\Helper\AdminHelperInterface;
8
use Symfony\Component\HttpFoundation\RequestStack;
9
use Symfony\Component\PropertyAccess\PropertyAccess;
10
use function Symfony\Component\String\u;
11
12
class MenuItemFactory implements MenuItemFactoryInterface
13
{
14
    private FactoryInterface $factory;
15
    private AdminHelperInterface $adminHelper;
16
    private RequestStack $requestStack;
17
18
    public function __construct(FactoryInterface $factory, AdminHelperInterface $adminHelper, RequestStack $requestStack)
19
    {
20
        $this->factory = $factory;
21
        $this->adminHelper = $adminHelper;
22
        $this->requestStack = $requestStack;
23
    }
24
25
    public function create(string $name, array $options = []): ItemInterface
26
    {
27
        $options = $this->mapRouteParameters($options);
28
        $child = $this->factory->createItem($name, $options);
29
30
        if (isset($options['icon'])) {
31
            $child->setExtra('icon', $options['icon']);
32
        }
33
        $currentRoute = $this->requestStack->getMasterRequest()->get('_route');
34
35
        if (isset($options['route']) && $options['route'] === $currentRoute) {
36
            $class = $child->setCurrent(true)->getAttribute('class');
37
            $child->setAttribute('class', $class.' current');
38
        }
39
40
        return $child;
41
    }
42
43
    private function mapRouteParameters(array $options): array
44
    {
45
        if (!$this->adminHelper->hasAdmin()) {
46
            return $options;
47
        }
48
        $admin = $this->adminHelper->getAdmin();
49
        $propertyAccessor = PropertyAccess::createPropertyAccessor();
50
51
        if (empty($options['routeParameters'])) {
52
            return $options;
53
        }
54
55
        foreach ($options['routeParameters'] as $name => $value) {
56
            if ($value === null && !u($name)->startsWith('_')) {
57
                $value = $propertyAccessor->getValue($admin->getData(), $name);
58
            }
59
            $options['routeParameters'][$name] = $value;
60
        }
61
62
        return $options;
63
    }
64
}
65