<?php
namespace App\Security\Voter;
use App\Entity\AbstractCollaborator;
use App\Entity\Property;
use App\Entity\Reference\ReferencePropertyStatus;
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 PropertyVoter extends Voter
{
public const GET = 'GET';
public const POST = 'POST';
public const PROPERTY_EDIT = 'PROPERTY_EDIT';
/**
* @var Security
*/
private Security $security;
/**
* @param Security $security
*/
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports(string $attribute, $subject)
{
return in_array(
$attribute,
[self::POST, self::GET, self::PROPERTY_EDIT],
true
) && $subject instanceof Property;
}
/**
* @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 Property $subject */
switch ($attribute) {
case self::PROPERTY_EDIT:
if (
($this->security->isGranted(AbstractCollaborator::ROLE_AGENT) &&
$subject->getCollaborator()->getId() === $user->getId() &&
$subject->getReferencePropertyStatus()->getName(
) == ReferencePropertyStatus::REFERENCE_PROPERTY_STATUS_INVALIDE)
||
(
$this->security->isGranted(
AbstractCollaborator::ROLE_MANAGER
) && $subject->getReferencePropertyStatus()->getName(
) != ReferencePropertyStatus::REFERENCE_PROPERTY_STATUS_RESERVED
)
) {
return true;
}
return false;
case self::POST:
if ($this->security->isGranted(AbstractCollaborator::ROLE_AGENT) || $this->security->isGranted(
AbstractCollaborator::ROLE_MANAGER
)) {
return true;
}
return false;
}
throw new Exception(sprintf('Unhandled attribute "%s"', $attribute));
}
}