src/Security/Voter/Resource/AdminGroupVoter.php line 12

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