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