<?php
namespace App\Infrastructure\Security\Voter;
use App\Database\Domain\Entity\Sessions\ToastSessionLink;
use App\Database\Domain\Entity\User\User;
use App\Database\Domain\Repository\CollaboratedSessionRepository;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ToastSessionLinkVoter extends Voter
{
public const ACCESS = 'toast_session_link.access';
public const ACCESS_WITH_COLLABORATORS = 'toast_session_link.access_with_collaborators';
private CollaboratedSessionRepository $collaboratedSessionRepository;
public function __construct(CollaboratedSessionRepository $collaboratedSessionRepository)
{
$this->collaboratedSessionRepository = $collaboratedSessionRepository;
}
protected function supports(string $attribute, $subject): bool
{
return $attribute === self::ACCESS || $attribute === self::ACCESS_WITH_COLLABORATORS;
}
/**
* @param ToastSessionLink $subject
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
/** @var User $user */
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
if ($attribute === self::ACCESS) {
return $user->getId() === $subject->getSession()->getUser()->getId();
}
if ($attribute === self::ACCESS_WITH_COLLABORATORS) {
$collaboratedSession = $this->collaboratedSessionRepository->findBy(['session' => $subject->getSession(), 'collaboratedUser' => $user]);
if (null !== $collaboratedSession) {
return true;
}
return $user->getId() === $subject->getSession()->getUser()->getId();
}
if ($attribute === self::ACCESS_WITH_COLLABORATORS) {
return $user->getId() === $subject->getSession()->getUser()->getId();
}
return false;
}
}