src/Security/Voter/GuardianVoter.php line 13
<?php
namespace App\Security\Voter;
use App\Entity\Guardian;
use App\Repository\GuardianRepository;
use Doctrine\ORM\NonUniqueResultException;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class GuardianVoter extends Voter
{
public const EDIT = 'GUARDIAN_EDIT';
public const SHOW = 'GUARDIAN_SHOW';
public const DELETE = 'GUARDIAN_DELETE';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports(string $attribute, mixed $subject): bool
{
return in_array($attribute, [self::EDIT, self::SHOW, self::DELETE]);
}
/**
* @param string $attribute
* @param Guardian $subject
* @param TokenInterface $token
* @return bool
* @throws NonUniqueResultException
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
/**
* Checks if requesting User is the Guardian
* Admin has general access
*/
$accessIsGranted = match ($attribute) {
'GUARDIAN_SHOW' =>
$user->getId() === $subject['user_id']
||
$this->security->isGranted('ROLE_ADMIN'),
'GUARDIAN_EDIT' =>
$user === $subject->getUser()
||
$this->security->isGranted('ROLE_ADMIN'),
'GUARDIAN_DELETE' => $this->security->isGranted('ROLE_ADMIN'),
};
return $accessIsGranted;
}
}