<?php
namespace App\Security\Voter;
use App\Entity\Product;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
class ProductVoter extends Voter
{
public const EDIT = 'product_edit';
public function __construct(
private Security $security,
) {
}
protected function supports(string $attribute, mixed $subject): bool
{
return $attribute == self::EDIT && $subject instanceof Product;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
/** @var Product $product */
$product = $subject;
if ($product->getUser() === $user
|| $this->security->isGranted('ROLE_ADMIN')
) {
return true;
}
return false;
}
}