<?php
/**
* @author Thomas HERISSON (contact@scaledev.fr)
* @copyright 2021 - ScaleDEV SAS, 12 RUE CHARLES MORET, 10120 ST ANDRE LES VERGERS
* @license commercial
*/
declare(strict_types=1);
namespace Bluue\StatisticsBundle\EventSubscriber;
use App\Event\ConfigureMenuEvent;
use Bluue\StatisticsBundle\Event\MenuStatisticPageEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ConfigureMenuSubscriber implements EventSubscriberInterface
{
/**
* @var TranslatorInterface
*/
private TranslatorInterface $tr;
/**
* @var RequestStack
*/
protected RequestStack $requestStack;
/**
* @var Security
*/
private Security $security;
/**
* @var EventDispatcherInterface
*/
private EventDispatcherInterface $eventDispatcher;
/**
* @param RequestStack $requestStack
* @param TranslatorInterface $tr
* @param Security $security
* @param EventDispatcherInterface $eventDispatcher
*/
public function __construct(
RequestStack $requestStack,
TranslatorInterface $tr,
Security $security,
EventDispatcherInterface $eventDispatcher
) {
$this->requestStack = $requestStack;
$this->tr = $tr;
$this->security = $security;
$this->eventDispatcher = $eventDispatcher;
}
/**
* @return array
*/
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__STATISTICS__READ_ONLY')) {
return;
}
$menu = $event->getMenu();
$currentRoute = $this->requestStack->getCurrentRequest()->attributes->get('_route');
$statisticDisplayEvent = new MenuStatisticPageEvent([]);
$this->eventDispatcher->dispatch(
$statisticDisplayEvent,
MenuStatisticPageEvent::NAME
);
$firstPage = current($statisticDisplayEvent->getPages());
if ($firstPage && array_key_exists('id', $firstPage)) {
$menu->addChild(
'StatisticsMenu',
[
'route' => $firstPage['id'],
'label' => $this->tr->trans('Statistics', [], 'StatisticsBundle')
]
)->setExtra('icon', 'fas fa-chart-pie');
if (str_contains($currentRoute, '__statistics')) {
$menu['StatisticsMenu']->setCurrent(true);
}
}
}
}