src/Security/ContactVoter.php line 13

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Security;
  4. use App\Entity\Contact;
  5. use App\Entity\SalesRep;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\Security;
  9. class ContactVoter extends Voter
  10. {
  11.     const EDIT 'edit';
  12.     private $security;
  13.     public function __construct(Security $security)
  14.     {
  15.         $this->security $security;
  16.     }
  17.     protected function supports(string $attributemixed $subject): bool
  18.     {
  19.         if (!in_array($attribute, [self::EDIT])) {
  20.             return false;
  21.         }
  22.         if (!$subject instanceof Contact) {
  23.             return false;
  24.         }
  25.         return true;
  26.     }
  27.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  28.     {
  29.         $user $token->getUser();
  30.         if (!$user instanceof SalesRep) {
  31.             return false;
  32.         }
  33.         return match($attribute) {
  34.             self::EDIT => $this->canEdit($subject$user),
  35.             default => throw new \LogicException('This code should not be reached!')
  36.         };
  37.     }
  38.     private function canEdit(Contact $contactSalesRep $user): bool
  39.     {
  40.         $ownerId null !== $contact->getSalesRep()
  41.             ? $contact->getSalesRep()->getId()
  42.             : null
  43.         ;
  44.         if (
  45.             false === $this->security->isGranted('ROLE_ADMIN')
  46.             && false === $this->security->isGranted('ROLE_UPDATER')
  47.             && false === $this->security->isGranted('ROLE_INSIDE_USER')
  48.             && false === $this->security->isGranted('ROLE_EX_UPDATE')
  49.             && $ownerId !== $user->getId()
  50.         ) {
  51.             return false;
  52.         }
  53.         return true;
  54.     }
  55. }