You are here

public function PromotionUsage::loadMultiple in Commerce Core 8.2

Loads the usage for the given promotions.

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

Parameters

\Drupal\commerce_promotion\Entity\PromotionInterface[] $promotions: The promotions.

string $mail: (Optional) The customer email.

Return value

array The usage counts, keyed by promotion ID.

Overrides PromotionUsageInterface::loadMultiple

1 call to PromotionUsage::loadMultiple()
PromotionUsage::load in modules/promotion/src/PromotionUsage.php
Loads the usage for the given promotion.

File

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

Class

PromotionUsage

Namespace

Drupal\commerce_promotion

Code

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

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