You are here

public function PromotionUsage::loadMultipleByCoupon in Commerce Core 8.2

Loads the usage for the given coupon.

The optional $mail parameter can be used to restrict the usage count to a specific customer email.

Parameters

\Drupal\commerce_promotion\Entity\CouponInterface[] $coupons: The coupons.

string $mail: (Optional) The customer email.

Return value

array The usage counts, keyed by promotion ID.

Overrides PromotionUsageInterface::loadMultipleByCoupon

1 call to PromotionUsage::loadMultipleByCoupon()
PromotionUsage::loadByCoupon in modules/promotion/src/PromotionUsage.php
Loads the usage for the given coupon.

File

modules/promotion/src/PromotionUsage.php, line 121

Class

PromotionUsage

Namespace

Drupal\commerce_promotion

Code

public function loadMultipleByCoupon(array $coupons, $mail = NULL) {
  if (empty($coupons)) {
    return [];
  }
  $coupon_ids = EntityHelper::extractIds($coupons);
  $query = $this->connection
    ->select('commerce_promotion_usage', 'cpu');
  $query
    ->addField('cpu', 'coupon_id');
  $query
    ->addExpression('COUNT(coupon_id)', 'count');
  $query
    ->condition('coupon_id', $coupon_ids, 'IN');
  if (!empty($mail)) {
    $query
      ->condition('mail', $mail);
  }
  $query
    ->groupBy('coupon_id');
  $result = $query
    ->execute()
    ->fetchAllAssoc('coupon_id', \PDO::FETCH_ASSOC);

  // Ensure that each coupon ID gets a count, even if it's not present
  // in the query due to non-existent usage.
  $counts = [];
  foreach ($coupon_ids as $coupon_id) {
    $counts[$coupon_id] = 0;
    if (isset($result[$coupon_id])) {
      $counts[$coupon_id] = $result[$coupon_id]['count'];
    }
  }
  return $counts;
}