<?php
namespace App\Security\Voter;
use App\Entity\PurchaseItemEtsy;
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 PurchaseItemEtsyVoter extends Voter
{
public const EDIT = 'purchase_item_etsy_edit';
public function __construct(
private Security $security,
) {
}
protected function supports(string $attribute, mixed $subject): bool
{
return $attribute == self::EDIT && $subject instanceof PurchaseItemEtsy;
}
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 PurchaseItemEtsy $purchase */
$purchase = $subject;
if ($purchase->getPurchase()->getUserStore()->getUser() === $user
|| $this->security->isGranted('ROLE_ADMIN')
) {
return true;
}
return false;
}
}