You are here

public function InvoiceStorage::createFromOrder in Commerce Invoice 8.2

Creates an invoice and populates its values with the ones from the order.

Parameters

\Drupal\commerce_order\Entity\OrderInterface $order: An order entity.

array $values: (optional) An array of values to set, keyed by property name.

Return value

\Drupal\commerce_invoice\Entity\InvoiceInterface The created invoice.

File

src/InvoiceStorage.php, line 63

Class

InvoiceStorage

Namespace

Drupal\commerce_invoice

Code

public function createFromOrder(OrderInterface $order, array $values = []) {

  /** @var \Drupal\commerce_order\Entity\OrderTypeInterface $order_type */
  $order_type = OrderType::load($order
    ->bundle());
  $values += [
    'type' => $order_type
      ->getThirdPartySetting('commerce_invoice', 'invoice_type', 'default'),
    'state' => 'draft',
    'store_id' => $order
      ->getStoreId(),
    'mail' => $order
      ->getEmail(),
    'uid' => $order
      ->getCustomerId(),
    'billing_profile' => $order
      ->getBillingProfile(),
  ];
  if (!array_key_exists('payment_method', $values)) {
    if ($order
      ->hasField('payment_method') && !$order
      ->get('payment_method')
      ->isEmpty()) {
      if ($payment_method = $order
        ->get('payment_method')->entity) {
        $values['payment_method'] = $payment_method
          ->label();
      }
    }
    elseif ($order
      ->hasField('payment_gateway') && !$order
      ->get('payment_gateway')
      ->isEmpty()) {
      if ($payment_gateway = $order
        ->get('payment_gateway')->entity) {
        $values['payment_method'] = $payment_gateway
          ->label();
      }
    }
  }

  /** @var \Drupal\commerce_invoice\Entity\InvoiceInterface $invoice */
  $invoice = parent::create($values);

  // If the invoice type is configured to do so, generate the translations
  // for all the available languages.
  if ($this->moduleHandler
    ->moduleExists('language')) {
    $config = ContentLanguageSettings::loadByEntityTypeBundle('commerce_invoice', $invoice
      ->bundle());
    if ($config && $config
      ->getThirdPartySetting('commerce_invoice', 'generate_translations', FALSE)) {
      $languages = $this->languageManager
        ->getLanguages();
      foreach ($languages as $langcode => $language) {
        if ($invoice
          ->hasTranslation($langcode)) {
          continue;
        }

        // Currently, only the data field is translatable on invoices, we
        // store the invoice type data there and make sure the translated data
        // is stored inside Invoice::presave().
        $invoice
          ->addTranslation($langcode, $invoice
          ->toArray());
      }
    }
  }
  return $invoice;
}