<?php
namespace App\V4\Voters;
use App\Security\User;
use App\V4\Model\Tab\Tab;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class TabVoter extends Voter
{
const TAB_MANAGE_LIST = 'tab_manage_list';
const TAB_SHOW_LIST = 'tab_show_list';
const TAB_SHOW_LIST_ADMIN = 'tab_show_list_admin';
const TAB_ADD_EDIT = 'tab_add_edit';
const TAB_SHOW = 'tab_show';
const TAB_SHOW_ADMIN = 'tab_show_admin';
/**
* @var Security
*/
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* @param $attribute
* @param $subject
*
* @return bool
*/
protected function supports($attribute, $subject): bool
{
if ($subject instanceof Tab && in_array($attribute, [
self::TAB_SHOW,
self::TAB_SHOW_ADMIN,
], true)) {
return true;
}
return in_array($attribute, [
self::TAB_MANAGE_LIST,
self::TAB_SHOW_LIST,
self::TAB_SHOW_LIST_ADMIN,
self::TAB_ADD_EDIT,
], true);
}
/**
* @param $attribute
* @param $subject
* @param TokenInterface $token
*
* @return bool
*
* @throws LogicException
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
switch ($attribute) {
case self::TAB_MANAGE_LIST:
return $this->canTabManageList();
case self::TAB_SHOW_LIST:
return $this->canTabShowList();
case self::TAB_SHOW_LIST_ADMIN:
return $this->canTabShowListAdmin($user);
case self::TAB_ADD_EDIT:
return $this->canTabAddEdit();
case self::TAB_SHOW:
return $this->canAccessTab($user, $subject);
case self::TAB_SHOW_ADMIN:
return $this->canAccessTabAdmin($user, $subject);
}
throw new LogicException('This should never happen');
}
/**
* @return bool
*/
private function canTabManageList(): bool
{
return true;
}
/**
* @return bool
*/
private function canTabShowList(): bool
{
return true;
}
/**
* @param User $user
*
* @return bool
*/
private function canTabShowListAdmin(User $user): bool
{
return $user->isAdmin();
}
/**
* @return bool
*/
private function canTabAddEdit(): bool
{
return true;
}
/**
* @param User $user
* @param Tab $tab
*
* @return bool
*/
private function canAccessTab(User $user, Tab $tab): bool
{
return null === $tab->getRole() || in_array($tab->getRole(), $user->getRoles(), true);
}
/**
* @param User $user
* @param Tab $tab
*
* @return bool
*/
private function canAccessTabAdmin(User $user, Tab $tab): bool
{
return $user->isAdmin();
}
}