src/Security/Voter/Customer/ManualTimeEntryVoter.php line 12

  1. <?php
  2. namespace App\Security\Voter\Customer;
  3. use App\Entity\Customer\ManualTimeEntry;
  4. use App\Entity\Admin\CustomerUser;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\User\UserInterface;
  8. use Symfony\Bundle\SecurityBundle\Security;
  9. class ManualTimeEntryVoter extends Voter
  10. {
  11.     final public const EDIT   'MTE_ENTITY_EDIT';
  12.     final public const VIEW   'MTE_ENTITY_VIEW';
  13.     final public const DELETE 'MTE_ENTITY_DELETE';
  14.     
  15.     public function __construct(
  16.             private readonly Security $security)
  17.     {
  18.     }
  19.     
  20.     protected function supports(string $attributemixed $subject): bool
  21.     {
  22.         if(!in_array($attribute, [self::EDITself::VIEWself::DELETE])){
  23.             return false;
  24.         }
  25.         if (!$subject instanceof ManualTimeEntry) {
  26.             return false;
  27.         }
  28.         
  29.         return true;
  30.     }
  31.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  32.     {
  33.         $user $token->getUser();
  34.         // if the user is anonymous, do not grant access
  35.         if (!$user instanceof UserInterface) {
  36.             return false;
  37.         }
  38.         
  39.         if (!$this->security->isGranted('ROLE_STAFF')){
  40.             return false;
  41.         }
  42.     
  43.         return match($attribute) {
  44.             self::VIEW => $this->canView($subject$user),
  45.             self::EDIT => $this->canEdit(),
  46.             self::DELETE => $this->canDelete(),
  47.             default => throw new \LogicException('This code should not be reached!')
  48.         };
  49.     }
  50.     
  51.     private function canView(ManualTimeEntry $entityCustomerUser $user): bool
  52.     {
  53.         if ($this->canEdit()) {
  54.             return true;
  55.         }
  56.         
  57.         if ($entity->getStaff()->getId() == $user->getStaff()) {
  58.             return true;
  59.         }
  60.         return false;
  61.     }
  62.     private function canEdit(): bool
  63.     {
  64.         return $this->security->isGranted('ROLE_ADMIN');
  65.     }
  66.     
  67.     private function canDelete(): bool
  68.     {
  69.         return $this->security->isGranted('ROLE_ADMIN');
  70.     }
  71. }