<?php
namespace App\Security\Voter;
use App\Entity\Conversation;
use App\Entity\User;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class ConversationVoter extends Voter
{
// these strings are just invented: you can use anything
const CREATE = 'create';
const VIEW = 'view';
const EDIT = 'edit';
const DELETE = 'delete';
private $em;
private $userRepository;
/**
* ConversationVoter constructor.
* @param EntityManagerInterface $entityManager
* @param UserRepository $userRepository
*/
public function __construct(EntityManagerInterface $entityManager,UserRepository $userRepository){
$this->em = $entityManager;
$this->userRepository = $userRepository;
}
protected function supports($attribute, $subject)
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [self::CREATE,self::VIEW,self::EDIT,self::DELETE])
&& $subject instanceof Conversation;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
/** @var User $user */
$user = $this->userRepository->findOneBy(['email' => $user->getUsername()]);
/** @var Conversation $conversation */
$conversation = $subject;
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case self::VIEW:
// logic to determine if the user can VIEW
return $this->canView($conversation,$user);
break;
}
return false;
}
private function canView(Conversation $conversation, User $user)
{
/** @var Conversation $conversationUser*/
foreach ($user->getConversations() as $conversationUser){
if($conversationUser->getId() === $conversation->getId())
return true;
}
return false;
}
}