Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ProductRepositorySave.php
Go to the documentation of this file.
1 <?php
7 
8 use Magento\Catalog\Model\ProductFactory;
16 
18 {
22  private $productAttributeRepository;
23 
27  private $productFactory;
28 
33  public function __construct(
34  ProductAttributeRepositoryInterface $productAttributeRepository,
35  ProductFactory $productFactory
36  ) {
37  $this->productAttributeRepository = $productAttributeRepository;
38  $this->productFactory = $productFactory;
39  }
40 
54  public function afterSave(
58  $saveOptions = false
59  ) {
60  if ($product->getTypeId() !== Configurable::TYPE_CODE) {
61  return $result;
62  }
63 
64  $extensionAttributes = $result->getExtensionAttributes();
65  if ($extensionAttributes === null) {
66  return $result;
67  }
68 
69  $configurableLinks = (array) $extensionAttributes->getConfigurableProductLinks();
70  $configurableOptions = (array) $extensionAttributes->getConfigurableProductOptions();
71 
72  if (empty($configurableLinks) && empty($configurableOptions)) {
73  return $result;
74  }
75 
76  $attributeCodes = [];
78  foreach ($configurableOptions as $configurableOption) {
79  $eavAttribute = $this->productAttributeRepository->get($configurableOption->getAttributeId());
80  $attributeCode = $eavAttribute->getAttributeCode();
82  }
83  $this->validateProductLinks($attributeCodes, $configurableLinks);
84  $result->getTypeInstance()->resetConfigurableAttributes($product);
85 
86  return $result;
87  }
88 
95  private function validateProductLinks(array $attributeCodes, array $linkIds)
96  {
97  $valueMap = [];
98 
99  foreach ($linkIds as $productId) {
100  $variation = $this->productFactory->create()->load($productId);
101  $valueKey = '';
102  foreach ($attributeCodes as $attributeCode) {
103  if (!$variation->getData($attributeCode)) {
104  throw new InputException(
105  __('Product with id "%1" does not contain required attribute "%2".', $productId, $attributeCode)
106  );
107  }
108  $valueKey = $valueKey . $attributeCode . ':' . $variation->getData($attributeCode) . ';';
109  }
110  if (isset($valueMap[$valueKey])) {
111  throw new InputException(
112  __(
113  'Products "%1" and "%2" have the same set of attribute values.',
114  $productId,
115  $valueMap[$valueKey]
116  )
117  );
118  }
119  $valueMap[$valueKey] = $productId;
120  }
121  }
122 }
__()
Definition: __.php:13
$attributeCode
Definition: extend.phtml:12
$extensionAttributes
Definition: payment.php:22
$productAttributeRepository
__construct(ProductAttributeRepositoryInterface $productAttributeRepository, ProductFactory $productFactory)