<?php
/**
* Copyright (c) 2011-present Qualiteam software Ltd. All rights reserved.
* See https://www.x-cart.com/license-agreement.html for license details.
*/
namespace CDev\Coupons\API\EventSubscriber\Storefront;
use ApiPlatform\Exception\InvalidArgumentException;
use ApiPlatform\Exception\ItemNotFoundException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use CDev\Coupons\Model\UsedCoupon as CouponModel;
use CDev\Coupons\Model\Repo\UsedCoupon as CouponRepository;
class CouponAccessValidationEventSubscriber implements EventSubscriberInterface
{
public function __construct(
private CouponRepository $couponRepository,
) {
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [
['checkCartCoupon', 5],
],
];
}
public function checkCartCoupon(RequestEvent $event): void
{
if (!$event->isMainRequest() || $event->getRequest()->getMethod() === 'OPTIONS') {
return;
}
if (!preg_match('/api\/storefront\/carts\/[^\/]+\/coupons\/(\d+)/S', $event->getRequest()->getPathInfo(), $match)) {
return;
}
$couponId = (int) $match[1];
if ($couponId <= 0) {
throw new InvalidArgumentException('Coupon ID Must be positive numeric');
}
/** @var ?CouponModel $coupon */
$coupon = $this->couponRepository->find($couponId);
if (!$coupon) {
throw new ItemNotFoundException('Coupon not found');
}
if ($coupon->getOrder()->getOrderId() !== $event->getRequest()->attributes->get('_cart')->getOrderId()) {
throw new ItemNotFoundException('Coupon not found in cart');
}
}
}