<?php
namespace App\Security\Voter;
use App\Entity\Course;
use App\Entity\Job\Lecturer;
use App\Entity\Job\Tutor;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class CourseVoter extends Voter
{
const UPDATE = 'COURSE_UPDATE';
const DELETE = 'COURSE_DELETE';
const READ = 'COURSE_READ';
private $security;
private $entityManager;
/**
* @param Security $security
* @param EntityManagerInterface $entityManager
*/
public function __construct(Security $security, EntityManagerInterface $entityManager)
{
$this->security = $security;
$this->entityManager = $entityManager;
}
protected function supports($attribute, $subject)
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::UPDATE, self::DELETE, self::READ])) {
return false;
}
// only vote on Course objects inside this voter
if (!$subject instanceof Course) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
if ($this->security->isGranted(User::ROLE_ADMIN)) {
return true;
}
/** @var Course $course */
$course = $subject; // you know $subject is a Course object, thanks to supports
switch ($attribute) {
case self::UPDATE:
return $this->canUpdate($course, $user);
case self::DELETE:
return $this->canDelete($course, $user);
case self::READ:
return $this->canRead($course, $user);
}
throw new \LogicException('This code should not be reached!');
}
private function canUpdate(Course $course, User $user)
{
if ($this->security->isGranted(User::ROLE_LECTURER)) {
return $course->getLecturers()->contains($user->getJob(Lecturer::class));
}
return false;
}
private function canDelete(Course $course, User $user)
{
if ($this->security->isGranted(User::ROLE_LECTURER)) {
return $course->getLecturers()->contains($user->getJob(Lecturer::class));
}
return false;
}
private function canRead(Course $course, User $user)
{
if ($this->security->isGranted(User::ROLE_LECTURER)) {
return $course->getLecturers()->contains($user->getJob(Lecturer::class));
}
if ($this->security->isGranted(User::ROLE_TUTOR)) {
$tutorsInCourse = $this->entityManager->getRepository(Tutor::class)->findByCourse($course);
return in_array($user->getJob(Tutor::class), $tutorsInCourse);
}
return false;
}
}