protected function manageCartDuplicationAtCustomerLogin(CartModel $cart, EventDispatcherInterface $dispatcher) { /** @var CustomerModel $customer */ if (null !== ($customer = $this->session->getCustomerUser())) { // Check if we have to duplicate the existing cart. $duplicateCart = true; // A customer is logged in. if (null === $cart->getCustomerId()) { // If the customer has a discount, whe have to duplicate the cart, // so that the discount will be applied to the products in cart. if (0 === $customer->getDiscount() || 0 === $cart->countCartItems()) { // If no discount, or an empty cart, there's no need to duplicate. $duplicateCart = false; } } if ($duplicateCart) { // Duplicate the cart $cart = $this->duplicateCart($dispatcher, $cart, $customer); } else { // No duplication required, just assign the cart to the customer $cart->setCustomerId($customer->getId())->save(); } } elseif ($cart->getCustomerId() != null) { // The cart belongs to another user if (0 === $cart->countCartItems()) { // No items in cart, assign it to nobody. $cart->setCustomerId(null)->save(); } else { // Some itemls in cart, duplicate it without assigning a customer ID. $cart = $this->duplicateCart($dispatcher, $cart); } } return $cart; }