src/Security/Voter/JobOfferVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\JobOffer;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. use Symfony\Component\Security\Core\Security;
  7. use Symfony\Component\Security\Core\User\UserInterface;
  8. class JobOfferVoter extends Voter
  9. {
  10.     public const EDIT 'OFFER_EDIT';
  11.     public const VIEW 'OFFER_VIEW';
  12.     public const CAN_SEE_CANDIDACIES 'CAN_SEE_CANDIDACIES';
  13.     public function __construct(private Security $security)
  14.     {
  15.     }
  16.     protected function supports(string $attributemixed $subject): bool
  17.     {
  18.         // replace with your own logic
  19.         // https://symfony.com/doc/current/security/voters.html
  20.         return in_array($attribute, [
  21.                 self::EDIT,
  22.                 self::VIEW,
  23.                 self::CAN_SEE_CANDIDACIES,
  24.             ])
  25.             && $subject instanceof \App\Entity\JobOffer;
  26.     }
  27.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  28.     {
  29.         $user $token->getUser();
  30.         if (!$user instanceof UserInterface) {
  31.             return false;
  32.         }
  33.         if($this->security->isGranted('ROLE_MANAGER')) {
  34.             return true;
  35.         }
  36.         // ... (check conditions and return true to grant permission) ...
  37.         switch ($attribute) {
  38.             case self::EDIT:
  39.                 return $this->canEdit($subject$user);
  40.             case self::VIEW:
  41.                 return $this->canView();
  42.             case self::CAN_SEE_CANDIDACIES:
  43.                 return $this->canSeeCandidacies($subject$user);
  44.         }
  45.         return false;
  46.     }
  47.     private function canView(): bool
  48.     {
  49.         return true;
  50.     }
  51.     private function canEdit(JobOffer $jobOfferUserInterface $user)
  52.     {
  53.         if($jobOffer->getCandidacies()->count() > 0) {
  54.             return false;
  55.         }
  56.         if($jobOffer->getCreatedBy() === $user) {
  57.             return true;
  58.         }
  59.         $userCenters $user->getCentre();
  60.         return $userCenters->contains($jobOffer->getCenter());
  61.     }
  62.     private function canSeeCandidacies(JobOffer $jobOfferUserInterface $user): bool
  63.     {
  64.         if($jobOffer->getCreatedBy() === $user) {
  65.             return true;
  66.         }
  67.         $userCenters $user->getCentre();
  68.         return $userCenters->contains($jobOffer->getCenter());
  69.     }
  70. }