src/Security/Voter/CartVoter.php line 15

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Security\Voter;
  4. use App\Entity\Cart;
  5. use App\Entity\User;
  6. use App\Manager\CartManager;
  7. use Symfony\Component\HttpFoundation\RequestStack;
  8. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  9. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  10. use Symfony\Component\Security\Core\Security;
  11. class CartVoter extends Voter
  12. {
  13.     private Security $securityChecker;
  14.     private CartManager $cartManager;
  15.     private RequestStack $requestStack;
  16.     /**
  17.      * CartVoter constructor.
  18.      * @param Security $securityChecker
  19.      * @param CartManager $cartManager
  20.      * @param RequestStack $requestStack
  21.      */
  22.     public function __construct(Security $securityCheckerCartManager $cartManagerRequestStack $requestStack)
  23.     {
  24.         $this->securityChecker $securityChecker;
  25.         $this->cartManager $cartManager;
  26.         $this->requestStack $requestStack;
  27.     }
  28.     protected function supports(string $attribute$subject): bool
  29.     {
  30.         return \in_array(
  31.                 $attribute,
  32.                 ['CART_VIEW''CART_VIEW_EXTRA''CART_NOT_EXPIRED'],
  33.                 true
  34.             ) && $subject instanceof Cart;
  35.     }
  36.     /**
  37.      * @param string $attribute
  38.      * @param Cart $subject
  39.      * @param TokenInterface $token
  40.      * @return bool
  41.      */
  42.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  43.     {
  44.         if ($attribute === 'CART_VIEW_EXTRA') {
  45.             if ($subject->isPaymentLink()) {
  46.                 return true;
  47.             }
  48.             $attribute 'CART_VIEW';
  49.         }
  50.         if ($attribute === 'CART_VIEW') {
  51.             if ($this->securityChecker->isGranted('ROLE_ORDER_WRITE')) {
  52.                 return true;
  53.             }
  54.             if ($subject->getAnonymousKey() === null) {
  55.                 if ($this->securityChecker->isGranted('ROLE_CUSTOMER')) {
  56.                     /** @var User $user */
  57.                     $user $token->getUser();
  58.                     return $subject->getUser()->getId()->toString() === $user->getId()->toString();
  59.                 }
  60.             } else {
  61.                 return $subject->getAnonymousKey() === $this->requestStack->getCurrentRequest()->headers
  62.                         ->get('Guest-Token'$this->cartManager->genAnonymousKey());
  63.             }
  64.         }
  65.         if ($attribute === 'CART_NOT_EXPIRED') {
  66.             return $subject->getExpiresOn() > new \DateTimeImmutable();
  67.         }
  68.         return false;
  69.     }
  70. }