<?php
/**
* @author Léo BANNHOLTZER (contact@scaledev.fr)
* @copyright 2021 - ScaleDEV SAS, 12 RUE CHARLES MORET, 10120 ST ANDRE LES VERGERS
* @license commercial
*/
declare(strict_types=1);
namespace Bluue\CustomersBundle\EventSubscriber;
use App\Event\ConfigureMenuEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\Translation\TranslatorInterface;
class ConfigureMenuSubscriber implements EventSubscriberInterface
{
/**
* @var TranslatorInterface
*/
private TranslatorInterface $tr;
/**
* @var RequestStack
*/
protected RequestStack $requestStack;
/**
* @var Security
*/
private Security $security;
/**
* @param RequestStack $requestStack
* @param TranslatorInterface $tr
* @param Security $security
*/
public function __construct(
RequestStack $requestStack,
TranslatorInterface $tr,
Security $security
) {
$this->requestStack = $requestStack;
$this->tr = $tr;
$this->security = $security;
}
/**
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return [
ConfigureMenuEvent::NAME => 'onLoad'
];
}
/**
* @param ConfigureMenuEvent $event
* @return void
*/
public function onLoad(ConfigureMenuEvent $event): void
{
if (!$this->security->isGranted('ROLE__CUSTOMERS__READ_ONLY')) {
return;
}
$menu = $event->getMenu();
$menuCustomersChilds = [
[
'key' => 'customers',
'label' => $this->tr->trans('Customers', [], 'CustomersBundle'),
'route' => 'customers_bundle__customer_list',
'matchPath' => [
'bundles/customers-bundle/view',
'bundles/customers-bundle/edit',
'bundles/customers-bundle/new'
]
]
];
$currentPath = $this->requestStack->getCurrentRequest()->getPathInfo();
$currentRoute = $this->requestStack->getCurrentRequest()->attributes->get('_route');
$parentName = $this->tr->trans('Customers', [], 'CustomersBundle');
$menu->addChild('CustomersMenu')
->setLabel($parentName)
->setExtra('icon', 'fas fa-users');
foreach ($menuCustomersChilds as $menuCustomersChild) {
$current = false;
if ($menuCustomersChild['route'] == $currentRoute) {
$current = true;
} else {
foreach ($menuCustomersChild['matchPath'] as $matchPath) {
if (strpos($currentPath, $matchPath) !== false) {
$current = true;
}
}
}
$menu['CustomersMenu']->addChild(
$menuCustomersChild['key'],
[
'route' => $menuCustomersChild['route'],
'label' => $menuCustomersChild['label'],
'current' => $current
]
);
}
}
}