<?php
namespace App\Security\Voter;
use App\Entity\AbstractCollaborator;
use App\Entity\CertificateOfOwnershipFile;
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;
use Exception;
class DeletePropertyCertificateVoter extends Voter
{
public const CERTIFICATE_DELETE = 'CERTIFICATE_DELETE';
/**
* @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 $attribute === self::CERTIFICATE_DELETE && $subject instanceof CertificateOfOwnershipFile;
}
/**
* @param string $attribute
* @param $subject
* @param TokenInterface $token
* @return bool
* @throws Exception
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token)
{
/** @var UserInterface $user */
$user = $token->getUser();
// Deny anonymous users
if (!$user instanceof UserInterface) {
return false;
}
/** @var CertificateOfOwnershipFile $subject */
if ($attribute == self::CERTIFICATE_DELETE) {
if ($subject->getProperty()->getCollaborator()->getUserIdentifier() === $user->getUserIdentifier() || $this->security->isGranted(AbstractCollaborator::ROLE_MANAGER)) {
return true;
}
return false;
}
throw new Exception(sprintf('Unhandled attribute "%s"', $attribute));
}
}