ProductEventSubscriber.php in Mailchimp E-Commerce 8        
                          
                  
                        
  
  
  
  
  
File
  modules/mailchimp_ecommerce_commerce/src/EventSubscriber/ProductEventSubscriber.php
  
    View source  
  <?php
namespace Drupal\mailchimp_ecommerce_commerce\EventSubscriber;
use Drupal\commerce_product\Entity\Product;
use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\commerce_product\Event\ProductEvent;
use Drupal\commerce_product\Event\ProductEvents;
use Drupal\mailchimp_ecommerce\ProductHandler;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductEventSubscriber implements EventSubscriberInterface {
  
  private $product_handler;
  
  public function __construct(ProductHandler $product_handler) {
    $this->product_handler = $product_handler;
  }
  
  public function productInsert(ProductEvent $event) {
    
    $product = $event
      ->getProduct();
    $product_id = $product
      ->get('product_id')->value;
    $title = !empty($product
      ->get('title')->value) ? $product
      ->get('title')->value : '';
    $description = !empty($product
      ->get('body')->value) ? $product
      ->get('body')->value : '';
    
    $type = !empty($product
      ->get('type')->value) ? $product
      ->get('type')->value : '';
    $variants = $this->product_handler
      ->buildProductVariants($product);
    $url = $this->product_handler
      ->buildProductUrl($product);
    $image_url = $this->product_handler
      ->getProductImageUrl($product);
    $this->product_handler
      ->addProduct($product_id, $title, $url, $image_url, $description, $type, $variants);
  }
  
  public function productUpdate(ProductEvent $event) {
    $product = $event
      ->getProduct();
    $title = !empty($product
      ->get('title')->value) ? $product
      ->get('title')->value : '';
    $description = !empty($product
      ->get('body')->value) ? $product
      ->get('body')->value : '';
    
    $type = !empty($product
      ->get('type')->value) ? $product
      ->get('type')->value : '';
    $variants = $this->product_handler
      ->buildProductVariants($product);
    $url = $this->product_handler
      ->buildProductUrl($product);
    $image_url = $this->product_handler
      ->getProductImageUrl($product);
    
    $this->product_handler
      ->updateProduct($product, $title, $url, $image_url, $description, $type, $variants);
  }
  
  public function productDelete(ProductEvent $event) {
    
  }
  
  public static function getSubscribedEvents() {
    $events[ProductEvents::PRODUCT_INSERT][] = [
      'productInsert',
    ];
    $events[ProductEvents::PRODUCT_UPDATE][] = [
      'productUpdate',
    ];
    $events[ProductEvents::PRODUCT_DELETE][] = [
      'productDelete',
    ];
    return $events;
  }
}