You are here

public function ProductHandler::deleteProductVariant in Mailchimp E-Commerce 8

@inheritdoc

Overrides ProductHandlerInterface::deleteProductVariant

File

src/ProductHandler.php, line 198

Class

ProductHandler
Product handler.

Namespace

Drupal\mailchimp_ecommerce

Code

public function deleteProductVariant($product_id, $product_variant_id) {
  try {
    $store_id = mailchimp_ecommerce_get_store_id();
    if (empty($store_id)) {
      throw new \Exception('Cannot delete a product variant without a store ID.');
    }

    /* @var \Mailchimp\MailchimpEcommerce $mc_ecommerce */
    $mc_ecommerce = mailchimp_get_api_object('MailchimpEcommerce');
    try {
      $variants = $mc_ecommerce
        ->getProductVariants($store_id, $product_id);

      // Delete the variant if the product contains multiple variants.
      if ($variants->total_items > 1) {
        $mc_ecommerce
          ->deleteProductVariant($store_id, $product_id, $product_variant_id);
      }
      else {

        // Delete the product if the product has only one variant.
        $mc_ecommerce
          ->deleteProduct($store_id, $product_id);
      }
    } catch (\Exception $e) {
      if ($e
        ->getCode() == 404) {

        // This product isn't in Mailchimp.
        return;
      }
      else {

        // An actual error occurred; pass on the exception.
        throw new \Exception($e
          ->getMessage(), $e
          ->getCode(), $e);
      }
    }
  } catch (\Exception $e) {
    mailchimp_ecommerce_log_error_message('Unable to delete product variant: ' . $e
      ->getMessage());
    drupal_set_message($e
      ->getMessage(), 'error');
  }
}