You are here

public function CouponValidConstraintValidator::validate in Commerce Cart API 8

Throws

\Drupal\Core\TypedData\Exception\MissingDataException

File

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

Class

CouponValidConstraintValidator

Namespace

Drupal\commerce_cart_api\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, [
        '%code' => $coupon
          ->getCode(),
      ])
        ->atPath((string) $delta)
        ->addViolation();
    }
  }
}