src/Security/Voter/SocietyV2Voter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\User;
  4. use App\Entity\V2\SocietyV2;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\Security;
  8. class SocietyV2Voter extends Voter
  9. {
  10.     const VIEW 'view';
  11.     const EDIT 'edit';
  12.     const DELETE 'delete';
  13.     private Security $security;
  14.     public function __construct(Security $security)
  15.     {
  16.         $this->security $security;
  17.     }
  18.     protected function supports(string $attribute$subject): bool
  19.     {
  20.         return in_array($attribute, [self::VIEWself::EDITself::DELETE])
  21.             && $subject instanceof SocietyV2;
  22.     }
  23.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  24.     {
  25.         $user $token->getUser();
  26.         if (!$user instanceof User) {
  27.             return false;
  28.         }
  29.         /** @var SocietyV2 $society */
  30.         $society $subject;
  31.         // Admin can do everything
  32.         if ($this->security->isGranted('ROLE_ADMIN')) {
  33.             return true;
  34.         }
  35.         switch ($attribute) {
  36.             case self::VIEW:
  37.                 return $this->canView($society$user);
  38.             case self::EDIT:
  39.                 return $this->canEdit($society$user);
  40.             case self::DELETE:
  41.                 return $this->canDelete($society$user);
  42.         }
  43.         return false;
  44.     }
  45.     private function canView(SocietyV2 $societyUser $user): bool
  46.     {
  47.         // Owner can view
  48.         if ($society->getUser() && $society->getUser()->getId() === $user->getId()) {
  49.             return true;
  50.         }
  51.         // Users from the same client can view
  52.         if ($society->getClient() && $user->getClient()) {
  53.             if ($society->getClient()->getId() === $user->getClient()->getId()) {
  54.                 return true;
  55.             }
  56.         }
  57.         return false;
  58.     }
  59.     private function canEdit(SocietyV2 $societyUser $user): bool
  60.     {
  61.         // Same as view for now - owner or same client
  62.         return $this->canView($society$user);
  63.     }
  64.     private function canDelete(SocietyV2 $societyUser $user): bool
  65.     {
  66.         // Only owner can delete
  67.         if ($society->getUser() && $society->getUser()->getId() === $user->getId()) {
  68.             return true;
  69.         }
  70.         return false;
  71.     }
  72. }