<?php
namespace App\Security\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use App\Entity\PurchaseItem;
class PurchaseItemVoter extends Voter
{
const ROLE_SUPER = 'ROLE_ADMIN';
const ROLE_ALL = 'ROLE_PURCHASE';
const ROLE_CREATE = 'ROLE_PURCHASE_CREATE';
const ROLE_SHOW = 'ROLE_USER';
const ROLE_EDIT = 'ROLE_PURCHASE_EDIT';
const ROLE_DELETE = 'ROLE_PURCHASE_DELETE';
const GRANT_CREATE = 'create';
const GRANT_SHOW = 'show';
const GRANT_EDIT = 'edit';
const GRANT_DELETE = 'delete';
private $decisionManager;
public function __construct(AccessDecisionManagerInterface $decisionManager)
{
$this->decisionManager = $decisionManager;
}
protected function supports($attribute, $subject)
{
return $subject instanceof PurchaseItem && in_array($attribute, [self::GRANT_SHOW, self::GRANT_CREATE, self::GRANT_EDIT, self::GRANT_DELETE], true);
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
// ROLE_SUPER_ADMIN can do anything! The power!
if ($this->decisionManager->decide($token, array(static::ROLE_SUPER))) {
return true;
}
$user = $token->getUser();
switch ($attribute) {
case self::GRANT_CREATE:
return $this->canCreate($user, $subject);
case self::GRANT_SHOW:
return $this->canShow($user, $subject);
case self::GRANT_EDIT:
return $this->canEdit($user, $subject);
case self::GRANT_DELETE:
return $this->canDelete($user, $subject);
}
throw new \LogicException('This code should not be reached!');
}
private function canDoAll($user, $subject)
{
if ($user->hasRole(static::ROLE_ALL)) {
return true;
}
return false;
}
private function canCreate($user, $subject)
{
// if they can do all, they can edit
if ($this->canDoAll($user, $subject)) {
return true;
}
if ($user->hasRole(static::ROLE_CREATE)) {
return true;
}
return false;
}
private function canShow($user, $subject)
{
// if they can do all, they can show
if ($this->canDoAll($user, $subject)) {
return true;
}
if ($user->hasRole(static::ROLE_SHOW)) {
return true;
}
return false;
}
private function canEdit($user, $subject)
{
// if they can do all, they can edit
if ($this->canDoAll($user, $subject)) {
return true;
}
if ($user->hasRole(static::ROLE_EDIT)) {
return true;
}
return false;
}
private function canDelete($user, $subject)
{
// if they can do all, they can delete
if ($this->canDoAll($user, $subject)) {
return true;
}
if ($user->hasRole(static::ROLE_DELETE)) {
return true;
}
return false;
}
}