<?php
declare(strict_types=1);
namespace App\Security\Blo;
use App\Entity\Blo\Product;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ProductVoter extends Voter
{
public const VIEW = 'blo_product_view';
public const EDIT = 'blo_product_edit';
public const DELETE = 'blo_product_delete';
protected function supports(string $attribute, mixed $subject): bool
{
return $subject instanceof Product
&& \in_array($attribute, [self::VIEW, self::EDIT, self::DELETE], true);
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
/** @var Product $product */
$product = $subject;
return match ($attribute) {
self::VIEW => $this->canView($product, $user),
self::EDIT, self::DELETE => $this->canEdit($product, $user),
default => false,
};
}
private function canView(Product $product, User $user): bool
{
if ($product->getStatus() === Product::STATUS_APPROVED) {
return true;
}
return $this->canEdit($product, $user);
}
private function canEdit(Product $product, User $user): bool
{
if (\in_array('ROLE_ADMIN', $user->getRoles(), true)) {
return true;
}
if (\in_array('ROLE_VENDOR', $user->getRoles(), true)) {
$shop = $product->getShop();
return $shop && $shop->getOwner() === $user;
}
return false;
}
}