<?php
namespace App\Security\Voter;
use App\Entity\User;
use App\Entity\Message;
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;
class MessageVoter extends Voter
{
public const EDIT = 'MESSAGE_EDIT';
public const DELETE = 'MESSAGE_DELETE';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports(string $attribute, $message): bool
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [self::EDIT, self::DELETE])
&& $message instanceof \App\Entity\Message;
}
protected function voteOnAttribute(string $attribute, $message, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) return false;
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case self::EDIT:
// logic to determine if the user can EDIT
// return true or false
return $this->canEdit($message,$user);
break;
case self::DELETE:
// logic to determine if the user can DELETE
// return true or false
return $this->canDelete($message,$user);
break;
}
return false;
}
private function canEdit(Message $message, User $user){
return $user === $message->getUser();
}
private function canDelete(Message $message, User $user){
return $user === $message->getUser() || $this->security->isGranted('ROLE_MODO');
}
}