<?php
namespace App\Security;
use App\Entity\Category;
use App\Entity\Security\AppUser;
use App\Repository\CategoryRepository;
use App\Repository\MalletteFileRepository;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class CategoryVoter extends Voter
{
public const VIEW = 'view';
public const VIEW_MENU = 'view_menu';
/** @var null|array<Category> */
private ?array $cachedAccessibleCategories = null;
private ?int $cachedUserId = null;
private ?string $cachedAttribute = null;
public function __construct(
private MalletteFileRepository $malletteFileRepository,
private CategoryRepository $categoryRepository,
) {
}
protected function supports(string $attribute, $subject): bool
{
if (!in_array($attribute, [self::VIEW, self::VIEW_MENU])) {
return false;
}
return $subject instanceof Category;
}
/**
* @param Category $subject
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
if (!in_array($attribute, [self::VIEW, self::VIEW_MENU])) {
return false;
}
$user = $token->getUser();
// the user must be logged in; if not, deny access
if (!$user instanceof AppUser) {
return false;
}
$this->loadAccessibleCategoriesIfNeeded($user, $attribute);
if (in_array($subject, $this->cachedAccessibleCategories, true)) {
return true;
}
return $attribute === self::VIEW_MENU && $this->hasAccessibleChild($subject);
}
private function loadAccessibleCategoriesIfNeeded(AppUser $user, string $attribute): void
{
if ($this->cachedUserId === $user->getId()
&& $this->cachedAttribute === $attribute
&& $this->cachedAccessibleCategories !== null) {
return;
}
$groups = $user->getClient()->getGroups();
$malletteFiles = $this->malletteFileRepository->findByCategoryAccess($groups, $user);
$this->cachedAccessibleCategories = $this->categoryRepository->findByGroupsAndMalletteFiles($groups, $malletteFiles);
$this->cachedUserId = $user->getId();
$this->cachedAttribute = $attribute;
}
private function hasAccessibleChild(Category $category): bool
{
foreach ($category->getSubCategories() as $subCategory) {
if (in_array($subCategory, $this->cachedAccessibleCategories, true)) {
return true;
}
if ($this->hasAccessibleDescendant($subCategory)) {
return true;
}
}
return false;
}
private function hasAccessibleDescendant(Category $category): bool
{
foreach ($category->getSubCategories() as $subCategory) {
if (in_array($subCategory, $this->cachedAccessibleCategories, true)) {
return true;
}
if ($this->hasAccessibleDescendant($subCategory)) {
return true;
}
}
return false;
}
}