src/Security/Voter/Customer/ScoreVoter.php line 14

  1. <?php
  2. namespace App\Security\Voter\Customer;
  3. use App\Entity\Customer\Score;
  4. use App\Entity\Customer\ScoreInvite;
  5. use App\Entity\Admin\CustomerUser;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\User\UserInterface;
  9. use Doctrine\Persistence\ManagerRegistry;
  10. use Symfony\Bundle\SecurityBundle\Security;
  11. class ScoreVoter extends Voter
  12. {
  13.     final public const EDIT 'SCORE_ENTITY_EDIT';
  14.     final public const VIEW 'SCORE_ENTITY_VIEW';
  15.     final public const DELETE 'SCORE_ENTITY_DELETE';
  16.     public function __construct(
  17.         private readonly Security $security
  18.     ) {
  19.     }
  20.     protected function supports(string $attributemixed $subject): bool
  21.     {
  22.         if (!in_array($attribute, [self::EDITself::VIEWself::DELETE])) {
  23.             return false;
  24.         }
  25.         if (!$subject instanceof Score) {
  26.             return false;
  27.         }
  28.         return true;
  29.     }
  30.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  31.     {
  32.         $user $token->getUser();
  33.         // if the user is anonymous, do not grant access
  34.         if (!$user instanceof UserInterface) {
  35.             return false;
  36.         }
  37.         if (!$this->security->isGranted('ROLE_STAFF')) {
  38.             return false;
  39.         }
  40.         // ... (check conditions and return true to grant permission) ...
  41.         return match ($attribute) {
  42.             self::VIEW => $this->canView($subject$user),
  43.             self::EDIT => $this->canEdit($subject),
  44.             self::DELETE => $this->canDelete(),
  45.             default => throw new \LogicException('This code should not be reached!')
  46.         };
  47.     }
  48.     private function canView(Score $entityCustomerUser $user): bool
  49.     {
  50.         if ($entity->getStaff()->getId() == $user->getStaff()) {
  51.             return true;
  52.         }
  53.         return false;
  54.     }
  55.     private function canEdit(?Score $entity): bool
  56.     {
  57.         if ($entity == null) {
  58.             return true;
  59.         }
  60.         if ($entity->getStaff() == null) {
  61.             return true;
  62.         }
  63.         return false;
  64.     }
  65.     private function canDelete(): bool
  66.     {
  67.         return false;
  68.     }
  69. }