You are here

function commerce_recurring_new_from_product in Commerce Recurring Framework 7.2

Generate a new recurring entity from a product. We set the price to the initial price from the line item if available. The start date for the recurring is the current date unless a set one is specified. Due date is start date + initial date. End date is optional, start date + end period.

Parameters

array $order: Commerce order to associate the recurring entity with.

array $product: Commerce product associated with the recurring entity.

int $fixed_price:

int $quantity:

Return value

entity $recurring_entity

2 calls to commerce_recurring_new_from_product()
CommerceRecurringTestCase::testCommerceRecurringEntityCreation in tests/commerce_recurring.test
Create a Recurring entity.
commerce_recurring_rules_generate_recurring_product in ./commerce_recurring.rules.inc
Generate the recurring entity using the product information.

File

./commerce_recurring.module, line 386
Commerce recurring module file.

Code

function commerce_recurring_new_from_product($order, $product, $fixed_price, $quantity) {
  if (empty($product)) {
    return;
  }
  $product_wrapper = entity_metadata_wrapper('commerce_product', $product);
  $date = new DateObject();
  $start_date = $date
    ->getTimestamp();
  $due_date = clone $date;
  if (!empty($product->commerce_recurring_ini_period)) {
    $initial_interval = $product_wrapper->commerce_recurring_ini_period
      ->value();
  }
  if (empty($initial_interval)) {
    if (!empty($product->commerce_recurring_rec_period)) {
      $initial_interval = $product_wrapper->commerce_recurring_rec_period
        ->value();
    }
  }
  if (!empty($initial_interval)) {
    interval_apply_interval($due_date, $initial_interval, TRUE);
  }
  $due_date = $due_date
    ->getTimestamp();
  if (!empty($product->commerce_recurring_end_period)) {
    $end_interval = $product_wrapper->commerce_recurring_end_period
      ->value();
    interval_apply_interval($date, $end_interval, TRUE);
    $end_date = $date
      ->getTimestamp();
  }
  $values = array(
    'product_id' => $product->product_id,
    'order_ids' => array(
      $order->order_id,
    ),
    'uid' => $order->uid,
    'start_date' => $start_date,
    'due_date' => $due_date,
    'end_date' => isset($end_date) ? $end_date : NULL,
  );
  $recurring_entity = commerce_recurring_new($values);

  // Add the price and quantity at the moment of purchase.
  if (!empty($fixed_price)) {
    $recurring_entity->commerce_recurring_fixed_price[LANGUAGE_NONE][0] = $fixed_price;
    $recurring_entity->quantity = empty($quantity) ? 1 : $quantity;
  }
  entity_save('commerce_recurring', $recurring_entity);
  return $recurring_entity;
}