<?php
namespace Crea\SecurityBundle\Voter;
use Crea\SecurityBundle\Entity\UserGroup;
use Crea\SecurityBundle\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class UserGroupVoter extends Voter
{
const USER_GROUP_LIST = "SECURITY_USER_GROUP_LIST";
const USER_GROUP_CREATE = "SECURITY_USER_GROUP_CREATE";
const USER_GROUP_UPDATE = "SECURITY_USER_GROUP_UPDATE";
const USER_GROUP_REMOVE = "SECURITY_USER_GROUP_REMOVE";
/**
* @inheritDoc
*/
protected function supports($attribute, $subject): bool
{
return in_array($attribute, [
self::USER_GROUP_LIST,
self::USER_GROUP_CREATE,
self::USER_GROUP_UPDATE,
self::USER_GROUP_REMOVE,
]) && ($subject === null || $subject instanceof UserGroup);
}
/**
* @inheritDoc
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
/** @var User $loggedUser */
$loggedUser = $token->getUser();
if (!$loggedUser instanceof UserInterface)
return false;
switch ($attribute) {
case self::USER_GROUP_LIST:
return $this->voteOnList($loggedUser);
case self::USER_GROUP_CREATE:
return $this->voteOnCreate($loggedUser);
case self::USER_GROUP_UPDATE:
return $this->voteOnUpdate($subject, $loggedUser);
case self::USER_GROUP_REMOVE:
return $this->voteOnRemove($subject, $loggedUser);
}
return false;
}
private function voteOnList(UserInterface $loggedUser): bool
{
if (in_array(self::USER_GROUP_LIST, $loggedUser->getRoles())) {
return true;
}
return false;
}
private function voteOnCreate(UserInterface $loggedUser): bool
{
if (in_array(self::USER_GROUP_CREATE, $loggedUser->getRoles())) {
return true;
}
return false;
}
private function voteOnUpdate(?UserGroup $subject, User $loggedUser): bool
{
if (!in_array(self::USER_GROUP_UPDATE, $loggedUser->getRoles()))
return false;
if (null === $subject)
return true;
if (in_array("ROLE_ADMIN", $loggedUser->getRoles()))
return true;
return false;
}
private function voteOnRemove(?UserGroup $subject, User $loggedUser): bool
{
if (!in_array(self::USER_GROUP_REMOVE, $loggedUser->getRoles()))
return false;
if (null === $subject)
return true;
if (in_array("ROLE_ADMIN", $loggedUser->getRoles()))
return true;
return false;
}
}