src/Security/Voter/Resource/AdminVoter.php line 14

  1. <?php
  2. namespace App\Security\Voter\Resource;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Symfony\Component\Security\Core\Authorization\Voter\Voter,
  5.     Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface,
  6.     Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use App\Entity\Admin,
  8.     App\Lib\Actions,
  9.     App\Lib\Roles;
  10. final class AdminVoter extends Voter
  11. {
  12.     const VOTABLE_ATTRIBUTES = [
  13.         Actions::CREATE,
  14.         Actions::VIEW,
  15.         Actions::EDIT,
  16.         Actions::DELETE
  17.     ];
  18.     private AuthorizationCheckerInterface $authorizationChecker;
  19.     private EntityManagerInterface $em;
  20.     public function __construct(
  21.         AuthorizationCheckerInterface $authorizationChecker,
  22.         EntityManagerInterface $em
  23.     ) {
  24.         $this->authorizationChecker $authorizationChecker;
  25.         $this->em $em;
  26.     }
  27.     protected function supports($attribute$subject): bool
  28.     {
  29.         if (
  30.             ! $subject instanceof Admin
  31.             || ! in_array($attributeself::VOTABLE_ATTRIBUTES)
  32.         ) {
  33.             return false;
  34.         }
  35.         return true;
  36.     }
  37.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  38.     {
  39.         if ($this->isSubjectCurrentAdmin($subject$token)) {
  40.             return false;
  41.         }
  42.         if ($this->isSubjectAccessable($subject)) {
  43.             return true;
  44.         }
  45.         return false;
  46.     }
  47.     private function isSubjectCurrentAdmin(Admin $subjectTokenInterface $token): bool
  48.     {
  49.         /** @var Admin */
  50.         $current $token->getUser();
  51.         if ($current->getUuid() !== $subject->getUuid()) {
  52.             return false;
  53.         }
  54.         return true;
  55.     }
  56.     private function isSubjectAccessable(Admin $subject): bool
  57.     {
  58.         if ($this->authorizationChecker->isGranted(Roles::ROLE_OPENFORM)) {
  59.             return true;
  60.         }
  61.         $original $this->em->getUnitOfWork()->getOriginalEntityData($subject);
  62.         if (
  63.             ! ($original['group'] ?? null)?->getIsOpenform()
  64.             && ! $subject->getGroup()?->getIsOpenform()
  65.          ) {
  66.             return false;
  67.         }
  68.         return true;
  69.     }
  70. }