<?php
declare(strict_types=1);
namespace Crea\SecurityBundle\Voter;
use Crea\SecurityBundle\Entity\User;
use Crea\SecurityBundle\Entity\UserGroup;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @extends Voter<string, UserGroup>
*/
class UserGroupVoter extends Voter
{
public const USER_GROUP_LIST = 'SECURITY_USER_GROUP_LIST';
public const USER_GROUP_CREATE = 'SECURITY_USER_GROUP_CREATE';
public const USER_GROUP_UPDATE = 'SECURITY_USER_GROUP_UPDATE';
public const USER_GROUP_REMOVE = 'SECURITY_USER_GROUP_REMOVE';
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,
]) && (null === $subject || $subject instanceof UserGroup);
}
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;
}
}