<?php
namespace App\Security\Voter;
use App\Entity\Job\Lecturer;
use App\Entity\User;
use App\Entity\StudyGroup;
use App\Entity\Job\Tutor;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class StudyGroupVoter extends Voter
{
const UPDATE = 'STUDY_GROUP_UPDATE';
const DELETE = 'STUDY_GROUP_DELETE';
const READ = 'STUDY_GROUP_READ';
private $security;
/**
* @param Security $security
*/
public function __construct(Security $security)
{
$this->security = $security;
}
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 StudyGroup objects inside this voter
if (!$subject instanceof StudyGroup) {
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 StudyGroup $studyGroup */
$studyGroup = $subject; // you know $subject is a StudyGroup object, thanks to supports
switch ($attribute) {
case self::UPDATE:
return $this->canUpdate($studyGroup, $user);
case self::DELETE:
return $this->canDelete($studyGroup, $user);
case self::READ:
return $this->canRead($studyGroup, $user);
}
throw new \LogicException('This code should not be reached!');
}
private function canUpdate(StudyGroup $studyGroup, User $user)
{
if ($this->security->isGranted(User::ROLE_TUTOR)) {
return $studyGroup->getTutors()->contains($user->getJob(Tutor::class));
} elseif ($this->security->isGranted(User::ROLE_LECTURER)) {
return $studyGroup->getCourse()->getLecturers()->contains($user->getJob(Lecturer::class));
}
return false;
}
private function canDelete(StudyGroup $studyGroup, User $user)
{
if ($this->security->isGranted(User::ROLE_LECTURER)) {
return $studyGroup->getCourse()->getLecturers()->contains($user->getJob(Lecturer::class));
}
return false;
}
private function canRead(StudyGroup $studyGroup, User $user)
{
if ($this->security->isGranted(User::ROLE_TUTOR)) {
return $studyGroup->getTutors()->contains($user->getJob(Tutor::class));
} elseif ($this->security->isGranted(User::ROLE_LECTURER)) {
return $studyGroup->getCourse()->getLecturers()->contains($user->getJob(Lecturer::class));
}
return false;
}
}