From 9a937bb196f27549c87a175d8448e72b0212c60d Mon Sep 17 00:00:00 2001 From: Maxime Huran Date: Wed, 20 Dec 2023 11:42:50 +0100 Subject: [PATCH] Check coupon eligibility in validator --- src/Form/Extension/CartTypeExtension.php | 31 ++++++++++++++++++++---- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/src/Form/Extension/CartTypeExtension.php b/src/Form/Extension/CartTypeExtension.php index e7f99b5..457b961 100644 --- a/src/Form/Extension/CartTypeExtension.php +++ b/src/Form/Extension/CartTypeExtension.php @@ -14,7 +14,11 @@ use MonsieurBiz\SyliusAdvancedPromotionPlugin\Entity\PromotionCouponsAwareInterface; use Sylius\Bundle\OrderBundle\Form\Type\CartType; use Sylius\Bundle\PromotionBundle\Form\Type\PromotionCouponToCodeType; +use Sylius\Component\Core\Model\OrderInterface; use Sylius\Component\Core\Model\PromotionCouponInterface; +use Sylius\Component\Order\Context\CartContextInterface; +use Sylius\Component\Promotion\Checker\Eligibility\PromotionEligibilityCheckerInterface; +use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\Form\Extension\Core\Type\CollectionType; use Symfony\Component\Form\FormBuilderInterface; @@ -28,6 +32,13 @@ final class CartTypeExtension extends AbstractTypeExtension { + public function __construct( + #[Autowire('@sylius.promotion_eligibility_checker')] + private PromotionEligibilityCheckerInterface $promotionEligibilityChecker, + private CartContextInterface $cartContext + ) { + } + /** * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ @@ -61,14 +72,24 @@ public function buildForm(FormBuilderInterface $builder, array $options): void public function validatePromotionEntry(?PromotionCouponInterface $entry, ExecutionContextInterface $context): void { - if (null !== $entry) { + if (null === $entry || null === ($promotion = $entry->getPromotion())) { + $context + ->buildViolation('sylius.promotion_coupon.is_invalid') + ->addViolation() + ; + return; } - $context - ->buildViolation('sylius.promotion_coupon.is_invalid') - ->addViolation() - ; + // Check if the promotion rule is eligible + /** @var OrderInterface $order */ + $order = $this->cartContext->getCart(); + if (!$this->promotionEligibilityChecker->isEligible($order, $promotion)) { + $context + ->buildViolation('sylius.promotion_coupon.is_invalid') + ->addViolation() + ; + } } /**