You are here

public function Package::save in Ubercart 8.4

Saves this package.

File

shipping/uc_fulfillment/src/Package.php, line 521

Class

Package
Defines the Package class.

Namespace

Drupal\uc_fulfillment

Code

public function save() {
  $status = '';
  $fields = [
    'order_id' => $this->order_id,
    'shipping_type' => $this->shipping_type,
    'pkg_type' => $this->pkg_type,
    'length' => $this->length,
    'width' => $this->width,
    'height' => $this->height,
    'length_units' => $this->length_units,
    'weight' => $this->weight,
    'weight_units' => $this->weight_units,
    'value' => $this->value,
    'currency' => $this->currency,
    'tracking_number' => $this->tracking_number,
  ];
  if ($this->sid) {
    $fields['sid'] = $this->sid;
  }
  if ($this->label_image) {
    $fields['label_image'] = $this->label_image->fid;
  }
  if (!$this->package_id) {

    // This is a new package, do an INSERT.
    $this->package_id = \Drupal::database()
      ->insert('uc_packages')
      ->fields($fields)
      ->execute();
    $status = SAVED_NEW;
  }
  else {

    // This is a package we're modifying, do an UPDATE.
    \Drupal::database()
      ->update('uc_packages')
      ->fields($fields)
      ->condition('package_id', $this->package_id)
      ->execute();
    $status = SAVED_UPDATED;
  }

  // Now take care of saving the product relations.
  if ($this->products) {
    $insert = \Drupal::database()
      ->insert('uc_packaged_products')
      ->fields([
      'package_id',
      'order_product_id',
      'qty',
    ]);
    foreach ($this->products as $id => $product) {
      $insert
        ->values([
        'package_id' => $this->package_id,
        'order_product_id' => $id,
        'qty' => $product->qty,
      ]);

      // Save the package_id to the OrderProduct.
      // 'package_id' is a key in the serialized 'data' array.
      // data->package_id is an array keyed by package ID with a
      // value equal to the quantity in that package.
      $order_product = OrderProduct::load($id);
      if (NULL != $order_product) {
        $package_array = (array) $order_product->data->package_id;
        $package_array[intval($this->package_id)] = (int) $product->qty;
        $order_product->data->package_id = $package_array;
        $order_product
          ->save();
      }
    }

    // Remove any old data for this package.
    \Drupal::database()
      ->delete('uc_packaged_products')
      ->condition('package_id', $this->package_id)
      ->execute();

    // Write the current data for this package.
    $insert
      ->execute();
  }
  return $status;
}