/** * {@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(); }
public function testConvertArrayFromData() { $values = [$this->value]; $expected = ['attribute_id' => 3, 'position' => 333, 'use_default' => true, 'label' => 'someLabel', 'values' => $values]; $this->option->expects($this->any())->method('getValues')->will($this->returnValue($values)); $this->option->expects($this->once())->method('getAttributeId')->will($this->returnValue($expected['attribute_id'])); $this->option->expects($this->once())->method('getPosition')->will($this->returnValue($expected['position'])); $this->option->expects($this->once())->method('isUseDefault')->will($this->returnValue($expected['use_default'])); $this->option->expects($this->once())->method('getLabel')->will($this->returnValue($expected['label'])); $this->valueConverter->expects($this->once())->method('convertArrayFromData')->with($this->equalTo($values[0]))->will($this->returnValue($values[0])); $result = $this->converter->convertArrayFromData($this->option); $this->assertEquals($expected, $result); }