You are here

public function CommerceRepeatOrder::repeatOrder in Commerce Repeat Order 8

Same name and namespace in other branches
  1. 8.2 src/Controller/CommerceRepeatOrder.php \Drupal\commerce_repeat_order\Controller\CommerceRepeatOrder::repeatOrder()
1 string reference to 'CommerceRepeatOrder::repeatOrder'
commerce_repeat_order.routing.yml in ./commerce_repeat_order.routing.yml
commerce_repeat_order.routing.yml

File

src/Controller/CommerceRepeatOrder.php, line 62

Class

CommerceRepeatOrder

Namespace

Drupal\commerce_repeat_order\Controller

Code

public function repeatOrder(Order $commerce_order) {
  $this->order = $commerce_order;

  // The current user ID.
  $uid = $this
    ->currentUser()
    ->id();
  $order_uid = $this->order
    ->getCustomerId();
  if (!empty($order_uid) && $uid == $order_uid) {

    // Loading config for module.
    $config = $this
      ->config('commerce_repeat_order.settings');
    $add_or_override = $config
      ->get('add_or_override');

    // Loading existing cart.
    $cart = $this->cartProvider
      ->getCart('default', $this->order
      ->getStore());
    if (empty($cart)) {

      // Creating new cart is there is none.
      $cart = $this->cartProvider
        ->createCart('default', $this->order
        ->getStore());
    }
    elseif ($add_or_override == 'override') {
      $this->cartManager
        ->emptyCart($cart);
    }
    foreach ($this->order
      ->getItems() as $order_item) {

      // Creating new duplicate order item for adding in cart.
      $variation = $order_item
        ->getPurchasedEntity();
      $product = $variation ? $variation
        ->getProduct() : NULL;
      if ($product && $product
        ->isPublished()) {
        $order_item_new = $order_item
          ->createDuplicate();
        $order_item_new
          ->enforceIsNew();
        $order_item_new->id = NULL;
        $order_item_new->order_item_id = NULL;
        $order_item_new
          ->save();

        // Adding order item in cart.
        $this->cartManager
          ->addOrderItem($cart, $order_item_new);
      }
      else {
        $message = "Some products weren't copied to the cart as they aren't currently available.";
      }
    }
    if (isset($message) && $config
      ->get('status_message') == 'show') {
      drupal_set_message(t('@msg', array(
        '@msg' => $message,
      )), 'status', FALSE);
    }
  }
  else {
    drupal_set_message(t('You can only repeat your own order.'), 'error', FALSE);
  }
  return $this
    ->redirect('commerce_cart.page');
}