<?php
namespace App\Security\Voter;
use App\Entity\Admin;
use App\Entity\Issue;
use App\Entity\ProviderUser;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class IssueVoter extends Voter
{
public const VIEW = 'view';
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::VIEW])
&& $subject instanceof Issue;
}
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;
}
switch ($attribute) {
case self::VIEW:
return $this->canView($subject, $user);
}
return false;
}
private function canView(Issue $issue, UserInterface $user): bool
{
// De momento, si es Administrador puede ver todas las incidencias
if ($user instanceof Admin) {
return true;
}
// Los usuarios de los clientes pueden acceder a sus incidencias y a las de los usuarios del mismo cliente, siempre que tengan habilitado el acceso
if ($user instanceof User) {
return $user->isIssuesEnable() && ($user->getId() === $issue->getUser()?->getId() || $user->getClient()->getId() === $issue->getUser()?->getClient()->getId());
}
if ($user instanceof ProviderUser) {
return $user->getProvider()->getId() === $issue->getProvider()?->getId();
}
return false;
}
}