src/Security/Voter/HealthVoter.php line 15
<?php
namespace App\Security\Voter;
use App\Entity\Health;
use App\Enum\RoleType;
use App\Repository\HealthRepository;
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 HealthVoter extends Voter
{
public const VIEW = 'HEALTH_VIEW';
public const EDIT = 'HEALTH_EDIT';
public function __construct(
private Security $security,
private HealthRepository $healthRepository,
)
{
}
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::VIEW, self::EDIT])
&& $subject instanceof Health;
}
/**
* @param mixed $subject = Health
*/
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;
}
$isAllowedUser = $this->healthRepository->getHealthUser($subject) === $user->getId();
// ... (check conditions and return true to grant permission) ...
$accessIsGranted = match ($attribute) {
'HEALTH_VIEW' =>
$this->security->isGranted(RoleType::ROLE_HEALTH)
||
$isAllowedUser,
'HEALTH_EDIT' => $isAllowedUser,
};
return $accessIsGranted;
}
}