/** * @param int $prodId Magento ID for the product * @param array $categories Odoo IDs of the categories. */ public function replicateCategories($prodId, $categories) { /* get current categories links for the product */ $prod = $this->_mageRepoProd->getById($prodId); $sku = $prod->getSku(); $catsExist = $prod->getCategoryIds(); $catsFound = []; if (is_array($categories)) { foreach ($categories as $catOdooId) { $catMageId = $this->_repoRegistry->getCategoryMageIdByOdooId($catOdooId); if (!in_array($catMageId, $catsExist)) { /* create new product link if not exists */ /** @var CategoryProductLinkInterface $prodLink */ $prodLink = $this->_manObj->create(CategoryProductLinkInterface::class); $prodLink->setCategoryId($catMageId); $prodLink->setSku($sku); $prodLink->setPosition(1); $this->_mageRepoCatLink->save($prodLink); } /* register found link */ $catsFound[] = $catMageId; } } /* get difference between exist & found */ $diff = array_diff($catsExist, $catsFound); foreach ($diff as $catMageId) { $this->_mageRepoCatLink->deleteByIds($catMageId, $sku); } }
/** * Assign product to given categories * * @param string $productSku * @param \int[] $categoryIds * @return bool */ public function assignProductToCategories($productSku, array $categoryIds) { $product = $this->productRepository->get($productSku); $assignedCategories = $this->productResource->getCategoryIds($product); foreach (array_diff($assignedCategories, $categoryIds) as $categoryId) { $this->categoryLinkRepository->deleteByIds($categoryId, $productSku); } foreach (array_diff($categoryIds, $assignedCategories) as $categoryId) { /** @var \Magento\Catalog\Api\Data\CategoryProductLinkInterface $categoryProductLink */ $categoryProductLink = $this->productLinkFactory->create(); $categoryProductLink->setSku($productSku); $categoryProductLink->setCategoryId($categoryId); $categoryProductLink->setPosition(0); $this->categoryLinkRepository->save($categoryProductLink); } $productCategoryIndexer = $this->indexerRegistry->get(Indexer\Product\Category::INDEXER_ID); if (!$productCategoryIndexer->isScheduled()) { $productCategoryIndexer->reindexRow($product->getId()); } return true; }