<?php
namespace App\Security\Voter;
use App\Entity\Flat;
use App\Entity\Resident;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class FlatVoter extends Voter
{
/** @var string */
public const FLAT_BELONGS_TO_RESIDENT = 'FLAT_BELONGS_TO_RESIDENT';
private const ATTRIBUTES = [
self::FLAT_BELONGS_TO_RESIDENT
];
/**
* @param string $attribute
* @param mixed $subject
* @return bool
*/
protected function supports(string $attribute, mixed $subject): bool
{
return in_array($attribute, self::ATTRIBUTES)
&& $subject instanceof Flat;
}
/**
* @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 UserInterface) {
return false;
}
return $attribute === self::FLAT_BELONGS_TO_RESIDENT
&& $subject instanceof Flat && $subject->getResident() === $user;
}
}