<?php
namespace App\Security;
use App\Entity\MalletteFile;
use App\Entity\Security\AppUser;
use App\Repository\MalletteFileRepository;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class MalletteFileVoter extends Voter
{
public const VIEW = 'view';
public const DOWNLOAD = 'download';
public function __construct(
private MalletteFileRepository $malletteFileRepository,
) {
}
protected function supports(string $attribute, $subject): bool
{
if (!in_array($attribute, [self::VIEW, self::DOWNLOAD])) {
return false;
}
return $subject instanceof MalletteFile;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
if (!in_array($attribute, [self::VIEW, self::DOWNLOAD])) {
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);
return in_array($subject, $malletteFiles);
}
}