modules/CDev/Coupons/src/API/EventSubscriber/Storefront/CouponAccessValidationEventSubscriber.php line 34

Open in your IDE?
  1. <?php
  2. /**
  3.  * Copyright (c) 2011-present Qualiteam software Ltd. All rights reserved.
  4.  * See https://www.x-cart.com/license-agreement.html for license details.
  5.  */
  6. namespace CDev\Coupons\API\EventSubscriber\Storefront;
  7. use ApiPlatform\Exception\InvalidArgumentException;
  8. use ApiPlatform\Exception\ItemNotFoundException;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\HttpKernel\Event\RequestEvent;
  11. use Symfony\Component\HttpKernel\KernelEvents;
  12. use CDev\Coupons\Model\UsedCoupon as CouponModel;
  13. use CDev\Coupons\Model\Repo\UsedCoupon as CouponRepository;
  14. class CouponAccessValidationEventSubscriber implements EventSubscriberInterface
  15. {
  16.     public function __construct(
  17.         private CouponRepository $couponRepository,
  18.     ) {
  19.     }
  20.     public static function getSubscribedEvents(): array
  21.     {
  22.         return [
  23.             KernelEvents::REQUEST => [
  24.                 ['checkCartCoupon'5],
  25.             ],
  26.         ];
  27.     }
  28.     public function checkCartCoupon(RequestEvent $event): void
  29.     {
  30.         if (!$event->isMainRequest() || $event->getRequest()->getMethod() === 'OPTIONS') {
  31.             return;
  32.         }
  33.         if (!preg_match('/api\/storefront\/carts\/[^\/]+\/coupons\/(\d+)/S'$event->getRequest()->getPathInfo(), $match)) {
  34.             return;
  35.         }
  36.         $couponId = (int) $match[1];
  37.         if ($couponId <= 0) {
  38.             throw new InvalidArgumentException('Coupon ID Must be positive numeric');
  39.         }
  40.         /** @var ?CouponModel $coupon */
  41.         $coupon $this->couponRepository->find($couponId);
  42.         if (!$coupon) {
  43.             throw new ItemNotFoundException('Coupon not found');
  44.         }
  45.         if ($coupon->getOrder()->getOrderId() !== $event->getRequest()->attributes->get('_cart')->getOrderId()) {
  46.             throw new ItemNotFoundException('Coupon not found in cart');
  47.         }
  48.     }
  49. }