/** * {@inheritdoc} * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function saveChild($sku, \Magento\Bundle\Api\Data\LinkInterface $linkedProduct) { $product = $this->productRepository->get($sku, true); if ($product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) { throw new InputException(__('Product with specified sku: "%1" is not a bundle product', [$product->getSku()])); } /** @var \Magento\Catalog\Model\Product $linkProductModel */ $linkProductModel = $this->productRepository->get($linkedProduct->getSku()); if ($linkProductModel->isComposite()) { throw new InputException(__('Bundle product could not contain another composite product')); } if (!$linkedProduct->getId()) { throw new InputException(__('Id field of product link is required')); } /** @var \Magento\Bundle\Model\Selection $selectionModel */ $selectionModel = $this->bundleSelection->create(); $selectionModel->load($linkedProduct->getId()); if (!$selectionModel->getId()) { throw new InputException(__('Can not find product link with id "%1"', [$linkedProduct->getId()])); } $linkField = $this->getMetadataPool()->getMetadata(ProductInterface::class)->getLinkField(); $selectionModel = $this->mapProductLinkToSelectionModel($selectionModel, $linkedProduct, $linkProductModel->getId(), $product->getData($linkField)); try { $selectionModel->save(); } catch (\Exception $e) { throw new CouldNotSaveException(__('Could not save child: "%1"', $e->getMessage()), $e); } return true; }
/** * Compare two links and determine if they are equal * * @param \Magento\Bundle\Api\Data\LinkInterface $firstLink * @param \Magento\Bundle\Api\Data\LinkInterface $secondLink * @return int * @SuppressWarnings(PHPMD.UnusedPrivateMethod) */ private function compareLinks(\Magento\Bundle\Api\Data\LinkInterface $firstLink, \Magento\Bundle\Api\Data\LinkInterface $secondLink) { if ($firstLink->getId() == $secondLink->getId()) { return 0; } else { return 1; } }