Skip to content

Commit

Permalink
Manage coupon delete on order if field is empty
Browse files Browse the repository at this point in the history
  • Loading branch information
maximehuran committed Dec 18, 2023
1 parent 7fdbc96 commit 81de712
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/Form/Extension/CartTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,15 @@

namespace MonsieurBiz\SyliusAdvancedPromotionPlugin\Form\Extension;

use MonsieurBiz\SyliusAdvancedPromotionPlugin\Entity\PromotionCouponsAwareInterface;
use Sylius\Bundle\OrderBundle\Form\Type\CartType;
use Sylius\Bundle\PromotionBundle\Form\Type\PromotionCouponToCodeType;
use Sylius\Component\Core\Model\PromotionCouponInterface;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
Expand Down Expand Up @@ -52,6 +55,7 @@ public function buildForm(FormBuilderInterface $builder, array $options): void
'class' => 'monsieurbiz-coupons',
],
])
->addEventListener(FormEvents::PRE_SUBMIT, [$this, 'removeEmptyCouponsOnPreSubmit'])
;
}

Expand All @@ -67,6 +71,34 @@ public function validatePromotionEntry(?PromotionCouponInterface $entry, Executi
;
}

/**
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function removeEmptyCouponsOnPreSubmit(FormEvent $event): void
{
$formData = $event->getData();
if (!\is_array($formData)) {
return;
}

$promotionCoupons = $formData['promotionCoupons'] ?? [];
if (!empty($promotionCoupons)) {
return;
}

$order = $event->getForm()->getNormData();
if (!$order instanceof PromotionCouponsAwareInterface) {
return;
}

foreach ($order->getPromotionCoupons() as $promotionCoupon) {
if (!$promotionCoupon) {
continue;
}
$order->removePromotionCoupon($promotionCoupon);
}
}

/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
Expand Down

0 comments on commit 81de712

Please sign in to comment.