src/Security/Voter/Tracking/UserTrackingVoter.php line 15

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