Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
CategoryLinkRepository.php
Go to the documentation of this file.
1 <?php
7 namespace Magento\Catalog\Model;
8 
11 
13 {
18 
22  protected $productRepository;
23 
28  public function __construct(
31  ) {
32  $this->categoryRepository = $categoryRepository;
33  $this->productRepository = $productRepository;
34  }
35 
39  public function save(\Magento\Catalog\Api\Data\CategoryProductLinkInterface $productLink)
40  {
41  $category = $this->categoryRepository->get($productLink->getCategoryId());
42  $product = $this->productRepository->get($productLink->getSku());
43  $productPositions = $category->getProductsPosition();
44  $productPositions[$product->getId()] = $productLink->getPosition();
45  $category->setPostedProducts($productPositions);
46  try {
47  $category->save();
48  } catch (\Exception $e) {
49  throw new CouldNotSaveException(
50  __(
51  'Could not save product "%1" with position %2 to category %3',
52  $product->getId(),
53  $productLink->getPosition(),
54  $category->getId()
55  ),
56  $e
57  );
58  }
59  return true;
60  }
61 
66  {
67  return $this->deleteByIds($productLink->getCategoryId(), $productLink->getSku());
68  }
69 
73  public function deleteByIds($categoryId, $sku)
74  {
75  $category = $this->categoryRepository->get($categoryId);
76  $product = $this->productRepository->get($sku);
77  $productPositions = $category->getProductsPosition();
78 
79  $productID = $product->getId();
80  if (!isset($productPositions[$productID])) {
81  throw new InputException(__("The category doesn't contain the specified product."));
82  }
83  $backupPosition = $productPositions[$productID];
84  unset($productPositions[$productID]);
85 
86  $category->setPostedProducts($productPositions);
87  try {
88  $category->save();
89  } catch (\Exception $e) {
90  throw new CouldNotSaveException(
91  __(
92  'Could not save product "%product" with position %position to category %category',
93  [
94  "product" => $product->getId(),
95  "position" => $backupPosition,
96  "category" => $category->getId()
97  ]
98  ),
99  $e
100  );
101  }
102  return true;
103  }
104 }
__()
Definition: __.php:13