You are here

public function Coupon::available in Commerce Core 8.2

Checks whether the coupon is available for the given order.

Ensures that the parent promotion is available, the coupon is enabled, and the usage limits are respected.

Parameters

\Drupal\commerce_order\Entity\OrderInterface $order: The order.

Return value

bool TRUE if coupon is available, FALSE otherwise.

Overrides CouponInterface::available

File

modules/promotion/src/Entity/Coupon.php, line 167

Class

Coupon
Defines the Coupon entity.

Namespace

Drupal\commerce_promotion\Entity

Code

public function available(OrderInterface $order) {
  if (!$this
    ->isEnabled()) {
    return FALSE;
  }
  if (!$this
    ->getPromotion()
    ->available($order)) {
    return FALSE;
  }
  $usage_limit = $this
    ->getUsageLimit();
  $usage_limit_customer = $this
    ->getCustomerUsageLimit();

  // If there are no usage limits, the coupon is available.
  if (!$usage_limit && !$usage_limit_customer) {
    return TRUE;
  }

  /** @var \Drupal\commerce_promotion\PromotionUsageInterface $usage */
  $usage = \Drupal::service('commerce_promotion.usage');

  // Check the global usage limit fist.
  if ($usage_limit && $usage_limit <= $usage
    ->loadByCoupon($this)) {
    return FALSE;
  }

  // Only check customer usage when email address is known.
  if ($usage_limit_customer) {
    $email = $order
      ->getEmail();
    if ($email && $usage_limit_customer <= $usage
      ->loadByCoupon($this, $email)) {
      return FALSE;
    }
  }
  return TRUE;
}