Example #1
0
 /**
  * Save product category relations
  *
  * @param \Magento\Framework\DataObject $object
  * @return $this
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 protected function _saveCategories(\Magento\Framework\DataObject $object)
 {
     /**
      * If category ids data is not declared we haven't do manipulations
      */
     if (!$object->hasCategoryIds()) {
         return $this;
     }
     $categoryIds = $object->getCategoryIds();
     $oldCategoryIds = $this->getCategoryIds($object);
     $object->setIsChangedCategories(false);
     $insert = array_diff($categoryIds, $oldCategoryIds);
     $delete = array_diff($oldCategoryIds, $categoryIds);
     $connection = $this->getConnection();
     if (!empty($insert)) {
         $data = [];
         foreach ($insert as $categoryId) {
             if (empty($categoryId)) {
                 continue;
             }
             $data[] = ['category_id' => (int) $categoryId, 'product_id' => (int) $object->getId(), 'position' => 1];
         }
         if ($data) {
             $connection->insertMultiple($this->getProductCategoryTable(), $data);
         }
     }
     if (!empty($delete)) {
         foreach ($delete as $categoryId) {
             $where = ['product_id = ?' => (int) $object->getId(), 'category_id = ?' => (int) $categoryId];
             $connection->delete($this->getProductCategoryTable(), $where);
         }
     }
     if (!empty($insert) || !empty($delete)) {
         $object->setAffectedCategoryIds(array_merge($insert, $delete));
         $object->setIsChangedCategories(true);
     }
     return $this;
 }