<?php
namespace App\Security\Voter;
use App\Entity\Product;
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 ProductVoter 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 Product) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
if ( !$user instanceof User && $attribute !== self::VIEW ) {
return false;
}
/** @var Product $product */
$product = $subject;
if ($this->security->isGranted(User::ROLE_SUPER_ADMIN)) {
return true;
}
switch ($attribute) {
case self::VIEW:
return $this->canView($product);
case self::EDIT:
return $this->canEdit();
case self::DELETE:
return $this->canDelete();
case self::EVALUATE:
return $this->canEvaluate($product);
}
throw new \LogicException('This code should not be reached!');
}
private function canView(Product $product)
{
return (
($this->security->isGranted(User::ROLE_PRODUCT_ADMIN)) ||
($product->getStatus() == Product::STATUS_SHOW)
);
}
private function canEdit()
{
return $this->security->isGranted(User::ROLE_PRODUCT_ADMIN);
}
private function canDelete()
{
return $this->security->isGranted(User::ROLE_PRODUCT_ADMIN);
}
private function canEvaluate(Product $product)
{
return $product->getStatus() == Product::STATUS_SHOW;
}
}