You are here

function uc_product_kit_uc_add_to_cart in Ubercart 8.4

Same name and namespace in other branches
  1. 7.3 uc_product_kit/uc_product_kit.module \uc_product_kit_uc_add_to_cart()

Implements hook_uc_add_to_cart().

File

uc_product_kit/uc_product_kit.module, line 804
The product kit module for Ubercart.

Code

function uc_product_kit_uc_add_to_cart($nid, $qty, $kit_data) {
  $node = Node::load($nid);
  if ($node
    ->getType() == 'product_kit') {
    $cart = \Drupal::service('uc_cart.manager')
      ->get();
    $unique = uniqid('', TRUE);
    $update = [];
    $product_data = [];
    foreach ($node->products as $product) {
      $data = [
        'kit_id' => $node
          ->id(),
        'module' => 'uc_product_kit',
      ] + \Drupal::moduleHandler()
        ->invokeAll('uc_add_to_cart_data', [
        $kit_data['products'][$product
          ->id()],
      ]);
      $product_data[$product
        ->id()] = $data;
      foreach ($cart
        ->getContents() as $item) {
        if ($item->nid == $product
          ->id() && isset($item->data['kit_id']) && $item->data['kit_id'] == $node
          ->id()) {

          // There is something in the cart like the product kit. Update
          // by default, but check that it's possible.
          $data['unique_id'] = $item->data['unique_id'];
          if ($item->data == $data) {

            // This product is a candidate for updating the cart quantity.
            // Make sure the data arrays will compare as equal when serialized.
            $product_data[$product
              ->id()] = $item->data;
            $update[$product
              ->id()] = TRUE;
          }
        }
      }
    }

    // The product kit can update its items only if they all can be updated.
    if (count($update) != count($node->products)) {
      foreach ($node->products as $product) {
        $data = $product_data[$product
          ->id()];
        $data['unique_id'] = $unique;
        $cart
          ->addItem($product
          ->id(), $product->qty * $qty, $data, FALSE);
      }
    }
    else {
      foreach ($node->products as $product) {
        $data = $product_data[$product
          ->id()];
        $cart
          ->addItem($product
          ->id(), $product->qty * $qty, $data, FALSE);
      }
    }
    return [
      [
        'success' => FALSE,
        'silent' => TRUE,
        'message' => '',
      ],
    ];
  }
}