You are here

function commerce_coupon_get_discount_properties in Commerce Coupon 7.2

Entity metadata getter: coupon properties on discounts.

1 string reference to 'commerce_coupon_get_discount_properties'
commerce_coupon_entity_property_info_alter in ./commerce_coupon.info.inc
Implements hook_entity_property_info_alter().

File

./commerce_coupon.module, line 654
Provides coupon functionality for Drupal Commerce.

Code

function commerce_coupon_get_discount_properties($discount, $options, $name) {
  switch ($name) {
    case 'coupons':
      if (!empty($discount->discount_id)) {

        // Load coupons that reference this discount.
        $query = new EntityFieldQuery();
        $results = $query
          ->entityCondition('entity_type', 'commerce_coupon')
          ->fieldCondition('commerce_discount_reference', 'target_id', $discount->discount_id)
          ->execute();
        if (isset($results['commerce_coupon'])) {
          return array_keys($results['commerce_coupon']);
        }
      }
      return array();
    case 'coupon_count':
      if (!empty($discount->discount_id)) {

        // First, look for a value in the cache.
        $cid = 'discount_coupon_count_' . $discount->discount_id;
        $cache = cache_get($cid);
        if (!empty($cache)) {
          return (int) $cache->data;
        }

        // If nothing has been cached, run the query. NOTE: when EFQ tries to
        // put an equivalent query together, it ends up super slow, so we use
        // db_select and joins here. It still is not particularly quick.
        $query = db_select('commerce_coupon', 'c')
          ->fields('c', array(
          'coupon_id',
        ));
        $query
          ->join('field_data_commerce_discount_reference', 'd', 'c.coupon_id=d.entity_id');
        $query
          ->condition('d.commerce_discount_reference_target_id', $discount->discount_id)
          ->condition('d.deleted', 0)
          ->condition('d.entity_type', 'commerce_coupon');
        $value = (int) $query
          ->countQuery()
          ->execute()
          ->fetchField();

        // Set cache to speed up next call.
        cache_set($cid, $value);
        return $value;
      }
      return 0;
  }
}