<?php
namespace App\Security\Voter;
use App\Entity\AbstractCollaborator;
use App\Entity\PropertyImages;
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 PropertyImagesVoter
*
*/
class PropertyImageVoter extends Voter
{
public const PATCH = 'PATCH';
/**
* @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::PATCH && $subject instanceof PropertyImages;
}
/**
* @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 PropertyImages $subject */
if ($attribute === self::PATCH) {
if ($this->security->isGranted(AbstractCollaborator::ROLE_MANAGER) || $user->getUserIdentifier() === $subject->getProperty()->getCollaborator()->getUserIdentifier()) {
return true;
}
return false;
}
throw new Exception(sprintf('Unhandled attribute "%s"', $attribute));
}
}