src/Security/Voter/ConversationVoter.php line 14

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Conversation;
  4. use App\Entity\User;
  5. use App\Repository\UserRepository;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. use Symfony\Component\Security\Core\User\UserInterface;
  10. class ConversationVoter extends Voter
  11. {
  12.     // these strings are just invented: you can use anything
  13.     const CREATE 'create';
  14.     const VIEW 'view';
  15.     const EDIT 'edit';
  16.     const DELETE 'delete';
  17.     private $em;
  18.     private $userRepository;
  19.     /**
  20.      * ConversationVoter constructor.
  21.      * @param EntityManagerInterface $entityManager
  22.      * @param UserRepository $userRepository
  23.      */
  24.     public function __construct(EntityManagerInterface $entityManager,UserRepository $userRepository){
  25.         $this->em $entityManager;
  26.         $this->userRepository $userRepository;
  27.     }
  28.     protected function supports($attribute$subject)
  29.     {
  30.         // replace with your own logic
  31.         // https://symfony.com/doc/current/security/voters.html
  32.         return in_array($attribute, [self::CREATE,self::VIEW,self::EDIT,self::DELETE])
  33.             && $subject instanceof Conversation;
  34.     }
  35.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  36.     {
  37.         $user $token->getUser();
  38.         // if the user is anonymous, do not grant access
  39.         if (!$user instanceof UserInterface) {
  40.             return false;
  41.         }
  42.         /** @var User $user */
  43.         $user $this->userRepository->findOneBy(['email' => $user->getUsername()]);
  44.         /** @var Conversation $conversation */
  45.         $conversation $subject;
  46.         // ... (check conditions and return true to grant permission) ...
  47.         switch ($attribute) {
  48.             case self::VIEW:
  49.                 // logic to determine if the user can VIEW
  50.                 return $this->canView($conversation,$user);
  51.                 break;
  52.         }
  53.         return false;
  54.     }
  55.     private function canView(Conversation $conversationUser $user)
  56.     {
  57.         /** @var Conversation $conversationUser*/
  58.         foreach ($user->getConversations() as $conversationUser){
  59.             if($conversationUser->getId() === $conversation->getId())
  60.                 return true;
  61.         }
  62.         return false;
  63.     }
  64. }