You are here

function uc_cart_user_login in Ubercart 8.4

Same name and namespace in other branches
  1. 7.3 uc_cart/uc_cart.module \uc_cart_user_login()

Implements hook_user_login().

Updates cart to include items from the user's anonymous session.

File

uc_cart/uc_cart.module, line 202
Handles all things concerning Ubercart's shopping cart.

Code

function uc_cart_user_login($account) {
  $session = \Drupal::service('session');
  if (!$session
    ->has('uc_cart_id')) {

    // No anonymous cart, so nothing to do here.
    return;
  }

  // If there are items in the anonymous cart, consolidate them.
  $cart_manager = \Drupal::service('uc_cart.manager');
  $anonymous_cart = $cart_manager
    ->get($session
    ->get('uc_cart_id'));
  if ($items = $anonymous_cart
    ->getContents()) {

    // Remove the anonymous cart items.
    $anonymous_cart
      ->emptyCart();

    // Merge the anonymous items into the user cart.
    $user_cart = $cart_manager
      ->get($account
      ->id());
    foreach ($items as $item) {
      $user_cart
        ->addItem($item->nid->target_id, $item->qty->value, $item->data
        ->first()
        ->toArray(), FALSE);
    }

    // Unset the anonymous cart ID, it's no longer needed.
    $session
      ->remove('uc_cart_id');
  }
}