<?php
namespace App\Security\Voter;
use App\Entity\AbstractCollaborator;
use App\Entity\Candidate;
use App\Entity\Agent;
use Exception;
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;
/**
* @package App\Security\Voter
* @class CandidateVoter
*
*/
class CandidateVoter extends Voter
{
public const POST = 'POST';
public const PUT = 'PUT';
public const GET = 'GET';
public const STATUS = 'STATUS';
/**
* @var Security
*/
private Security $security;
/**
* @param Security $security
*/
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* @param string $attribute
* @param mixed $subject
* @return bool
*/
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, [self::POST, self::PUT,self::GET,self::STATUS], true) && $subject instanceof Candidate;
}
/**
* @throws Exception
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
/** @var UserInterface $user */
$user = $token->getUser();
// Deny anonymous users
if (!$user instanceof UserInterface) {
return false;
}
/** @var Candidate $subject */
switch ($attribute) {
case self::STATUS:
case self::GET:
if ($this->security->isGranted(AbstractCollaborator::ROLE_MANAGER) || $this->security->isGranted(AbstractCollaborator::ROLE_AGENT)) {
return true;
}
break;
case self::PUT:
if ($subject->getSponsor() === $user) {
return true;
}
break;
case self::POST:
if ($this->security->isGranted(AbstractCollaborator::ROLE_AGENT)) {
return true;
}
return false;
}
throw new Exception(sprintf('Unhandled attribute "%s"', $attribute));
}
}