src/Security/Voter/OnlineShop/SupplierDocumentSecurityVoter.php line 16

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