src/Security/Voter/RequestItemVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\EnterpriseContactPosition;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\User\UserInterface;
  8. class RequestItemVoter extends Voter
  9. {
  10.     private EntityManagerInterface $em;
  11.     public function __construct(EntityManagerInterface $em)
  12.     {
  13.         $this->em $em;
  14.     }
  15.     protected function supports($attribute$subject)
  16.     {
  17.         // replace with your own logic
  18.         // https://symfony.com/doc/current/security/voters.html
  19.         return in_array($attribute, ['create''update','delete','view'])
  20.             && $subject instanceof \App\Entity\RequestItem;
  21.     }
  22.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  23.     {
  24.         $user $token->getUser();
  25.         // if the user is anonymous, do not grant access
  26.         if (!$user instanceof UserInterface) {
  27.             return false;
  28.         }
  29.         $enterprises $this->em->getRepository(EnterpriseContactPosition::class)->getEnterprises($user->getContact());
  30.         if ($user->getRoles()[0] == "ROLE_ADMIN") { return true;
  31.         }
  32.         // ... (check conditions and return true to grant permission) ...
  33.         switch ($attribute) {
  34.         case 'create':
  35.             if(in_array($subject->getRemovalRequest()->getCustomer(), $enterprises)) { return true;
  36.             }
  37.             break;
  38.         case 'update':
  39.             if(in_array($subject->getRemovalRequest()->getCustomer(), $enterprises)|| in_array($subject->getSupplier(), $enterprises) ) { return true;
  40.             }
  41.             break;
  42.         case 'delete':
  43.             return false;
  44.             break;
  45.         case 'view':
  46.             if(in_array($subject->getRemovalRequest()->getCustomer(), $enterprises)|| in_array($subject->getSupplier(), $enterprises) ) { return true;
  47.             }
  48.             break;
  49.         }
  50.         return false;
  51.     }
  52. }