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

MenuItemFactory::create()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

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