src/Security/Voter/WorkroomVoter.php line 17

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\User;
  4. use App\Entity\UserProject;
  5. use App\Entity\UserWorkroom;
  6. use App\Entity\Workroom;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  9. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  10. use Symfony\Component\Security\Core\User\UserInterface;
  11. /**
  12.  * Class WorkroomVoter.
  13.  */
  14. class WorkroomVoter extends Voter
  15. {
  16.     // Permissions.
  17.     const WORKROOM_VIEW 'workroom_view';
  18.     // Full list.
  19.     const PERMISSIONS = [
  20.         self::WORKROOM_VIEW,
  21.     ];
  22.     private EntityManagerInterface $em;
  23.     public function __construct(EntityManagerInterface $em)
  24.     {
  25.         $this->em $em;
  26.     }
  27.     /**
  28.      * {@inheritdoc}
  29.      */
  30.     protected function supports($attribute$subject): bool
  31.     {
  32.         return in_array($attributeself::PERMISSIONS) && ($subject instanceof Workroom);
  33.     }
  34.     /**
  35.      * {@inheritdoc}
  36.      */
  37.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  38.     {
  39.         /** @var User $user */
  40.         $user $token->getUser();
  41.         // If the user is anonymous, do not grant access.
  42.         if (!$user instanceof UserInterface) {
  43.             return false;
  44.         }
  45.         // Check conditions and provide access bases on it.
  46.         switch ($attribute) {
  47.             case self::WORKROOM_VIEW:
  48.                 return $this->canView($subject$user);
  49.             default:
  50.                 break;
  51.         }
  52.         return false;
  53.     }
  54.     /**
  55.      * Check that the user can view the workroom
  56.      * If the user has UserWorkroom entity we provide access, otherwise - not !!!
  57.      */
  58.     public function canView(Workroom $workroomUser $user): bool
  59.     {
  60.         $userProject $this->em->getRepository(UserProject::class)->findBy([
  61.             'project' => $workroom->getProject()->getId(),
  62.             'user' => $user->getId()
  63.         ]);
  64.         return !empty($userProject);
  65.     }
  66. }