ProductVariationsBuilder.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\ConfigurableProduct\Model;
  7. class ProductVariationsBuilder
  8. {
  9. /**
  10. * @var \Magento\Framework\Api\AttributeValueFactory
  11. */
  12. private $customAttributeFactory;
  13. /**
  14. * @var \Magento\Catalog\Model\ProductFactory
  15. */
  16. protected $productFactory;
  17. /**
  18. * @var \Magento\ConfigurableProduct\Model\Product\Type\VariationMatrix
  19. */
  20. private $variationMatrix;
  21. /**
  22. * @param \Magento\Catalog\Model\ProductFactory $productFactory
  23. * @param \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory
  24. * @param Product\Type\VariationMatrix $variationMatrix
  25. */
  26. public function __construct(
  27. \Magento\Catalog\Model\ProductFactory $productFactory,
  28. \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory,
  29. \Magento\ConfigurableProduct\Model\Product\Type\VariationMatrix $variationMatrix
  30. ) {
  31. $this->productFactory = $productFactory;
  32. $this->customAttributeFactory = $customAttributeFactory;
  33. $this->variationMatrix = $variationMatrix;
  34. }
  35. /**
  36. * Populate product with variation of attributes
  37. *
  38. * @param \Magento\Catalog\Api\Data\ProductInterface $product
  39. * @param array $attributes
  40. * @return \Magento\Catalog\Api\Data\ProductInterface[]
  41. */
  42. public function create(\Magento\Catalog\Api\Data\ProductInterface $product, $attributes)
  43. {
  44. $variations = $this->variationMatrix->getVariations($attributes);
  45. $products = [];
  46. foreach ($variations as $variation) {
  47. $price = $product->getPrice();
  48. /** @var \Magento\Catalog\Model\Product $item */
  49. $item = $this->productFactory->create();
  50. $item->setData($product->getData());
  51. $suffix = '';
  52. foreach ($variation as $attributeId => $valueInfo) {
  53. $suffix .= '-' . $valueInfo['value'];
  54. $customAttribute = $this->customAttributeFactory->create()
  55. ->setAttributeCode($attributes[$attributeId]['attribute_code'])
  56. ->setValue($valueInfo['value']);
  57. $customAttributes = array_merge(
  58. $item->getCustomAttributes(),
  59. [
  60. $attributes[$attributeId]['attribute_code'] => $customAttribute
  61. ]
  62. );
  63. $item->setData('custom_attributes', $customAttributes);
  64. }
  65. $item->setPrice($price);
  66. $item->setName($product->getName() . $suffix);
  67. $item->setSku($product->getSku() . $suffix);
  68. $item->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE);
  69. $products[] = $item;
  70. }
  71. return $products;
  72. }
  73. }