You are here

function commerce_gc_product_line_item_generate_giftcard in Commerce GC 7

File

modules/commerce_gc_product/commerce_gc_product.rules.inc, line 113
Provides Rules module support for buying giftcards.

Code

function commerce_gc_product_line_item_generate_giftcard(EntityDrupalWrapper $line_item_wrapper) {
  $coupon = commerce_coupon_create('giftcard_coupon');
  $coupon_wrapper = entity_metadata_wrapper('commerce_coupon', $coupon);

  // Get the value of the giftcard product.
  $coupon_wrapper->commerce_gc_value = $line_item_wrapper->commerce_product->commerce_gc_value
    ->value();

  // Use the product title as the giftcard name.
  $coupon_wrapper->commerce_gc_name = $line_item_wrapper->commerce_product->title
    ->value();

  // Generate a code and save.
  $coupon->code = commerce_coupon_generate_coupon_code('giftcard_coupon');

  // Allow other modules to alter the coupon before it is saved as a giftcard.
  drupal_alter('commerce_gc_product_giftcard_coupon_presave', $coupon_wrapper, $line_item_wrapper);
  commerce_coupon_save($coupon);

  // Record a reference to this coupon on the line item.
  $line_item_wrapper->commerce_giftcards[] = $coupon;
  $line_item_wrapper
    ->save();
  return array(
    'giftcard_coupon' => $coupon,
  );
}