You are here

public function Promotion::available in Commerce Core 8.2

Checks whether the promotion is available for the given order.

Ensures that the order type and store match the promotion's, that the promotion is enabled, the current date matches the start and end dates, and the usage limits are respected.

Parameters

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

Return value

bool TRUE if promotion is available, FALSE otherwise.

Overrides PromotionInterface::available

File

modules/promotion/src/Entity/Promotion.php, line 505

Class

Promotion
Defines the promotion entity class.

Namespace

Drupal\commerce_promotion\Entity

Code

public function available(OrderInterface $order) {
  if (!$this
    ->isEnabled()) {
    return FALSE;
  }
  if (!in_array($order
    ->bundle(), $this
    ->getOrderTypeIds())) {
    return FALSE;
  }
  if (!in_array($order
    ->getStoreId(), $this
    ->getStoreIds())) {
    return FALSE;
  }
  $date = $order
    ->getCalculationDate();
  $store_timezone = $date
    ->getTimezone()
    ->getName();
  $start_date = $this
    ->getStartDate($store_timezone);
  if ($start_date
    ->format('U') > $date
    ->format('U')) {
    return FALSE;
  }
  $end_date = $this
    ->getEndDate($store_timezone);
  if ($end_date && $end_date
    ->format('U') <= $date
    ->format('U')) {
    return FALSE;
  }
  $usage_limit = $this
    ->getUsageLimit();
  $usage_limit_customer = $this
    ->getCustomerUsageLimit();

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

  /** @var \Drupal\commerce_promotion\PromotionUsageInterface $usage */
  $usage = \Drupal::service('commerce_promotion.usage');
  if ($usage_limit && $usage_limit <= $usage
    ->load($this)) {
    return FALSE;
  }
  if ($usage_limit_customer) {

    // Promotion cannot apply to orders without email addresses.
    if (!($email = $order
      ->getEmail())) {
      return FALSE;
    }
    if ($usage_limit_customer <= $usage
      ->load($this, $email)) {
      return FALSE;
    }
  }
  return TRUE;
}