<?php
namespace App\Security\Voter;
use App\Entity\Course;
use App\Entity\Job\Lecturer;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class UserVoter extends Voter
{
const READ = 'USER_READ';
const UPDATE = 'USER_UPDATE';
const DELETE = 'USER_DELETE';
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::READ, self::UPDATE, self::DELETE])) {
return false;
}
// only vote on User objects inside this voter
if (!$subject instanceof User) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$currentUser = $token->getUser();
if (!$currentUser instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
if ($this->security->isGranted(User::ROLE_ADMIN)) {
return true;
}
switch ($attribute) {
case self::READ:
return $this->canRead($currentUser);
case self::UPDATE:
return $this->canUpdate($currentUser);
case self::DELETE:
return $this->canDelete($currentUser);
}
throw new \LogicException('This code should not be reached!');
}
private function canRead(User $currentUser)
{
if ($this->security->isGranted(User::ROLE_LECTURER)) {
return true;
}
return false;
}
private function canUpdate(User $currentUser)
{
if ($this->security->isGranted(User::ROLE_LECTURER)) {
return true;
}
return false;
}
private function canDelete(User $currentUser)
{
return false;
}
}