src/Security/SectionVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\Section;
  4. use App\Entity\SectionAcl;
  5. use App\Entity\User;
  6. use App\Entity\UserGroup;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  9. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  10. class SectionVoter extends Voter
  11. {
  12.     /**
  13.      * @var EntityManagerInterface
  14.      */
  15.     private $em;
  16.     /**
  17.      * SectionVoter constructor.
  18.      * @param EntityManagerInterface $em
  19.      */
  20.     public function __construct(EntityManagerInterface $em)
  21.     {
  22.         $this->em $em;
  23.     }
  24.     /**
  25.      * {@inheritdoc}
  26.      */
  27.     protected function supports($attribute$subject)
  28.     {
  29.         if (!in_array($attributeSectionAcl::getPermissions())) {
  30.             return false;
  31.         }
  32.         if (!$subject instanceof Section) {
  33.             return false;
  34.         }
  35.         return true;
  36.     }
  37.     /**
  38.      * {@inheritdoc}
  39.      */
  40.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  41.     {
  42.         /** @var Section $section */
  43.         $section $subject;
  44.         $user $token->getUser();
  45.         $group = ($user instanceof User) ?
  46.             $user->getGroup() :
  47.             $this->em->getRepository(UserGroup::class)->findOneBy(['role' => UserGroup::ROLE_ANONYMOUS]);
  48.         $acl $this->em->getRepository(SectionAcl::class)->findOneBy([
  49.             'section' => $section,
  50.             'userGroup' => $group,
  51.         ]);
  52.         if (!$acl instanceof SectionAcl) {
  53.             return false;
  54.         }
  55.         switch ($attribute) {
  56.             case SectionAcl::PERMISSION_READ:
  57.                 return $this->canRead($acl);
  58.             case SectionAcl::PERMISSION_READ_WRITE:
  59.                 return $this->canWrite($acl);
  60.         }
  61.         throw new \LogicException("This code should not be reached.");
  62.     }
  63.     /**
  64.      * @return bool
  65.      */
  66.     private function canRead(SectionAcl $acl): bool
  67.     {
  68.         if ($this->canWrite($acl)) {
  69.             return true;
  70.         }
  71.         return $acl->getPermission() === SectionAcl::PERMISSION_READ;
  72.     }
  73.     /**
  74.      * @return bool
  75.      */
  76.     private function canWrite(SectionAcl $acl): bool
  77.     {
  78.         return $acl->getPermission() === SectionAcl::PERMISSION_READ_WRITE;
  79.     }
  80. }