src/Security/Voter/HomeworkVoter.php line 17

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Homework;
  4. use App\Entity\HomeworkResult;
  5. use App\Entity\User;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. use Symfony\Component\Security\Core\User\UserInterface;
  10. use App\DBAL\Types\HomeworkResultStatusEnum;
  11. use App\DBAL\Types\HomeworkVisionType;
  12. use Symfony\Component\Security\Core\Security;
  13. use App\DBAL\Types\RoleEnumType;
  14. class HomeworkVoter extends Voter
  15. {
  16.     const VIEW_ANALYSIS 'view_analysis';
  17.     
  18.     const SHOW_THE_MORE_BUTTON 'SHOW_THE_MORE_BUTTON';
  19.     private $em;
  20.     
  21.     private $security;
  22.     public function __construct(EntityManagerInterface $entityManagerSecurity $security)
  23.     {
  24.         $this->em $entityManager;
  25.         $this->security $security;
  26.     }
  27.     
  28.     protected function supports($attribute$subject)
  29.     {
  30.         return in_array($attribute, [self::VIEW_ANALYSISself::SHOW_THE_MORE_BUTTON])
  31.             && $subject instanceof Homework;
  32.     }
  33.     /**
  34.      * @var string $attribute
  35.      * @var Homework $subject
  36.      * @see \Symfony\Component\Security\Core\Authorization\Voter\Voter::voteOnAttribute()
  37.      */
  38.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  39.     {
  40.         /** @var User $user */
  41.         $user $token->getUser();
  42.         // if the user is anonymous, do not grant access
  43.         if (!$user instanceof UserInterface) {
  44.             return false;
  45.         }
  46.         $homeworkResultsRepo $this->em->getRepository(HomeworkResult::class);
  47.         switch ($attribute) {
  48.             case self::VIEW_ANALYSIS:
  49.                 $homeworkResult $homeworkResultsRepo->findBy([
  50.                     'homework' => $subject->getId(),
  51.                     'student' => $user->getId(),
  52.                     'status' => HomeworkResultStatusEnum::STATUS_DONE
  53.                 ]);
  54.                 return (bool) $homeworkResult;
  55.                 break;
  56.                 
  57.             case self::SHOW_THE_MORE_BUTTON:
  58.                 if($this->security->isGranted(RoleEnumType::ROLE_ADMIN)){
  59.                     return true;
  60.                 }
  61.                 
  62.                 if($this->security->isGranted(RoleEnumType::ROLE_STUDENT) && $this->security->isGranted('view_analysis'$subject)){
  63.                     return ($subject->getVision() == HomeworkVisionType::COMPLETED_STUDENTS);
  64.                 }
  65.                 
  66.                 break;
  67.         }
  68.         return false;
  69.     }
  70. }