<?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';
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;
}
$groups = $user->getClient()->getGroups();
$malletteFiles = $this->malletteFileRepository->findByCategoryAccess($groups, $user, $subject);
$categories = $this->categoryRepository->findByGroupsAndMalletteFiles($groups, $malletteFiles);
if (in_array($subject, $categories)) {
return true;
}
if ($attribute == self::VIEW_MENU) {
// Allow to show in the menu any category for which we can access a child
foreach ($subject->getSubCategories() as $subCategory) {
if ($this->voteOnAttribute($attribute, $subCategory, $token)) {
return true;
}
}
}
return false;
}
}