src/Security/Voter/AddressVoter.php line 12
<?php
namespace App\Security\Voter;
use App\Repository\UserRepository;
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 AddressVoter extends Voter
{
public const EDIT = 'ADDRESS_EDIT';
public const VIEW = 'ADDRESS_VIEW';
private $security;
private $userRepository;
public function __construct(Security $security, UserRepository $userRepository)
{
$this->security = $security;
$this->userRepository = $userRepository;
}
protected function supports(string $attribute, mixed $subject): bool
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [self::EDIT, self::VIEW])
&& $subject instanceof \App\Entity\Address;
}
/**
* @throws NonUniqueResultException
*/
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;
}
// Address belongs to Student, ParentData or Guardian
// Find out which one it belongs to and check if the user requesting it is the owner
// TODO: This could and should be refactored to boost performance and minimize query searches
if ($subject->getStudent()) {
$fromStudent = $this->userRepository->getUserFromStudent($subject->getStudent()->getId()) === $user;
} elseif ($subject->getGuardian()) {
$fromGuardian = $this->userRepository->getUserFromGuardian($subject->getGuardian()->getId()) === $user;
} elseif ($subject->getParent()) {
// No need to fetch more than one student to verify who is the user, first() is enough
$fromParent = $this->userRepository->getUserFromParent($subject->getParent()->getId()) === $user;
} else {
return false;
}
// ... (check conditions and return true to grant permission) ...
$accessIsGranted = match ($attribute) {
'ADDRESS_VIEW', 'ADDRESS_EDIT' =>
$this->security->isGranted('ROLE_ADMIN')
||
in_array(true, [$fromStudent ?? false, $fromGuardian ?? false, $fromParent ?? false])
};
return $accessIsGranted;
}
}