PageRenderTime 27ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/app/code/Magento/Bundle/Model/LinkManagement.php

https://gitlab.com/crazybutterfly815/magento2
PHP | 386 lines | 259 code | 40 blank | 87 comment | 37 complexity | 0db691ac1fa9b712c1e3696df7d520af MD5 | raw file
  1. <?php
  2. /**
  3. *
  4. * Copyright © 2016 Magento. 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(__('Only implemented for bundle product'));
  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. __('Product with specified sku: "%1" is not 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(__('Bundle product could not contain another composite product'));
  122. }
  123. if (!$linkedProduct->getId()) {
  124. throw new InputException(__('Id field of product link is required'));
  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(__('Can not find product link with id "%1"', [$linkedProduct->getId()]));
  131. }
  132. $linkField = $this->getMetadataPool()->getMetadata(ProductInterface::class)->getLinkField();
  133. $selectionModel = $this->mapProductLinkToSelectionModel(
  134. $selectionModel,
  135. $linkedProduct,
  136. $linkProductModel->getId(),
  137. $product->getData($linkField)
  138. );
  139. try {
  140. $selectionModel->save();
  141. } catch (\Exception $e) {
  142. throw new CouldNotSaveException(__('Could not save child: "%1"', $e->getMessage()), $e);
  143. }
  144. return true;
  145. }
  146. /**
  147. * @param \Magento\Bundle\Model\Selection $selectionModel
  148. * @param \Magento\Bundle\Api\Data\LinkInterface $productLink
  149. * @param string $linkedProductId
  150. * @param string $parentProductId
  151. * @return \Magento\Bundle\Model\Selection
  152. */
  153. protected function mapProductLinkToSelectionModel(
  154. \Magento\Bundle\Model\Selection $selectionModel,
  155. \Magento\Bundle\Api\Data\LinkInterface $productLink,
  156. $linkedProductId,
  157. $parentProductId
  158. ) {
  159. $selectionModel->setProductId($linkedProductId);
  160. $selectionModel->setParentProductId($parentProductId);
  161. if (($productLink->getOptionId() !== null)) {
  162. $selectionModel->setOptionId($productLink->getOptionId());
  163. }
  164. if ($productLink->getPosition() !== null) {
  165. $selectionModel->setPosition($productLink->getPosition());
  166. }
  167. if ($productLink->getQty() !== null) {
  168. $selectionModel->setSelectionQty($productLink->getQty());
  169. }
  170. if ($productLink->getPriceType() !== null) {
  171. $selectionModel->setSelectionPriceType($productLink->getPriceType());
  172. }
  173. if ($productLink->getPrice() !== null) {
  174. $selectionModel->setSelectionPriceValue($productLink->getPrice());
  175. }
  176. if ($productLink->getCanChangeQuantity() !== null) {
  177. $selectionModel->setSelectionCanChangeQty($productLink->getCanChangeQuantity());
  178. }
  179. if ($productLink->getIsDefault() !== null) {
  180. $selectionModel->setIsDefault($productLink->getIsDefault());
  181. }
  182. return $selectionModel;
  183. }
  184. /**
  185. * {@inheritdoc}
  186. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  187. */
  188. public function addChild(
  189. \Magento\Catalog\Api\Data\ProductInterface $product,
  190. $optionId,
  191. \Magento\Bundle\Api\Data\LinkInterface $linkedProduct
  192. ) {
  193. if ($product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) {
  194. throw new InputException(
  195. __('Product with specified sku: "%1" is not a bundle product', $product->getSku())
  196. );
  197. }
  198. $options = $this->optionCollection->create();
  199. $options->setIdFilter($optionId);
  200. $existingOption = $options->getFirstItem();
  201. if (!$existingOption->getId()) {
  202. throw new InputException(
  203. __(
  204. 'Product with specified sku: "%1" does not contain option: "%2"',
  205. [$product->getSku(), $optionId]
  206. )
  207. );
  208. }
  209. $linkField = $this->getMetadataPool()->getMetadata(ProductInterface::class)->getLinkField();
  210. /* @var $resource \Magento\Bundle\Model\ResourceModel\Bundle */
  211. $resource = $this->bundleFactory->create();
  212. $selections = $resource->getSelectionsData($product->getData($linkField));
  213. /** @var \Magento\Catalog\Model\Product $linkProductModel */
  214. $linkProductModel = $this->productRepository->get($linkedProduct->getSku());
  215. if ($linkProductModel->isComposite()) {
  216. throw new InputException(__('Bundle product could not contain another composite product'));
  217. }
  218. if ($selections) {
  219. foreach ($selections as $selection) {
  220. if ($selection['option_id'] == $optionId &&
  221. $selection['product_id'] == $linkProductModel->getEntityId()) {
  222. if (!$product->getCopyFromView()) {
  223. throw new CouldNotSaveException(
  224. __(
  225. 'Child with specified sku: "%1" already assigned to product: "%2"',
  226. [$linkedProduct->getSku(), $product->getSku()]
  227. )
  228. );
  229. } else {
  230. return $this->bundleSelection->create()->load($linkProductModel->getEntityId());
  231. }
  232. }
  233. }
  234. }
  235. $selectionModel = $this->bundleSelection->create();
  236. $selectionModel = $this->mapProductLinkToSelectionModel(
  237. $selectionModel,
  238. $linkedProduct,
  239. $linkProductModel->getEntityId(),
  240. $product->getData($linkField)
  241. );
  242. $selectionModel->setOptionId($optionId);
  243. try {
  244. $selectionModel->save();
  245. $resource->addProductRelation($product->getData($linkField), $linkProductModel->getEntityId());
  246. } catch (\Exception $e) {
  247. throw new CouldNotSaveException(__('Could not save child: "%1"', $e->getMessage()), $e);
  248. }
  249. return $selectionModel->getId();
  250. }
  251. /**
  252. * {@inheritdoc}
  253. */
  254. public function removeChild($sku, $optionId, $childSku)
  255. {
  256. $product = $this->productRepository->get($sku, true);
  257. if ($product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) {
  258. throw new InputException(__('Product with specified sku: %1 is not a bundle product', $sku));
  259. }
  260. $excludeSelectionIds = [];
  261. $usedProductIds = [];
  262. $removeSelectionIds = [];
  263. foreach ($this->getOptions($product) as $option) {
  264. /** @var \Magento\Bundle\Model\Selection $selection */
  265. foreach ($option->getSelections() as $selection) {
  266. if ((strcasecmp($selection->getSku(), $childSku) == 0) && ($selection->getOptionId() == $optionId)) {
  267. $removeSelectionIds[] = $selection->getSelectionId();
  268. $usedProductIds[] = $selection->getProductId();
  269. continue;
  270. }
  271. $excludeSelectionIds[] = $selection->getSelectionId();
  272. $usedProductIds[] = $selection->getProductId();
  273. }
  274. }
  275. if (empty($removeSelectionIds)) {
  276. throw new \Magento\Framework\Exception\NoSuchEntityException(
  277. __('Requested bundle option product doesn\'t exist')
  278. );
  279. }
  280. $linkField = $this->getMetadataPool()->getMetadata(ProductInterface::class)->getLinkField();
  281. /* @var $resource \Magento\Bundle\Model\ResourceModel\Bundle */
  282. $resource = $this->bundleFactory->create();
  283. $resource->dropAllUnneededSelections($product->getData($linkField), $excludeSelectionIds);
  284. $resource->removeProductRelations($product->getData($linkField), array_unique($usedProductIds));
  285. return true;
  286. }
  287. /**
  288. * @param \Magento\Catalog\Model\Product $selection
  289. * @param \Magento\Catalog\Model\Product $product
  290. * @return \Magento\Bundle\Api\Data\LinkInterface
  291. */
  292. private function buildLink(\Magento\Catalog\Model\Product $selection, \Magento\Catalog\Model\Product $product)
  293. {
  294. $selectionPriceType = $selectionPrice = null;
  295. /** @var \Magento\Bundle\Model\Selection $product */
  296. if ($product->getPriceType()) {
  297. $selectionPriceType = $selection->getSelectionPriceType();
  298. $selectionPrice = $selection->getSelectionPriceValue();
  299. }
  300. /** @var \Magento\Bundle\Api\Data\LinkInterface $link */
  301. $link = $this->linkFactory->create();
  302. $this->dataObjectHelper->populateWithArray(
  303. $link,
  304. $selection->getData(),
  305. \Magento\Bundle\Api\Data\LinkInterface::class
  306. );
  307. $link->setIsDefault($selection->getIsDefault())
  308. ->setId($selection->getSelectionId())
  309. ->setQty($selection->getSelectionQty())
  310. ->setCanChangeQuantity($selection->getSelectionCanChangeQty())
  311. ->setPrice($selectionPrice)
  312. ->setPriceType($selectionPriceType);
  313. return $link;
  314. }
  315. /**
  316. * @param \Magento\Catalog\Api\Data\ProductInterface $product
  317. * @return \Magento\Bundle\Api\Data\OptionInterface[]
  318. */
  319. private function getOptions(\Magento\Catalog\Api\Data\ProductInterface $product)
  320. {
  321. /** @var \Magento\Bundle\Model\Product\Type $productTypeInstance */
  322. $productTypeInstance = $product->getTypeInstance();
  323. $productTypeInstance->setStoreFilter(
  324. $product->getStoreId(),
  325. $product
  326. );
  327. $optionCollection = $productTypeInstance->getOptionsCollection($product);
  328. $selectionCollection = $productTypeInstance->getSelectionsCollection(
  329. $productTypeInstance->getOptionsIds($product),
  330. $product
  331. );
  332. $options = $optionCollection->appendSelections($selectionCollection, true);
  333. return $options;
  334. }
  335. /**
  336. * Get MetadataPool instance
  337. * @return MetadataPool
  338. */
  339. private function getMetadataPool()
  340. {
  341. if (!$this->metadataPool) {
  342. $this->metadataPool = ObjectManager::getInstance()->get(MetadataPool::class);
  343. }
  344. return $this->metadataPool;
  345. }
  346. }