<?php
namespace App\Security;
use App\Entity\Course;
use App\Entity\User;
use App\Service\InstructorService;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
/**
* Checks if an instructor is able to access a given course.
*/
class InstructorCourseAccessVoter extends Voter
{
private InstructorService $instructorService;
public function __construct(InstructorService $instructorService)
{
$this->instructorService = $instructorService;
}
protected function supports(string $attribute, $subject): bool
{
if (!$subject instanceof Course) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
// must be logged in
return false;
}
// confirmed $subject is a Course object, thanks to `supports()`
/** @var Course $course */
$course = $subject;
return in_array($course, $this->instructorService->fetchInstructorCourses($user));
}
}