src/Security/Voter/MessageVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\User;
  4. use App\Entity\Message;
  5. use Symfony\Component\Security\Core\Security;
  6. use Symfony\Component\Security\Core\User\UserInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  9. class MessageVoter extends Voter
  10. {
  11.     public const EDIT 'MESSAGE_EDIT';
  12.     public const DELETE 'MESSAGE_DELETE';
  13.     private $security;
  14.     public function __construct(Security $security)
  15.     {
  16.         $this->security $security;
  17.     }
  18.     protected function supports(string $attribute$message): bool
  19.     {
  20.         // replace with your own logic
  21.         // https://symfony.com/doc/current/security/voters.html
  22.         return in_array($attribute, [self::EDITself::DELETE])
  23.             && $message instanceof \App\Entity\Message;
  24.     }
  25.     protected function voteOnAttribute(string $attribute$messageTokenInterface $token): bool
  26.     {
  27.         $user $token->getUser();
  28.         // if the user is anonymous, do not grant access
  29.         if (!$user instanceof UserInterface) return false;
  30.         
  31.         // ... (check conditions and return true to grant permission) ...
  32.         switch ($attribute) {
  33.             case self::EDIT:
  34.                 // logic to determine if the user can EDIT
  35.                 // return true or false
  36.                 return $this->canEdit($message,$user);
  37.                 break;
  38.             case self::DELETE:
  39.                 // logic to determine if the user can DELETE
  40.                 // return true or false
  41.                 return $this->canDelete($message,$user);
  42.                 break;
  43.         }
  44.         return false;
  45.     }
  46.     private function canEdit(Message $messageUser $user){
  47.         return $user === $message->getUser();
  48.     }
  49.     private function canDelete(Message $messageUser $user){
  50.         return $user === $message->getUser() || $this->security->isGranted('ROLE_MODO');
  51.     }
  52. }