src/Security/Voter/Tires/TireVoter.php line 14

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