<?php
namespace App\Security\Voter;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
class FormVoter extends Voter
{
public const EDIT = 'EDIT_FORM';
public const VIEW = 'VIEW_FORM';
public function __construct(public Security $security, private ParameterBagInterface $serviceParams)
{
}
protected function supports(string $attribute, $subject): bool
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [self::EDIT, self::VIEW]);
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
$accessGranted = false;
// ... (check conditions and return true to grant permission) ...
$accessGranted = match($attribute){
self::VIEW => $this->security->isGranted($this->serviceParams->get('role_admin')) or $this->security->isGranted($this->serviceParams->get('role_comercial')),
self::EDIT => $this->security->isGranted($this->serviceParams->get('role_admin')) or $this->security->isGranted($this->serviceParams->get('role_comercial'))
};
return $accessGranted;
}
}