You are here

public function CartEventSubscriber::cartAdd in Mailchimp E-Commerce 8

Respond to event fired after adding a cart item.

Initial cart creation in Mailchimp needs to happen when the first cart item is added. This is because we can't rely on the total price being available when the Commerce Order itself is first created.

File

modules/mailchimp_ecommerce_commerce/src/EventSubscriber/CartEventSubscriber.php, line 66

Class

CartEventSubscriber
Event Subscriber for Commerce Carts.

Namespace

Drupal\mailchimp_ecommerce_commerce\EventSubscriber

Code

public function cartAdd(CartEntityAddEvent $event) {

  /** @var \Drupal\commerce_order\Entity\Order $order */
  $order = $event
    ->getCart();
  $customer['email_address'] = $order
    ->getEmail();
  if (empty($customer['email_address'])) {

    // Cannot create or add an item to a cart with no customer email address.
    return;
  }
  if ($this->cart_handler
    ->cartExists($order
    ->id())) {

    // Add item to the existing cart.

    /** @var \Drupal\commerce_order\Entity\OrderItem $order_item */
    $order_item = $event
      ->getOrderItem();
    $product = $this->order_handler
      ->buildProduct($order_item);
    $this->cart_handler
      ->addCartLine($order
      ->id(), $order_item
      ->id(), $product);
  }
  else {

    // Create a new cart.
    $billing_profile = $order
      ->getBillingProfile();
    $customer = $this->customer_handler
      ->buildCustomer($customer, $billing_profile);

    // Update or add customer in case this is a new cart.
    $this->customer_handler
      ->addOrUpdateCustomer($customer);
    $order_data = $this->order_handler
      ->buildOrder($order, $customer);

    // Add cart total price to order data.
    if (!isset($order_data['currency_code'])) {

      /** @var Price $price */
      $price = $event
        ->getEntity()
        ->getPrice();
      $order_data['currency_code'] = $price
        ->getCurrencyCode();
      $order_data['order_total'] = $price
        ->getNumber();
    }
    $order_data['checkout_url'] = Url::fromRoute('commerce_checkout.form', [
      'commerce_order' => $order
        ->id(),
    ], [
      'absolute' => TRUE,
    ])
      ->toString();
    $this->cart_handler
      ->addOrUpdateCart($order
      ->id(), $customer, $order_data);
  }
}