You are here

public function CouponValidConstraintValidator::validate in Commerce Core 8.2

File

modules/promotion/src/Plugin/Validation/Constraint/CouponValidConstraintValidator.php, line 19

Class

CouponValidConstraintValidator
Validates the CouponValid constraint.

Namespace

Drupal\commerce_promotion\Plugin\Validation\Constraint

Code

public function validate($value, Constraint $constraint) {
  assert($value instanceof EntityReferenceFieldItemListInterface);
  $order = $value
    ->getEntity();
  assert($order instanceof OrderInterface);

  // Only draft orders should be processed.
  if ($order
    ->getState()
    ->getId() !== 'draft') {
    return;
  }
  $coupons = $value
    ->referencedEntities();
  foreach ($coupons as $delta => $coupon) {
    assert($coupon instanceof CouponInterface);
    if (!$coupon
      ->available($order) || !$coupon
      ->getPromotion()
      ->applies($order)) {
      $this->context
        ->buildViolation($constraint->message)
        ->atPath($delta . '.target_id')
        ->setInvalidValue($coupon
        ->getCode())
        ->addViolation();
    }
  }
}