Skip to content

Commit

Permalink
Check coupon eligibility in validator
Browse files Browse the repository at this point in the history
  • Loading branch information
maximehuran committed Dec 20, 2023
1 parent ae33fac commit 9a937bb
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions src/Form/Extension/CartTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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)
*/
Expand Down Expand Up @@ -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()
;
}
}

/**
Expand Down

0 comments on commit 9a937bb

Please sign in to comment.