<?php
namespace App\Security\Voter;
use App\Entity\ProductShop;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class ProductShopVoter extends Voter
{
const VIEW = 'view';
const EDIT = 'edit';
const DELETE = 'delete';
const EVALUATE = 'evaluate';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject)
{
if (!in_array($attribute, [self::VIEW, self::EDIT, self::DELETE, self::EVALUATE])) {
return false;
}
if (!$subject instanceof ProductShop) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
/** @var ProductShop $productShop */
$productShop = $subject;
if ($this->security->isGranted(User::ROLE_SUPER_ADMIN)) {
return true;
}
switch ($attribute) {
case self::VIEW:
return $this->canView($productShop, $user, $token);
case self::EDIT:
return $this->canEdit($productShop, $user, $token);
case self::DELETE:
return $this->canDelete($productShop, $user, $token);
case self::EVALUATE:
return $this->canEvaluate($productShop, $user, $token);
}
throw new \LogicException('This code should not be reached!');
}
private function canView(ProductShop $productShop, User $user = null, TokenInterface $token = null)
{
return (
($this->security->isGranted(User::ROLE_PRODUCT_ADMIN)) ||
($productShop->getStatus() == ProductShop::STATUS_SHOW)
);
}
private function canEdit(ProductShop $productShop, User $user, TokenInterface $token)
{
return $this->security->isGranted(User::ROLE_PRODUCT_ADMIN);
}
private function canDelete(ProductShop $productShop, User $user, TokenInterface $token)
{
return $this->security->isGranted(User::ROLE_PRODUCT_ADMIN);
}
private function canEvaluate(ProductShop $productShop, User $user, TokenInterface $token)
{
return $productShop->getStatus() == ProductShop::STATUS_SHOW;
}
}