LinkManagement.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. <?php
  2. /**
  3. *
  4. * Copyright © Magento, Inc. All rights reserved.
  5. * See COPYING.txt for license details.
  6. */
  7. namespace Magento\Bundle\Model;
  8. use Magento\Catalog\Api\Data\ProductInterface;
  9. use Magento\Catalog\Api\ProductRepositoryInterface;
  10. use Magento\Framework\App\ObjectManager;
  11. use Magento\Framework\Exception\CouldNotSaveException;
  12. use Magento\Framework\Exception\InputException;
  13. use Magento\Framework\EntityManager\MetadataPool;
  14. /**
  15. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  16. */
  17. class LinkManagement implements \Magento\Bundle\Api\ProductLinkManagementInterface
  18. {
  19. /**
  20. * @var \Magento\Catalog\Api\ProductRepositoryInterface
  21. */
  22. protected $productRepository;
  23. /**
  24. * @var \Magento\Bundle\Api\Data\LinkInterfaceFactory
  25. */
  26. protected $linkFactory;
  27. /**
  28. * @var \Magento\Bundle\Model\ResourceModel\BundleFactory
  29. */
  30. protected $bundleFactory;
  31. /**
  32. * @var SelectionFactory
  33. */
  34. protected $bundleSelection;
  35. /**
  36. * @var \Magento\Bundle\Model\ResourceModel\Option\CollectionFactory
  37. */
  38. protected $optionCollection;
  39. /**
  40. * @var \Magento\Framework\Api\DataObjectHelper
  41. */
  42. protected $dataObjectHelper;
  43. /**
  44. * @var MetadataPool
  45. */
  46. private $metadataPool;
  47. /**
  48. * @param ProductRepositoryInterface $productRepository
  49. * @param \Magento\Bundle\Api\Data\LinkInterfaceFactory $linkFactory
  50. * @param \Magento\Bundle\Model\SelectionFactory $bundleSelection
  51. * @param \Magento\Bundle\Model\ResourceModel\BundleFactory $bundleFactory
  52. * @param \Magento\Bundle\Model\ResourceModel\Option\CollectionFactory $optionCollection
  53. * @param \Magento\Store\Model\StoreManagerInterface $storeManager
  54. * @param \Magento\Framework\Api\DataObjectHelper $dataObjectHelper
  55. */
  56. public function __construct(
  57. ProductRepositoryInterface $productRepository,
  58. \Magento\Bundle\Api\Data\LinkInterfaceFactory $linkFactory,
  59. \Magento\Bundle\Model\SelectionFactory $bundleSelection,
  60. \Magento\Bundle\Model\ResourceModel\BundleFactory $bundleFactory,
  61. \Magento\Bundle\Model\ResourceModel\Option\CollectionFactory $optionCollection,
  62. \Magento\Store\Model\StoreManagerInterface $storeManager,
  63. \Magento\Framework\Api\DataObjectHelper $dataObjectHelper
  64. ) {
  65. $this->productRepository = $productRepository;
  66. $this->linkFactory = $linkFactory;
  67. $this->bundleFactory = $bundleFactory;
  68. $this->bundleSelection = $bundleSelection;
  69. $this->optionCollection = $optionCollection;
  70. $this->storeManager = $storeManager;
  71. $this->dataObjectHelper = $dataObjectHelper;
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public function getChildren($productSku, $optionId = null)
  77. {
  78. $product = $this->productRepository->get($productSku, true);
  79. if ($product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) {
  80. throw new InputException(__('This is implemented for bundle products only.'));
  81. }
  82. $childrenList = [];
  83. foreach ($this->getOptions($product) as $option) {
  84. if (!$option->getSelections() || ($optionId !== null && $option->getOptionId() != $optionId)) {
  85. continue;
  86. }
  87. /** @var \Magento\Catalog\Model\Product $selection */
  88. foreach ($option->getSelections() as $selection) {
  89. $childrenList[] = $this->buildLink($selection, $product);
  90. }
  91. }
  92. return $childrenList;
  93. }
  94. /**
  95. * {@inheritdoc}
  96. */
  97. public function addChildByProductSku($sku, $optionId, \Magento\Bundle\Api\Data\LinkInterface $linkedProduct)
  98. {
  99. /** @var \Magento\Catalog\Model\Product $product */
  100. $product = $this->productRepository->get($sku, true);
  101. return $this->addChild($product, $optionId, $linkedProduct);
  102. }
  103. /**
  104. * {@inheritdoc}
  105. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  106. * @SuppressWarnings(PHPMD.NPathComplexity)
  107. */
  108. public function saveChild(
  109. $sku,
  110. \Magento\Bundle\Api\Data\LinkInterface $linkedProduct
  111. ) {
  112. $product = $this->productRepository->get($sku, true);
  113. if ($product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) {
  114. throw new InputException(
  115. __('The product with the "%1" SKU isn\'t a bundle product.', [$product->getSku()])
  116. );
  117. }
  118. /** @var \Magento\Catalog\Model\Product $linkProductModel */
  119. $linkProductModel = $this->productRepository->get($linkedProduct->getSku());
  120. if ($linkProductModel->isComposite()) {
  121. throw new InputException(__('The bundle product can\'t contain another composite product.'));
  122. }
  123. if (!$linkedProduct->getId()) {
  124. throw new InputException(__('The product link needs an ID field entered. Enter and try again.'));
  125. }
  126. /** @var \Magento\Bundle\Model\Selection $selectionModel */
  127. $selectionModel = $this->bundleSelection->create();
  128. $selectionModel->load($linkedProduct->getId());
  129. if (!$selectionModel->getId()) {
  130. throw new InputException(
  131. __(
  132. 'The product link with the "%1" ID field wasn\'t found. Verify the ID and try again.',
  133. [$linkedProduct->getId()]
  134. )
  135. );
  136. }
  137. $linkField = $this->getMetadataPool()->getMetadata(ProductInterface::class)->getLinkField();
  138. $selectionModel = $this->mapProductLinkToSelectionModel(
  139. $selectionModel,
  140. $linkedProduct,
  141. $linkProductModel->getId(),
  142. $product->getData($linkField)
  143. );
  144. try {
  145. $selectionModel->save();
  146. } catch (\Exception $e) {
  147. throw new CouldNotSaveException(__('Could not save child: "%1"', $e->getMessage()), $e);
  148. }
  149. return true;
  150. }
  151. /**
  152. * @param \Magento\Bundle\Model\Selection $selectionModel
  153. * @param \Magento\Bundle\Api\Data\LinkInterface $productLink
  154. * @param string $linkedProductId
  155. * @param string $parentProductId
  156. * @return \Magento\Bundle\Model\Selection
  157. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  158. * @SuppressWarnings(PHPMD.NPathComplexity)
  159. */
  160. protected function mapProductLinkToSelectionModel(
  161. \Magento\Bundle\Model\Selection $selectionModel,
  162. \Magento\Bundle\Api\Data\LinkInterface $productLink,
  163. $linkedProductId,
  164. $parentProductId
  165. ) {
  166. $selectionModel->setProductId($linkedProductId);
  167. $selectionModel->setParentProductId($parentProductId);
  168. if ($productLink->getSelectionId() !== null) {
  169. $selectionModel->setSelectionId($productLink->getSelectionId());
  170. }
  171. if ($productLink->getOptionId() !== null) {
  172. $selectionModel->setOptionId($productLink->getOptionId());
  173. }
  174. if ($productLink->getPosition() !== null) {
  175. $selectionModel->setPosition($productLink->getPosition());
  176. }
  177. if ($productLink->getQty() !== null) {
  178. $selectionModel->setSelectionQty($productLink->getQty());
  179. }
  180. if ($productLink->getPriceType() !== null) {
  181. $selectionModel->setSelectionPriceType($productLink->getPriceType());
  182. }
  183. if ($productLink->getPrice() !== null) {
  184. $selectionModel->setSelectionPriceValue($productLink->getPrice());
  185. }
  186. if ($productLink->getCanChangeQuantity() !== null) {
  187. $selectionModel->setSelectionCanChangeQty($productLink->getCanChangeQuantity());
  188. }
  189. if ($productLink->getIsDefault() !== null) {
  190. $selectionModel->setIsDefault($productLink->getIsDefault());
  191. }
  192. return $selectionModel;
  193. }
  194. /**
  195. * {@inheritdoc}
  196. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  197. */
  198. public function addChild(
  199. \Magento\Catalog\Api\Data\ProductInterface $product,
  200. $optionId,
  201. \Magento\Bundle\Api\Data\LinkInterface $linkedProduct
  202. ) {
  203. if ($product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) {
  204. throw new InputException(
  205. __('The product with the "%1" SKU isn\'t a bundle product.', $product->getSku())
  206. );
  207. }
  208. $linkField = $this->getMetadataPool()->getMetadata(ProductInterface::class)->getLinkField();
  209. $options = $this->optionCollection->create();
  210. $options->setIdFilter($optionId);
  211. $options->setProductLinkFilter($product->getData($linkField));
  212. $existingOption = $options->getFirstItem();
  213. if (!$existingOption->getId()) {
  214. throw new InputException(
  215. __(
  216. 'Product with specified sku: "%1" does not contain option: "%2"',
  217. [$product->getSku(), $optionId]
  218. )
  219. );
  220. }
  221. /* @var $resource \Magento\Bundle\Model\ResourceModel\Bundle */
  222. $resource = $this->bundleFactory->create();
  223. $selections = $resource->getSelectionsData($product->getData($linkField));
  224. /** @var \Magento\Catalog\Model\Product $linkProductModel */
  225. $linkProductModel = $this->productRepository->get($linkedProduct->getSku());
  226. if ($linkProductModel->isComposite()) {
  227. throw new InputException(__('The bundle product can\'t contain another composite product.'));
  228. }
  229. if ($selections) {
  230. foreach ($selections as $selection) {
  231. if ($selection['option_id'] == $optionId &&
  232. $selection['product_id'] == $linkProductModel->getEntityId() &&
  233. $selection['parent_product_id'] == $product->getData($linkField)) {
  234. if (!$product->getCopyFromView()) {
  235. throw new CouldNotSaveException(
  236. __(
  237. 'Child with specified sku: "%1" already assigned to product: "%2"',
  238. [$linkedProduct->getSku(), $product->getSku()]
  239. )
  240. );
  241. } else {
  242. return $this->bundleSelection->create()->load($linkProductModel->getEntityId());
  243. }
  244. }
  245. }
  246. }
  247. $selectionModel = $this->bundleSelection->create();
  248. $selectionModel = $this->mapProductLinkToSelectionModel(
  249. $selectionModel,
  250. $linkedProduct,
  251. $linkProductModel->getEntityId(),
  252. $product->getData($linkField)
  253. );
  254. $selectionModel->setOptionId($optionId);
  255. try {
  256. $selectionModel->save();
  257. $resource->addProductRelation($product->getData($linkField), $linkProductModel->getEntityId());
  258. } catch (\Exception $e) {
  259. throw new CouldNotSaveException(__('Could not save child: "%1"', $e->getMessage()), $e);
  260. }
  261. return $selectionModel->getId();
  262. }
  263. /**
  264. * {@inheritdoc}
  265. */
  266. public function removeChild($sku, $optionId, $childSku)
  267. {
  268. $product = $this->productRepository->get($sku, true);
  269. if ($product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) {
  270. throw new InputException(__('The product with the "%1" SKU isn\'t a bundle product.', $sku));
  271. }
  272. $excludeSelectionIds = [];
  273. $usedProductIds = [];
  274. $removeSelectionIds = [];
  275. foreach ($this->getOptions($product) as $option) {
  276. /** @var \Magento\Bundle\Model\Selection $selection */
  277. foreach ($option->getSelections() as $selection) {
  278. if ((strcasecmp($selection->getSku(), $childSku) == 0) && ($selection->getOptionId() == $optionId)) {
  279. $removeSelectionIds[] = $selection->getSelectionId();
  280. $usedProductIds[] = $selection->getProductId();
  281. continue;
  282. }
  283. $excludeSelectionIds[] = $selection->getSelectionId();
  284. }
  285. }
  286. if (empty($removeSelectionIds)) {
  287. throw new \Magento\Framework\Exception\NoSuchEntityException(
  288. __("The bundle product doesn't exist. Review your request and try again.")
  289. );
  290. }
  291. $linkField = $this->getMetadataPool()->getMetadata(ProductInterface::class)->getLinkField();
  292. /* @var $resource \Magento\Bundle\Model\ResourceModel\Bundle */
  293. $resource = $this->bundleFactory->create();
  294. $resource->dropAllUnneededSelections($product->getData($linkField), $excludeSelectionIds);
  295. $resource->removeProductRelations($product->getData($linkField), array_unique($usedProductIds));
  296. return true;
  297. }
  298. /**
  299. * @param \Magento\Catalog\Model\Product $selection
  300. * @param \Magento\Catalog\Model\Product $product
  301. * @return \Magento\Bundle\Api\Data\LinkInterface
  302. */
  303. private function buildLink(\Magento\Catalog\Model\Product $selection, \Magento\Catalog\Model\Product $product)
  304. {
  305. $selectionPriceType = $selectionPrice = null;
  306. /** @var \Magento\Bundle\Model\Selection $product */
  307. if ($product->getPriceType()) {
  308. $selectionPriceType = $selection->getSelectionPriceType();
  309. $selectionPrice = $selection->getSelectionPriceValue();
  310. }
  311. /** @var \Magento\Bundle\Api\Data\LinkInterface $link */
  312. $link = $this->linkFactory->create();
  313. $this->dataObjectHelper->populateWithArray(
  314. $link,
  315. $selection->getData(),
  316. \Magento\Bundle\Api\Data\LinkInterface::class
  317. );
  318. $link->setIsDefault($selection->getIsDefault())
  319. ->setId($selection->getSelectionId())
  320. ->setQty($selection->getSelectionQty())
  321. ->setCanChangeQuantity($selection->getSelectionCanChangeQty())
  322. ->setPrice($selectionPrice)
  323. ->setPriceType($selectionPriceType);
  324. return $link;
  325. }
  326. /**
  327. * @param \Magento\Catalog\Api\Data\ProductInterface $product
  328. * @return \Magento\Bundle\Api\Data\OptionInterface[]
  329. */
  330. private function getOptions(\Magento\Catalog\Api\Data\ProductInterface $product)
  331. {
  332. /** @var \Magento\Bundle\Model\Product\Type $productTypeInstance */
  333. $productTypeInstance = $product->getTypeInstance();
  334. $productTypeInstance->setStoreFilter(
  335. $product->getStoreId(),
  336. $product
  337. );
  338. $optionCollection = $productTypeInstance->getOptionsCollection($product);
  339. $selectionCollection = $productTypeInstance->getSelectionsCollection(
  340. $productTypeInstance->getOptionsIds($product),
  341. $product
  342. );
  343. $options = $optionCollection->appendSelections($selectionCollection, true);
  344. return $options;
  345. }
  346. /**
  347. * Get MetadataPool instance
  348. * @return MetadataPool
  349. */
  350. private function getMetadataPool()
  351. {
  352. if (!$this->metadataPool) {
  353. $this->metadataPool = ObjectManager::getInstance()->get(MetadataPool::class);
  354. }
  355. return $this->metadataPool;
  356. }
  357. }