src/Security/StudentCourseAccessVoter.php line 15

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\Course;
  4. use App\Entity\Enrollment;
  5. use App\Entity\User;
  6. use App\Repository\EnrollmentRepository;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. /**
  10.  * Checks if a user is able to access a given course.
  11.  */
  12. class StudentCourseAccessVoter extends Voter
  13. {
  14.     private EnrollmentRepository $enrollmentRepository;
  15.     public function __construct(EnrollmentRepository $enrollmentRepository)
  16.     {
  17.         $this->enrollmentRepository $enrollmentRepository;
  18.     }
  19.     protected function supports(string $attribute$subject): bool
  20.     {
  21.         if (!$subject instanceof Course) {
  22.             return false;
  23.         }
  24.         return true;
  25.     }
  26.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  27.     {
  28.         $user $token->getUser();
  29.         if (!$user instanceof User) {
  30.             // must be logged in
  31.             return false;
  32.         }
  33.         // confirmed $subject is a Course object, thanks to `supports()`
  34.         /** @var Course $course */
  35.         $course $subject;
  36.         $enrollments $this->enrollmentRepository->findBy(['student' => $user->getId()]);
  37.         $enrolledCourseIds array_map(function(Enrollment $enrollment) {
  38.             return $enrollment->getModule()->getCourse()->getId();
  39.         }, $enrollments);
  40.         if (!in_array($course->getId(), $enrolledCourseIds)) {
  41.             return false;
  42.         }
  43.         return true;
  44.     }
  45. }