<?php
namespace App\EventSubscriber;
use App\Entity\Security\AppUser;
use App\Repository\CategoryRepository;
use App\Repository\GroupRepository;
use App\Repository\MalletteFileRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Security;
use Twig\Environment;
class AccessibleCategoriesSubscriber implements EventSubscriberInterface
{
public function __construct(
private Environment $twig,
private Security $security,
private MalletteFileRepository $malletteFileRepository,
private CategoryRepository $categoryRepository,
private GroupRepository $groupRepository,
) {
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
public function onKernelController(ControllerEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
$user = $this->security->getUser();
if (!$user instanceof AppUser) {
return;
}
$groups = $this->groupRepository->findByClient($user->getClient());
$allAccessibleFiles = $this->malletteFileRepository->findByCategoryAccess($groups, $user);
$accessibleCategories = $this->categoryRepository->findByGroupsAndMalletteFiles($groups, $allAccessibleFiles);
$categoryFileCounts = [];
foreach ($allAccessibleFiles as $file) {
foreach ($file->getCategories() as $category) {
$categoryId = $category->getId();
if (!isset($categoryFileCounts[$categoryId])) {
$categoryFileCounts[$categoryId] = 0;
}
$categoryFileCounts[$categoryId]++;
}
}
$this->twig->addGlobal('accessibleCategories', $accessibleCategories);
$this->twig->addGlobal('categoryFileCounts', $categoryFileCounts);
}
}