<?php
/*
* Created on Fri Dec 02 2022
*
* DAVID-OLIVIER DESCOMBES
*
* @licence
* You may not sell, sub-license, rent or lease any portion of the Software or Documentation to anyone.
*
* Copyright (c) 2022 dodarchitecte.com (https://dodarchitecte.com)
*
* Developed by developpeur-informatique.ma (https://www.developpeur-informatique.ma)
*/
namespace App\Security\Voter;
use App\Entity\Chat\Conversation;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
class ConversationVoter extends Voter
{
public const EDIT = 'POST_EDIT';
public const VIEW = 'CONVERSATION_VIEW';
public function __construct(private Security $security)
{
}
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])
&& $subject instanceof Conversation;
}
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;
}
// ... (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 true;
break;
case self::VIEW:
return $this->canView($user, $subject);
break;
}
return false;
}
//check if the user can view the specific conversation
private function canView($user, $subject): bool
{
$isGestionnaire = count($user->getRoles()) > 1;
if ($isGestionnaire) {
// for admin , chef , secritary
foreach ($subject->getParticipations() as $participation) {
if ($participation->getUser()->getId() == $user->getId()) {
return true;
continue;
}
}
return false;
} else {
// for the client
return $subject->getProject()->getEnterprise() == $user->getEnterprise();
}
}
}