You are here

public function InvoiceController::save in Commerce Invoice 7.2

File

src/Entity/InvoiceController.php, line 30
The entity controller for invoices.

Class

InvoiceController

Namespace

Drupal\commerce_invoice\Entity

Code

public function save($entity, \DatabaseTransaction $transaction = NULL) {

  /** @var Invoice $entity */
  if (empty($entity->created) || empty($entity->invoice_id)) {
    $entity->created = REQUEST_TIME;
  }
  if (empty($entity->changed)) {
    $entity->changed = REQUEST_TIME;
  }
  if (empty($entity->invoice_date)) {
    $entity->invoice_date = $entity->created;
  }

  // Default due date should be invoice_date + Net D x 24 x 60 x 60.
  if (empty($entity->invoice_due)) {
    $net_d = variable_get('commerce_invoice_net_d', 30);
    $entity->invoice_due = $entity->created + $net_d * 86400;
  }
  if (empty($entity->uid)) {
    if (!empty($entity->order_id) && !empty($entity
      ->wrapper()->order->owner)) {
      $entity->uid = $entity
        ->wrapper()->order->owner
        ->getIdentifier();
    }
    else {
      $entity->uid = $GLOBALS['user']->uid;
    }
  }
  if (!$entity
    ->hasInvoiceNumber()) {
    $pattern = $entity
      ->getNumberPattern();
    $lock_name = 'commerce_invoice_nr_' . $pattern->name;
    while (!lock_acquire($lock_name)) {
      lock_wait($lock_name);
    }
    $generator = new Generator($pattern);
    $transaction = isset($transaction) ? $transaction : db_transaction();
    $entity
      ->setInvoiceNumber($generator
      ->getNext($entity));
  }
  try {
    return parent::save($entity, $transaction);
  } finally {
    unset($transaction);

    // Always release the invoice number lock.
    if (isset($lock_name)) {
      lock_release($lock_name);
    }
  }
}