Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ProductWebsiteLinkRepository.php
Go to the documentation of this file.
1 <?php
7 namespace Magento\Catalog\Model;
8 
12 
14 {
18  protected $productRepository;
19 
23  public function __construct(
25  ) {
26  $this->productRepository = $productRepository;
27  }
28 
32  public function save(ProductWebsiteLinkInterface $productWebsiteLink)
33  {
34  if (!$productWebsiteLink->getWebsiteId()) {
35  throw new InputException(__('There are not websites for assign to product'));
36  }
37  $product = $this->productRepository->get($productWebsiteLink->getSku());
38  $product->setWebsiteIds(array_merge($product->getWebsiteIds(), [$productWebsiteLink->getWebsiteId()]));
39  try {
40  $this->productRepository->save($product);
41  } catch (\Exception $e) {
42  throw new CouldNotSaveException(
43  __(
44  'Could not assign product "%1" to websites "%2"',
45  $product->getId(),
46  $productWebsiteLink->getWebsiteId()
47  ),
48  $e
49  );
50  }
51  return true;
52  }
53 
57  public function delete(ProductWebsiteLinkInterface $productLink)
58  {
59  return $this->deleteById($productLink->getSku(), $productLink->getSku());
60  }
61 
65  public function deleteById($sku, $websiteId)
66  {
67  $product = $this->productRepository->get($sku);
68  $product->setWebsiteIds(array_diff($product->getWebsiteIds(), [$websiteId]));
69 
70  try {
71  $this->productRepository->save($product);
72  } catch (\Exception $e) {
73  throw new CouldNotSaveException(
74  __(
75  'Could not save product "%1" with websites %2',
76  $product->getId(),
77  implode(', ', $product->getWebsiteIds())
78  ),
79  $e
80  );
81  }
82  return true;
83  }
84 }
__()
Definition: __.php:13