71 lines
2.2 KiB
PHP
71 lines
2.2 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace External\CykloSpecialityBundle\EventSubscriber;
|
|
|
|
use KupShop\OrderingBundle\Cart;
|
|
use KupShop\OrderingBundle\Event\CartEvent;
|
|
use KupShop\OrderingBundle\EventListener\CartEventListener;
|
|
use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
|
|
use Symfony\Component\HttpFoundation\RequestStack;
|
|
use Symfony\Contracts\Service\Attribute\Required;
|
|
|
|
class OrderCartSubscriber extends CartEventListener
|
|
{
|
|
protected RequestStack $requestStack;
|
|
|
|
#[Required]
|
|
public function setRequestStack(RequestStack $requestStack): void
|
|
{
|
|
$this->requestStack = $requestStack;
|
|
}
|
|
|
|
public function checkCoupons(CartEvent $event): void
|
|
{
|
|
$cart = $event->getCart();
|
|
$purchaseState = $cart->getPurchaseState();
|
|
|
|
foreach ($purchaseState->getDiscounts() as $discount) {
|
|
if ($couponPrice = $discount->getNote()['coupon_price']) {
|
|
$totalDiscountPrice = toDecimal($couponPrice);
|
|
|
|
if ($cart->totalPriceWithVat->lowerThan($totalDiscountPrice)) {
|
|
$coupon = $discount->getNote()['generated_coupon']['code'];
|
|
$this->deleteCoupon($cart, $coupon,
|
|
sprintf(translate('cart_coupon_failed_value', 'cyklospeciality'), $coupon, printPrice($totalDiscountPrice)));
|
|
}
|
|
}
|
|
}
|
|
|
|
parent::checkCoupons($event);
|
|
}
|
|
|
|
private function deleteCoupon(Cart $cart, string $coupon, ?string $deleteMessage = null): void
|
|
{
|
|
try {
|
|
$session = $this->requestStack->getSession();
|
|
} catch (SessionNotFoundException) {
|
|
return;
|
|
}
|
|
|
|
$messages = $session->getFlashBag()->peek('success');
|
|
foreach ($messages as $index => $message) {
|
|
if (str_starts_with((string) $message['id'], 'coupon')) {
|
|
unset($messages[$index]);
|
|
}
|
|
}
|
|
$session->getFlashBag()->set('success', $messages);
|
|
|
|
$cart->deleteCoupon(strtoupper($coupon));
|
|
|
|
addUserMessage(
|
|
$deleteMessage ?: sprintf(translate('cart_coupon_failed', 'cyklospeciality'), $coupon),
|
|
'warning',
|
|
[
|
|
'id' => 'coupons_'.$coupon,
|
|
],
|
|
);
|
|
}
|
|
}
|