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