/** * Generates child products for configurable product * * @param \Magento\Catalog\Api\Data\ProductAttributeInterface $configurableAttribute * @return array * @throws \Exception */ protected function createConfigurableChildren($configurableAttribute) { $availableOptions = $configurableAttribute->getOptions(); /* Not sure why the zero index has no value for all attributes. Maybe will be fixed in next Magento versions */ unset($availableOptions[0]); if (!count($availableOptions) > 0) { throw new \Exception('The selected configurable attribute has no values'); } // Create child simple products $availableProductsCount = $this->getCount() - $this->processedProducts - 1; if ($availableProductsCount >= self::CONFIGURABLE_CHILD_LIMIT) { $childrenLimit = self::CONFIGURABLE_CHILD_LIMIT; } else { $childrenLimit = $availableProductsCount; } if ($childrenLimit > count($availableOptions)) { $childrenLimit = count($availableOptions); } $childrenCount = rand(1, $childrenLimit); $childProductsIds = $configurableOptionsValues = []; for ($optCount = 0; $optCount < $childrenCount; $optCount++) { $product = $this->createSimpleProduct(true, true); $currentOptionId = array_rand($availableOptions); $optValueId = $availableOptions[$currentOptionId]->getValue(); unset($availableOptions[$currentOptionId]); $product->setCustomAttribute($configurableAttribute->getAttributeCode(), $optValueId); $optionValue = $this->optionValue; $optionValue->setValueIndex($optValueId); $configurableOptionsValues[] = $optionValue; $product = $this->productRepository->save($product); $childProductsIds[] = $product->getId(); } return ['child_products_ids' => $childProductsIds, 'configurable_options_values' => $configurableOptionsValues]; }