src/Security/Voter/HealthVoter.php line 15

  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Health;
  4. use App\Enum\RoleType;
  5. use App\Repository\HealthRepository;
  6. use App\Repository\UserRepository;
  7. use Doctrine\ORM\NonUniqueResultException;
  8. use Symfony\Bundle\SecurityBundle\Security;
  9. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  10. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  11. use Symfony\Component\Security\Core\User\UserInterface;
  12. class HealthVoter extends Voter
  13. {
  14.     public const VIEW 'HEALTH_VIEW';
  15.     public const EDIT 'HEALTH_EDIT';
  16.     public function __construct(
  17.         private Security         $security,
  18.         private HealthRepository $healthRepository,
  19.     )
  20.     {
  21.     }
  22.     protected function supports(string $attributemixed $subject): bool
  23.     {
  24.         // replace with your own logic
  25.         // https://symfony.com/doc/current/security/voters.html
  26.         return in_array($attribute, [self::VIEWself::EDIT])
  27.             && $subject instanceof Health;
  28.     }
  29.     /**
  30.      * @param mixed $subject = Health
  31.      */
  32.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  33.     {
  34.         $user $token->getUser();
  35.         // if the user is anonymous, do not grant access
  36.         if (!$user instanceof UserInterface) {
  37.             return false;
  38.         }
  39.         $isAllowedUser $this->healthRepository->getHealthUser($subject) === $user->getId();
  40.         // ... (check conditions and return true to grant permission) ...
  41.         $accessIsGranted = match ($attribute) {
  42.             'HEALTH_VIEW' =>
  43.                 $this->security->isGranted(RoleType::ROLE_HEALTH)
  44.                 ||
  45.                 $isAllowedUser,
  46.             'HEALTH_EDIT' => $isAllowedUser,
  47.         };
  48.         return $accessIsGranted;
  49.     }
  50. }