src/Security/Voter/Customer/WorkContractVoter.php line 14

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