You are here

function commerce_license_commerce_line_item_presave in Commerce License 7

Implements hook_commerce_line_item_presave().

Ensures that each saved line item has a matching license with the correct product id.

File

./commerce_license.module, line 373
Provides a framework for selling access to local or remote resources.

Code

function commerce_license_commerce_line_item_presave($line_item) {

  // This is not a license line item type, stop here.
  if (!in_array($line_item->type, commerce_license_line_item_types())) {
    return;
  }
  $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
  $product = $line_item_wrapper->commerce_product
    ->value();

  // The line item has a license, maintain its product_id value.
  if (!empty($line_item->commerce_license) && $line_item_wrapper->commerce_license
    ->value()) {
    $license = $line_item_wrapper->commerce_license
      ->value();
    if (empty($license->product_id) || $license->product_id != $product->product_id) {
      $license->product_id = $line_item_wrapper->commerce_product->product_id
        ->value();
      $license
        ->save();
    }
  }

  // The line item has no license, create it if the product is licensable.
  if (empty($line_item->commerce_license) && !empty($product->commerce_license_type)) {
    $uid = $GLOBALS['user']->uid;
    if (!empty($line_item->order_id)) {

      // Use the uid associated with the order whenever available, this allows
      // the admin to add a license for another user.
      $order = commerce_order_load($line_item->order_id);
      $uid = $order->uid;
    }

    // Ship some initial values to the entity controller. We pass in the
    // responsible order and line item here for context, because the line item
    // doesn't have its own reference to the license until after the license is
    // created. These properties (order and line_item) are ultimately not saved.
    $values = array(
      'type' => $line_item_wrapper->commerce_product->commerce_license_type
        ->value(),
      'uid' => $uid,
      'product_id' => $line_item_wrapper->commerce_product->product_id
        ->value(),
      'line_item' => $line_item_wrapper
        ->value(),
      'order' => $line_item_wrapper->order
        ->value(),
    );
    $license = entity_create('commerce_license', $values);
    $license
      ->save();
    $line_item_wrapper->commerce_license = $license;
  }
}