<?php
declare(strict_types=1);
namespace App\Security\Voter;
use App\Entity\Cart;
use App\Entity\User;
use App\Manager\CartManager;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class CartVoter extends Voter
{
private Security $securityChecker;
private CartManager $cartManager;
private RequestStack $requestStack;
/**
* CartVoter constructor.
* @param Security $securityChecker
* @param CartManager $cartManager
* @param RequestStack $requestStack
*/
public function __construct(Security $securityChecker, CartManager $cartManager, RequestStack $requestStack)
{
$this->securityChecker = $securityChecker;
$this->cartManager = $cartManager;
$this->requestStack = $requestStack;
}
protected function supports(string $attribute, $subject): bool
{
return \in_array(
$attribute,
['CART_VIEW', 'CART_VIEW_EXTRA', 'CART_NOT_EXPIRED'],
true
) && $subject instanceof Cart;
}
/**
* @param string $attribute
* @param Cart $subject
* @param TokenInterface $token
* @return bool
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
if ($attribute === 'CART_VIEW_EXTRA') {
if ($subject->isPaymentLink()) {
return true;
}
$attribute = 'CART_VIEW';
}
if ($attribute === 'CART_VIEW') {
if ($this->securityChecker->isGranted('ROLE_ORDER_WRITE')) {
return true;
}
if ($subject->getAnonymousKey() === null) {
if ($this->securityChecker->isGranted('ROLE_CUSTOMER')) {
/** @var User $user */
$user = $token->getUser();
return $subject->getUser()->getId()->toString() === $user->getId()->toString();
}
} else {
return $subject->getAnonymousKey() === $this->requestStack->getCurrentRequest()->headers
->get('Guest-Token', $this->cartManager->genAnonymousKey());
}
}
if ($attribute === 'CART_NOT_EXPIRED') {
return $subject->getExpiresOn() > new \DateTimeImmutable();
}
return false;
}
}