src/Security/Voter/Garages/GarageSearchConfigVoter.php line 14

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter\Garages;
  3. use App\Entity\Garages\GarageSearchConfig;
  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 GarageSearchConfigVoter 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::CONFIG_GARAGE_SEARCH,
  20.         ];
  21.     }
  22.     protected function supports(string $attribute$subject): bool
  23.     {
  24.         // first check the $subject and last if the $attribute is supported,
  25.         // because there are attributes (with subject) used as well by other voters (like UPDATE, ...)
  26.         if ($subject && !$subject instanceof GarageSearchConfig) {
  27.             // only vote on these objects
  28.             return false;
  29.         }
  30.         if (in_array($attribute$this->voters)) {
  31.             // if the attribute is one we support
  32.             return true;
  33.         }
  34.         return false;
  35.     }
  36.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  37.     {
  38.         $user $token->getUser();
  39.         if (!$user instanceof User) {
  40.             // the user must be logged in; if not, deny access
  41.             return false;
  42.         }
  43.         switch ($attribute) {
  44.             case VotersEnum::CONFIG_GARAGE_SEARCH:
  45.                 return $this->canConfig();
  46.         }
  47.         throw new LogicException('This code should not be reached!');
  48.     }
  49.     private function canConfig(): bool
  50.     {
  51.         return $this->isAdminUser();
  52.     }
  53.     private function isAdminUser(): bool
  54.     {
  55.         return $this->security->isGranted(UserRolesEnum::ROLE_ADMIN_LONG);
  56.     }
  57. }