You are here

public function CartHandler::addOrUpdateCart in Mailchimp E-Commerce 8

@inheritdoc

Overrides CartHandlerInterface::addOrUpdateCart

File

src/CartHandler.php, line 93

Class

CartHandler
Cart handler.

Namespace

Drupal\mailchimp_ecommerce

Code

public function addOrUpdateCart($cart_id, array $customer, array $cart) {
  try {
    $store_id = $this->helper
      ->getStoreId();
    if (empty($store_id)) {
      throw new \Exception('Cannot add a cart without a store ID.');
    }
    if (!$this->helper
      ->validateCustomer($customer)) {

      // A user not existing in the store's Mailchimp list/audience is not an error, so
      // don't throw an exception.
      return;
    }

    // Get the Mailchimp campaign ID, if available.
    $campaign_id = $this->helper
      ->getCampaignId();
    if (!empty($campaign_id)) {
      $cart['campaign_id'] = $campaign_id;
      $cart['landing_site'] = isset($_SESSION['mc_landing_site']) ? $_SESSION['mc_landing_site'] : '';
    }
    try {
      if (!empty($this->mcEcommerce
        ->getCart($store_id, $cart_id))) {
        $this->mcEcommerce
          ->updateCart($store_id, $cart_id, $customer, $cart);
      }
    } catch (\Exception $e) {
      if ($e
        ->getCode() == 404) {

        // Cart doesn't exist; add a new cart.
        $this->mcEcommerce
          ->addCart($store_id, $cart_id, $customer, $cart);
      }
      else {

        // An actual error occurred; pass on the exception.
        throw new \Exception($e
          ->getMessage(), $e
          ->getCode(), $e);
      }
    }
  } catch (\Exception $e) {

    //mailchimp_ecommerce_log_error_message('Unable to add a cart: ' . $e->getMessage());
    $this->messenger
      ->addError($e
      ->getMessage());
  }
}