<?php
namespace App\Security\Voter;
use App\Entity\Resident;
use App\Security\Voter\DTO\FlatPoll;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class FlatPollVoter extends Voter
{
/** @var string */
public const FLAT_AND_POLL_BELONG_TO_SAME_BUILDING = 'FLAT_AND_POLL_BELONG_TO_SAME_BUILDING';
/** @var array<string> */
private array $accessTypes = [self::FLAT_AND_POLL_BELONG_TO_SAME_BUILDING];
/**
* @param string $attribute
* @param mixed $subject
* @return bool
*/
protected function supports(string $attribute, mixed $subject): bool
{
return in_array($attribute, $this->accessTypes)
&& $subject instanceof FlatPoll;
}
/**
* @param string $attribute
* @param mixed $subject
* @param TokenInterface $token
* @return bool
*/
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof Resident) {
return false;
}
return $attribute === self::FLAT_AND_POLL_BELONG_TO_SAME_BUILDING
&& $subject->getFlat()->getBuilding() === $subject->getPoll()->getBuilding();
}
}