You are here

public function CommerceLineItemEntityController::save in Commerce Core 7

Saves a line item.

Parameters

$line_item: The full line item object to save.

$transaction: An optional transaction object.

Return value

SAVED_NEW or SAVED_UPDATED depending on the operation performed.

Overrides DrupalCommerceEntityController::save

File

modules/line_item/includes/commerce_line_item.controller.inc, line 49
The controller for the line item entity containing the CRUD operations.

Class

CommerceLineItemEntityController
The controller class for line items contains methods for the line item CRUD operations. The load method is inherited from the default controller.

Code

public function save($line_item, DatabaseTransaction $transaction = NULL) {
  if (!isset($transaction)) {
    $transaction = db_transaction();
    $started_transaction = TRUE;
  }
  $wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
  try {

    // Set the timestamp fields.
    if (empty($line_item->line_item_id) && empty($line_item->created)) {
      $line_item->created = REQUEST_TIME;
    }
    else {

      // Otherwise if the line item is not new but comes from an entity_create()
      // or similar function call that initializes the created timestamp to an
      // empty string, unset it to prevent destroying existing data in that
      // property on update.
      if ($line_item->created === '') {
        unset($line_item->created);
      }
    }
    $line_item->changed = REQUEST_TIME;

    // Update the total of the line item based on the quantity and unit price.
    $unit_price = commerce_price_wrapper_value($wrapper, 'commerce_unit_price', TRUE);
    $wrapper->commerce_total->amount = $line_item->quantity * $unit_price['amount'];
    $wrapper->commerce_total->currency_code = $unit_price['currency_code'];

    // Add the components multiplied by the quantity to the data array.
    if (empty($unit_price['data']['components'])) {
      $unit_price['data']['components'] = array();
    }
    else {
      foreach ($unit_price['data']['components'] as $key => &$component) {
        $component['price']['amount'] *= $line_item->quantity;
      }
    }

    // Set the updated data array to the total price.
    $wrapper->commerce_total->data = $unit_price['data'];
    return parent::save($line_item, $transaction);
  } catch (Exception $e) {
    if (!empty($started_transaction)) {
      $transaction
        ->rollback();
      watchdog_exception($this->entityType, $e);
    }
    throw $e;
  }
}