|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright © Magento, Inc. All rights reserved. |
| 4 | + * See COPYING.txt for license details. |
| 5 | + */ |
| 6 | +use Magento\Catalog\Api\ProductRepositoryInterface; |
| 7 | +use Magento\Catalog\Model\Product; |
| 8 | +use Magento\Catalog\Model\Product\Attribute\Source\Status; |
| 9 | +use Magento\Catalog\Model\Product\Type; |
| 10 | +use Magento\Catalog\Model\Product\Visibility; |
| 11 | +use Magento\GroupedProduct\Model\Product\Type\Grouped; |
| 12 | +use Magento\TestFramework\Helper\Bootstrap; |
| 13 | + |
| 14 | +/** @var ProductRepositoryInterface $productRepository */ |
| 15 | +$productRepository = Bootstrap::getObjectManager() |
| 16 | + ->get(ProductRepositoryInterface::class); |
| 17 | + |
| 18 | +$productLinkFactory = Bootstrap::getObjectManager() |
| 19 | + ->get(\Magento\Catalog\Api\Data\ProductLinkInterfaceFactory::class); |
| 20 | +$productIds = ['11', '22']; |
| 21 | + |
| 22 | +foreach ($productIds as $productId) { |
| 23 | + /** @var $product Product */ |
| 24 | + $product = Bootstrap::getObjectManager()->create(Product::class); |
| 25 | + $product->setTypeId(Type::TYPE_SIMPLE) |
| 26 | + ->setId($productId) |
| 27 | + ->setWebsiteIds([1]) |
| 28 | + ->setAttributeSetId(4) |
| 29 | + ->setName('Simple ' . $productId) |
| 30 | + ->setSku('simple_' . $productId) |
| 31 | + ->setPrice(100) |
| 32 | + ->setVisibility(Visibility::VISIBILITY_BOTH) |
| 33 | + ->setStatus(Status::STATUS_ENABLED) |
| 34 | + ->setStockData(['use_config_manage_stock' => 1, 'qty' => 100, 'is_qty_decimal' => 0, 'is_in_stock' => 1]); |
| 35 | + |
| 36 | + $linkedProducts[] = $productRepository->save($product); |
| 37 | +} |
| 38 | + |
| 39 | +/** @var $product Product */ |
| 40 | +$product = Bootstrap::getObjectManager()->create(Product::class); |
| 41 | + |
| 42 | +$product->setTypeId(Grouped::TYPE_CODE) |
| 43 | + ->setId(1) |
| 44 | + ->setWebsiteIds([1]) |
| 45 | + ->setAttributeSetId(4) |
| 46 | + ->setName('Grouped Product') |
| 47 | + ->setSku('grouped') |
| 48 | + ->setVisibility(Visibility::VISIBILITY_BOTH) |
| 49 | + ->setStatus(Status::STATUS_ENABLED) |
| 50 | + ->setStockData(['use_config_manage_stock' => 1, 'is_in_stock' => 1]); |
| 51 | + |
| 52 | +foreach ($linkedProducts as $linkedProduct) { |
| 53 | + /** @var \Magento\Catalog\Api\Data\ProductLinkInterface $productLink */ |
| 54 | + $productLink = $productLinkFactory->create(); |
| 55 | + $productLink->setSku($product->getSku()) |
| 56 | + ->setLinkType('associated') |
| 57 | + ->setLinkedProductSku($linkedProduct->getSku()) |
| 58 | + ->setLinkedProductType($linkedProduct->getTypeId()) |
| 59 | + ->getExtensionAttributes() |
| 60 | + ->setQty(1); |
| 61 | + $newLinks[] = $productLink; |
| 62 | +} |
| 63 | + |
| 64 | +$product->setProductLinks($newLinks); |
| 65 | + |
| 66 | +$productRepository->save($product); |
0 commit comments