Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
AssignWebsiteToDefaultStockPlugin.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
9 
18 use Magento\InventorySalesApi\Api\Data\SalesChannelInterfaceFactory;
22 
27 {
31  private $stockRepository;
32 
36  private $defaultStockProvider;
37 
41  private $salesChannelFactory;
42 
46  private $getAssignedStockIdForWebsite;
47 
54  public function __construct(
55  StockRepositoryInterface $stockRepository,
56  DefaultStockProviderInterface $defaultStockProvider,
57  SalesChannelInterfaceFactory $salesChannelFactory,
58  GetAssignedStockIdForWebsiteInterface $getAssignedStockIdForWebsite
59  ) {
60  $this->stockRepository = $stockRepository;
61  $this->defaultStockProvider = $defaultStockProvider;
62  $this->salesChannelFactory = $salesChannelFactory;
63  $this->getAssignedStockIdForWebsite = $getAssignedStockIdForWebsite;
64  }
65 
76  public function afterSave(
77  WebsiteResourceModel $subject,
80  ) {
81  $websiteCode = $website->getCode();
82 
84  return $result;
85  }
86 
87  // checks is some stock already assigned to this website
88  if ($this->getAssignedStockIdForWebsite->execute($websiteCode) !== null) {
89  return $result;
90  }
91 
92  $defaultStockId = $this->defaultStockProvider->getId();
93  $defaultStock = $this->stockRepository->get($defaultStockId);
94 
95  $extensionAttributes = $defaultStock->getExtensionAttributes();
96  $salesChannels = $extensionAttributes->getSalesChannels();
97  $salesChannels[] = $this->createSalesChannelByWebsiteCode($websiteCode);
98 
99  $extensionAttributes->setSalesChannels($salesChannels);
100  $this->stockRepository->save($defaultStock);
101 
102  return $result;
103  }
104 
111  private function createSalesChannelByWebsiteCode(string $websiteCode): SalesChannelInterface
112  {
113  $salesChannel = $this->salesChannelFactory->create();
114  $salesChannel->setCode($websiteCode);
115  $salesChannel->setType(SalesChannelInterface::TYPE_WEBSITE);
116  return $salesChannel;
117  }
118 }
afterSave(WebsiteResourceModel $subject, WebsiteResourceModel $result, AbstractModel $website)
$stockRepository
Definition: stock.php:19
$extensionAttributes
Definition: payment.php:22
if(!isset($_GET['website_code'])) $websiteCode
Definition: website.php:11
__construct(StockRepositoryInterface $stockRepository, DefaultStockProviderInterface $defaultStockProvider, SalesChannelInterfaceFactory $salesChannelFactory, GetAssignedStockIdForWebsiteInterface $getAssignedStockIdForWebsite)