<?php
declare(strict_types=1);
namespace App\Security;
use App\Entity\Product\Product;
use App\Entity\User\AdminUser;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ProductBatchVoter extends Voter
{
public const EDIT = 'product_batch_edit';
protected function supports(string $attribute, mixed $subject): bool
{
if ($attribute !== self::EDIT) {
return false;
}
return $subject instanceof Product;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (! $user instanceof AdminUser) {
return false;
}
/** @var Product $product */
$product = $subject;
return match ($attribute) {
self::EDIT => $this->canEditProductBatch($product, $user),
default => throw new LogicException('This code should not be reached!')
};
}
private function canEditProductBatch(Product $product, AdminUser $user): bool
{
// Super admins can always edit product batches
if ($user->hasRole('ROLE_SUPER_ADMIN')) {
return true;
}
// Check if user has the specific permission to edit product batches
return $user->hasPermission('product_batch_edit');
}
}