<?php
namespace App\Security\Voter;
use App\Repository\CorrespondanceBotCentreRepository;
use App\Services\Metier\CallBotConversationHistoriqueSM;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class CallBotConversationVoter extends Voter
{
private CallBotConversationHistoriqueSM $callBotSM;
private CorrespondanceBotCentreRepository $correspondanceBotCentreRepository;
const CAN_SEE_CONVERSATION = "can_see_conversation";
const ACTIONS = [
self::CAN_SEE_CONVERSATION
];
public function __construct(
CallBotConversationHistoriqueSM $callBotSM,
CorrespondanceBotCentreRepository $correspondanceBotCentreRepository
)
{
$this->callBotSM = $callBotSM;
$this->correspondanceBotCentreRepository = $correspondanceBotCentreRepository;
}
/**
* Elle vérifie si l’attribut demandé (can_see_conversation) est géré par ce voter
*
* @param string $attribute An attribute
* @param mixed $subject The subject to vote on
*
* @return bool true if this Voter supports the given attribute, false otherwise
*/
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, self::ACTIONS);
}
/**
* Il récupère l'utilisateur à partir du TokenInterface.
* Il vérifie l'action demandée et appelle la méthode correspondante (canSeeConversation).
* En cas d'erreur, il lève une exception logique.
*
* @param string $attribute The attribute to be checked.
* @param mixed $subject The subject to vote on.
* @param TokenInterface $token The security token containing the user credentials.
*
* @return bool True if the user is granted permission for the attribute, false otherwise.
*
* @throws \LogicException If the attribute is not supported by this voter.
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
switch ($attribute) {
case self::CAN_SEE_CONVERSATION:
return $this->canSeeConversation($user, $subject);
default:
throw new \LogicException('This code should not be reached!');
}
}
/**
* Vérifie si l'utilisateur peut acc der une conversation
*
* @param UserInterface|null $user
*
* @return bool
*/
private function canSeeConversation(?UserInterface $user): bool
{
if (!$user instanceof UserInterface) {
return false;
}
$dossiers = $this->callBotSM->getConnectedUserDossiers($user);
$correspondence = $this->correspondanceBotCentreRepository->findOneBy(['dossier' => $dossiers[0]['cle']]);
return !empty($correspondence);
}
}