src/Security/Voter/Voter/PersonVoter.php line 12

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Security\Voter\Voter;
  4. use App\Entity\Job;
  5. use App\Entity\Person;
  6. use App\Entity\User;
  7. use App\Security\Voter\AbstractVoter;
  8. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  9. class PersonVoter extends AbstractVoter
  10. {
  11.     /**
  12.      * @param string $attribute
  13.      * @param $subject
  14.      * @return bool
  15.      */
  16.     protected function supports(string $attribute$subject): bool
  17.     {
  18.         $cond1 $subject instanceof Person;
  19.         $cond2 in_array($attribute, [self::EDIT]);
  20.         return $cond1 && $cond2;
  21.     }
  22.     /**
  23.      * @param string $attribute
  24.      * @param $subject
  25.      * @param TokenInterface $token
  26.      * @return bool
  27.      */
  28.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  29.     {
  30.         $user $token->getUser();
  31.         if (!$user instanceof User) {
  32.             return false;
  33.         }
  34.         if ($user->hasRole(User::ROLE_ADMIN)) {
  35.             return true;
  36.         }
  37.         switch ($attribute) {
  38.             case self::EDIT:
  39.                 return $this->canEdit($subject$user);
  40.         }
  41.         return false;
  42.     }
  43.     private function canEdit(Person $personUser $user): bool
  44.     {
  45.         if (!$user->hasRole(User::ROLE_ORGANIZATION_REDACTOR)) {
  46.             return false;
  47.         }
  48.         $cond1 $user->getId() === $person->getCreatedBy()->getId();
  49.         $cond2 false;
  50.         /** @var Job $job */
  51.         foreach ($person->getJobs() as $job) {
  52.             if ($user->getOrganization()->getId() === $job->getOrganization()->getId()) {
  53.                 $cond2 true;
  54.             }
  55.         }
  56.         return $cond1 || $cond2;
  57.     }
  58. }