<?php
namespace DW\GingerBundle\Security;
use DW\GingerBundle\Entity\GroupInterface;
use DW\GingerBundle\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
class GroupVoter extends Voter
{
const VIEW = 'view';
const EDIT = 'edit';
const CREATE = 'create';
const DELETE = 'delete';
private AccessDecisionManagerInterface $decisionManager;
public function __construct(AccessDecisionManagerInterface $decisionManager)
{
$this->decisionManager = $decisionManager;
}
protected function supports($attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, array(self::VIEW, self::EDIT, self::CREATE, self::DELETE))) {
return false;
}
// only vote on tag objects inside this voter
if (!$subject instanceof GroupInterface) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
/** @var GroupInterface $group */
$group = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($group, $token);
case self::EDIT:
return $this->canEdit($group, $token);
case self::CREATE:
return $this->canCreate($group, $token);
case self::DELETE:
return $this->canDelete($group, $token);
}
throw new \LogicException('This code should not be reached!');
}
private function canCreate(GroupInterface $group, TokenInterface $token): bool
{
if ($this->decisionManager->decide($token, array('ROLE_GINGER_GROUP_CREATE'))) {
return true;
}
return false;
}
private function canView(GroupInterface $group, TokenInterface $token): bool
{
// if they can edit, they can view
if ($this->canEdit($group, $token)) {
return true;
}
return false;
}
private function canEdit(GroupInterface $group, TokenInterface $token): bool
{
if ($this->decisionManager->decide($token, ['ROLE_GINGER_GROUP_EDIT'])) {
return true;
}
}
private function canDelete(GroupInterface $group, TokenInterface $token): bool
{
if ($this->decisionManager->decide($token, ['ROLE_GINGER_GROUP_DELETE'])) {
return true;
}
return false;
}
}