You are here

public function OrderEventSubscriber::orderAssign in Mailchimp E-Commerce 8

Respond to event fired after assigning an anonymous order to a user.

File

modules/mailchimp_ecommerce_commerce/src/EventSubscriber/OrderEventSubscriber.php, line 113

Class

OrderEventSubscriber
Event Subscriber for Commerce Orders.

Namespace

Drupal\mailchimp_ecommerce_commerce\EventSubscriber

Code

public function orderAssign(OrderAssignEvent $event) {

  /** @var \Drupal\commerce_order\Entity\Order $order */
  $order = $event
    ->getOrder();

  // An anonymous user has logged in or created an account after populating
  // a cart with items. This is the first point we can send this cart to
  // Mailchimp as we are now able to get the user's email address.
  $account = $event
    ->getAccount();
  $customer['email_address'] = $account
    ->getEmail();
  $billing_profile = $order
    ->getBillingProfile();
  $customer = $this->customer_handler
    ->buildCustomer($customer, $billing_profile);
  $this->customer_handler
    ->addOrUpdateCustomer($customer);

  // Mailchimp considers any order to be a cart until the order is complete.
  // This order is created as a cart in Mailchimp when assigned to the user.
  $order_data = $this->order_handler
    ->buildOrder($order, $customer);

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

    /** @var \Drupal\commerce_price\Price $price */
    $price = $event
      ->getOrder()
      ->getTotalPrice();
    if ($price) {
      $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);
}