You are here

public function CartProvider::createCart in Commerce Core 8.2

Creates a cart order for the given store and user.

Parameters

string $order_type: The order type ID.

\Drupal\commerce_store\Entity\StoreInterface $store: The store. If empty, the current store is assumed.

\Drupal\Core\Session\AccountInterface $account: The user. If empty, the current user is assumed.

Return value

\Drupal\commerce_order\Entity\OrderInterface The created cart order.

Throws

\Drupal\commerce_cart\Exception\DuplicateCartException When a cart with the given criteria already exists.

Overrides CartProviderInterface::createCart

File

modules/cart/src/CartProvider.php, line 78

Class

CartProvider
Default implementation of the cart provider.

Namespace

Drupal\commerce_cart

Code

public function createCart($order_type, StoreInterface $store = NULL, AccountInterface $account = NULL) {
  $store = $store ?: $this->currentStore
    ->getStore();
  $account = $account ?: $this->currentUser;
  $uid = $account
    ->id();
  $store_id = $store
    ->id();
  if ($this
    ->getCartId($order_type, $store, $account)) {

    // Don't allow multiple cart orders matching the same criteria.
    throw new DuplicateCartException("A cart order for type '{$order_type}', store '{$store_id}' and account '{$uid}' already exists.");
  }

  // Create the new cart order.
  $cart = $this->orderStorage
    ->create([
    'type' => $order_type,
    'store_id' => $store_id,
    'uid' => $uid,
    'cart' => TRUE,
  ]);
  $cart
    ->save();

  // Store the new cart order id in the anonymous user's session so that it
  // can be retrieved on the next page load.
  if ($account
    ->isAnonymous()) {
    $this->cartSession
      ->addCartId($cart
      ->id());
  }

  // Cart data has already been loaded, add the new cart order to the list.
  if (isset($this->cartData[$uid])) {
    $this->cartData[$uid][$cart
      ->id()] = [
      'type' => $order_type,
      'store_id' => $store_id,
    ];
  }
  return $cart;
}