src/Security/VacancyVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\User;
  4. use App\Entity\Vacancy;
  5. use LogicException;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. class VacancyVoter extends Voter
  9. {
  10.     // these strings are just invented: you can use anything
  11.     public const VIEW 'view';
  12.     public const EDIT 'edit';
  13.     /**
  14.      * @param string $attribute
  15.      * @param mixed  $subject
  16.      */
  17.     protected function supports($attribute$subject): bool
  18.     {
  19.         // if the attribute isn't one we support, return false
  20.         if (!\in_array($attribute, [self::VIEWself::EDIT], true)) {
  21.             return false;
  22.         }
  23.         // only vote on Vacancy objects inside this voter
  24.         if (!$subject instanceof Vacancy) {
  25.             return false;
  26.         }
  27.         return true;
  28.     }
  29.     /**
  30.      * @param string $attribute
  31.      * @param mixed  $subject
  32.      */
  33.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  34.     {
  35.         $user $token->getUser();
  36.         if (!$user instanceof User) {
  37.             // the user must be logged in; if not, deny access
  38.             return false;
  39.         }
  40.         // you know $subject is a Vacancy object, thanks to supports
  41.         /** @var Vacancy $vacancy */
  42.         $vacancy $subject;
  43.         switch ($attribute) {
  44.             case self::VIEW:
  45.                 return $this->canView($vacancy$user);
  46.             case self::EDIT:
  47.                 return $this->canEdit($vacancy$user);
  48.         }
  49.         throw new LogicException('This code should not be reached!');
  50.     }
  51.     private function canView(Vacancy $vacancyUser $user): bool
  52.     {
  53.         // if they can edit, they can view
  54.         if ($this->canEdit($vacancy$user)) {
  55.             return true;
  56.         }
  57.         if ($user->hasRole('ROLE_ADMIN_USER') || $user->isSuperAdmin()) {
  58.             return true;
  59.         }
  60.         if ($user->hasRole('ROLE_ADMIN_JOB_OWNER')) {
  61.             if ($vacancy->getManagers()->count() && $user->getCompanies()->isEmpty()) {
  62.                 return $vacancy->getManagers()->contains($user);
  63.             }
  64.             if ($user->getCompanies()->contains($vacancy->getCompany())) {
  65.                 return true;
  66.             }
  67.         }
  68.         return false;
  69.     }
  70.     /**
  71.      * @return bool
  72.      */
  73.     private function canEdit(Vacancy $vacancyUser $user)
  74.     {
  75.         return false;
  76.     }
  77. }