/** * {@inheritdoc} */ public function add($productSku, \Magento\Catalog\Service\V1\Product\CustomOptions\Data\Option $option) { $product = $this->productRepository->get($productSku); if ($option->getOptionId()) { throw new InputException('Unable to save option. Please, check input data.'); } $optionData = $this->optionConverter->convert($option); $product->setCanSaveCustomOptions(true); $product->setProductOptions([$optionData]); $existingOptions = $product->getOptions(); try { $product->save(); } catch (\Exception $e) { throw new CouldNotSaveException('Could not save product option'); } $productId = $product->getId(); $product->reset(); $product->load($productId); $currentOptions = $product->getOptions(); $newID = array_diff(array_keys($currentOptions), array_keys($existingOptions)); if (empty($newID)) { throw new CouldNotSaveException('Could not save product option'); } $newID = current($newID); /** @var \Magento\Catalog\Model\Product\Option $newOption */ $newOption = $currentOptions[$newID]; $data = array(Data\Option::OPTION_ID => $newOption->getId(), Data\Option::TITLE => $newOption->getTitle(), Data\Option::TYPE => $newOption->getType(), Data\Option::IS_REQUIRE => $newOption->getIsRequire(), Data\Option::SORT_ORDER => $newOption->getSortOrder(), Data\Option::METADATA => $this->optionMetadataReader->read($newOption)); $optionDataObject = $this->optionBuilder->populateWithArray($data)->create(); return $optionDataObject; }
/** * Convert data object to array * * @param \Magento\Catalog\Service\V1\Product\CustomOptions\Data\Option $option * @return array */ public function convert(\Magento\Catalog\Service\V1\Product\CustomOptions\Data\Option $option) { $output = ['option_id' => $option->getOptionId(), 'title' => $option->getTitle(), 'type' => $option->getType(), 'sort_order' => $option->getSortOrder(), 'is_require' => $option->getIsRequire()]; $output = array_merge($output, $this->metadataConverter->convert($option)); return $output; }