Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ProductVariationsBuilder.php
Go to the documentation of this file.
1 <?php
8 
10 {
14  private $customAttributeFactory;
15 
19  protected $productFactory;
20 
24  private $variationMatrix;
25 
31  public function __construct(
32  \Magento\Catalog\Model\ProductFactory $productFactory,
33  \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory,
34  \Magento\ConfigurableProduct\Model\Product\Type\VariationMatrix $variationMatrix
35  ) {
36  $this->productFactory = $productFactory;
37  $this->customAttributeFactory = $customAttributeFactory;
38  $this->variationMatrix = $variationMatrix;
39  }
40 
48  public function create(\Magento\Catalog\Api\Data\ProductInterface $product, $attributes)
49  {
50  $variations = $this->variationMatrix->getVariations($attributes);
51  $products = [];
52  foreach ($variations as $variation) {
53  $price = $product->getPrice();
55  $item = $this->productFactory->create();
56  $item->setData($product->getData());
57 
58  $suffix = '';
59  foreach ($variation as $attributeId => $valueInfo) {
60  $suffix .= '-' . $valueInfo['value'];
61  $customAttribute = $this->customAttributeFactory->create()
62  ->setAttributeCode($attributes[$attributeId]['attribute_code'])
63  ->setValue($valueInfo['value']);
64  $customAttributes = array_merge(
65  $item->getCustomAttributes(),
66  [
67  $attributes[$attributeId]['attribute_code'] => $customAttribute
68  ]
69  );
70  $item->setData('custom_attributes', $customAttributes);
71  }
72  $item->setPrice($price);
73  $item->setName($product->getName() . $suffix);
74  $item->setSku($product->getSku() . $suffix);
75  $item->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE);
76  $products[] = $item;
77  }
78  return $products;
79  }
80 }
$suffix
Definition: name.phtml:27
__construct(\Magento\Catalog\Model\ProductFactory $productFactory, \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory, \Magento\ConfigurableProduct\Model\Product\Type\VariationMatrix $variationMatrix)
$price
$attributes
Definition: matrix.phtml:13