<?php
namespace App\Voters;
use App\Security\SecurityConfig;
use App\Security\User;
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 ProductVoter extends Voter
{
const PRODUCT_MANAGE_LIST = 'product_manage_list';
const PRODUCT_SHOW_LIST = 'product_show_list';
const PRODUCT_ADD_EDIT = 'product_add_edit';
const CATEGORY_ADD_EDIT = 'category_add_edit';
const PRODUCT_MANAGE_FIELDS = 'product_manage_fields';
/**
* @var Security
*/
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* @param $attribute
* @param $subject
*
* @return bool
*/
protected function supports($attribute, $subject): bool
{
return in_array($attribute, [
self::PRODUCT_MANAGE_LIST,
self::PRODUCT_SHOW_LIST,
self::PRODUCT_ADD_EDIT,
self::CATEGORY_ADD_EDIT,
self::PRODUCT_MANAGE_FIELDS,
], 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::PRODUCT_MANAGE_LIST:
return $this->canProductManageList();
case self::PRODUCT_SHOW_LIST:
return $this->canProductShowList();
case self::PRODUCT_ADD_EDIT:
return $this->canProductAddEdit();
case self::CATEGORY_ADD_EDIT:
return $this->canCategoryAddEdit();
case self::PRODUCT_MANAGE_FIELDS:
return $this->canProductManageFields();
}
throw new LogicException('This should never happen');
}
private function canProductManageList(): bool
{
return $this->canAccessModuleProduct();
}
private function canProductShowList(): bool
{
return $this->canAccessModuleProduct();
}
private function canProductAddEdit(): bool
{
return $this->canAccessModuleProduct();
}
private function canCategoryAddEdit(): bool
{
return $this->canAccessModuleProduct();
}
private function canProductManageFields(): bool
{
return $this->canAccessModuleProduct();
}
private function canAccessModuleProduct(): bool
{
return $this->security->isGranted(SecurityConfig::MODULE_PRODUCT);
}
}