src/Security/Voter/Whatsapp/WhatsappMessageVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter\Whatsapp;
  3. use App\Entity\User;
  4. use App\Entity\Whatsapp\whatsappMessage;
  5. use App\Enum\UserRolesEnum;
  6. use App\Enum\VotersEnum;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. use Symfony\Component\Security\Core\Security;
  10. class WhatsappMessageVoter extends Voter
  11. {
  12.     private Security $security;
  13.     private array $voters;
  14.     public function __construct(Security $security)
  15.     {
  16.         $this->security $security;
  17.         $this->voters = [
  18.             VotersEnum::LIST_WHATSAPP_MESSAGE,
  19.         ];
  20.     }
  21.     protected function supports(string $attribute$subject): bool
  22.     {
  23.         // first check the $subject and last if the $attribute is supported,
  24.         // because there are attributes (with subject) used as well by other voters (like UPDATE, ...)
  25.         if ($subject && !$subject instanceof whatsappMessage) {
  26.             // only vote on these objects
  27.             return false;
  28.         }
  29.         if (in_array($attribute$this->voters)) {
  30.             // if the attribute is one we support
  31.             return true;
  32.         }
  33.         return false;
  34.     }
  35.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  36.     {
  37.         $user $token->getUser();
  38.         if (!$user instanceof User) {
  39.             // the user must be logged in; if not, deny access
  40.             return false;
  41.         }
  42.         switch ($attribute) {
  43.             case VotersEnum::LIST_WHATSAPP_MESSAGE:
  44.                 return $this->canlist();
  45.         }
  46.         throw new \LogicException('This code should not be reached!');
  47.     }
  48.     private function canList(): bool
  49.     {
  50.         return $this->isAdminUser();
  51.     }
  52.     private function isAdminUser(): bool
  53.     {
  54.         return $this->security->isGranted(UserRolesEnum::ROLE_ADMIN_LONG);
  55.     }
  56. }