/** * {@inheritdoc} */ public function add($productSku, Option $option) { $product = $this->productRepository->get($productSku); $allowedTypes = [ProductType::TYPE_SIMPLE, ProductType::TYPE_VIRTUAL, ConfigurableType::TYPE_CODE]; if (!in_array($product->getTypeId(), $allowedTypes)) { throw new \InvalidArgumentException('Incompatible product type'); } $eavAttribute = $this->eavConfig->getAttribute(Product::ENTITY, $option->getAttributeId()); /** @var $configurableAttribute \Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute */ $configurableAttribute = $this->configurableAttributeFactory->create(); $configurableAttribute->loadByProductAndAttribute($product, $eavAttribute); if ($configurableAttribute->getId()) { throw new CouldNotSaveException('Product already has this option'); } try { $product->setTypeId(ConfigurableType::TYPE_CODE); $product->setConfigurableAttributesData([$this->optionConverter->convertArrayFromData($option)]); $product->setStoreId($this->storeManager->getStore(Store::ADMIN_CODE)->getId()); $product->save(); } catch (\Exception $e) { throw new CouldNotSaveException('An error occurred while saving option'); } $configurableAttribute = $this->configurableAttributeFactory->create(); $configurableAttribute->loadByProductAndAttribute($product, $eavAttribute); if (!$configurableAttribute->getId()) { throw new CouldNotSaveException('An error occurred while saving option'); } return $configurableAttribute->getId(); }
/** * @param Option $option * @return array */ public function convertArrayFromData(Option $option) { $values = []; if (is_array($option->getValues())) { foreach ($option->getValues() as $value) { $values[] = $this->valueConverter->convertArrayFromData($value); } } return ['attribute_id' => $option->getAttributeId(), 'position' => $option->getPosition(), 'use_default' => $option->isUseDefault(), 'label' => $option->getLabel(), 'values' => $values]; }