src/Security/Voters/Organisation/Page.php line 12

  1. <?php
  2. namespace App\Security\Voters\Organisation;
  3. use App\Entity\Organisation\Organisation;
  4. use App\Entity\Organisation\User;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\Security;
  9. class Page extends Voter
  10. {
  11.     public const PAGE_EDIT 'page_edit';
  12.     /**
  13.      * @var Security
  14.      */
  15.     private $security;
  16.     /**
  17.      * @var EntityManagerInterface
  18.      */
  19.     private $em;
  20.     public function __construct(Security $securityEntityManagerInterface $em)
  21.     {
  22.         $this->security $security;
  23.         $this->em $em;
  24.     }
  25.     protected function supports(string $attribute$subject): bool
  26.     {
  27.         if ($subject instanceof \App\Entity\Organisation\Page) {
  28.             if (in_array($attribute, [self::PAGE_EDIT])) {
  29.                 return true;
  30.             }
  31.         }
  32.         return false;
  33.     }
  34.     /**
  35.      * @param string $attribute
  36.      *
  37.      * @param TokenInterface $token
  38.      * @return bool
  39.      */
  40.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  41.     {
  42.         switch ($attribute) {
  43.             case self::PAGE_EDIT:
  44.                 return $this->pageEdit($subject);
  45.         }
  46.         throw new \LogicException('This code should not be reached!');
  47.     }
  48.     /**
  49.      *
  50.      * @return bool
  51.      */
  52.     protected function pageEdit(\App\Entity\Organisation\Page $subject): bool
  53.     {
  54.         /** @var \App\Entity\User\User $user */
  55.         $user $this->security->getUser();
  56.         if ($subject->isDeleted() || !$user) {
  57.             return false;
  58.         }
  59.         $orgUser $this->em->getRepository(User::class)->findByUser($user->getId());
  60.         if (!$orgUser) {
  61.             return false;
  62.         }
  63.         return $orgUser->getOrganisation()->getId() == $subject->getOrganisation()->getId();
  64.     }
  65. }