Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Management.php
Go to the documentation of this file.
1 <?php
8 
13 
15 {
19  protected $productRepository;
20 
24  protected $linkTypeProvider;
25 
30  public function __construct(
33  ) {
34  $this->productRepository = $productRepository;
35  $this->linkTypeProvider = $linkTypeProvider;
36  }
37 
41  public function getLinkedItemsByType($sku, $type)
42  {
43  $output = [];
44 
45  $linkTypes = $this->linkTypeProvider->getLinkTypes();
46 
47  if (!isset($linkTypes[$type])) {
48  throw new NoSuchEntityException(
49  __('The "%1" link type is unknown. Verify the type and try again.', (string)$type)
50  );
51  }
52  $product = $this->productRepository->get($sku);
53  $links = $product->getProductLinks();
54 
55  // Only return the links of type specified
56  foreach ($links as $link) {
57  if ($link->getLinkType() == $type) {
58  $output[] = $link;
59  }
60  }
61 
62  return $output;
63  }
64 
68  public function setProductLinks($sku, array $items)
69  {
70  $linkTypes = $this->linkTypeProvider->getLinkTypes();
71 
72  // Check if product link type is set and correct
73  if (!empty($items)) {
74  foreach ($items as $newLink) {
75  $type = $newLink->getLinkType();
76  if ($type == null) {
77  throw InputException::requiredField("linkType");
78  }
79  if (!isset($linkTypes[$type])) {
80  throw new NoSuchEntityException(
81  __('The "%1" link type wasn\'t found. Verify the type and try again.', $type)
82  );
83  }
84  }
85  }
86 
87  $product = $this->productRepository->get($sku);
88 
89  // Replace only links of the specified type
90  $existingLinks = $product->getProductLinks();
91  $newLinks = [];
92  if (!empty($existingLinks)) {
93  foreach ($existingLinks as $link) {
94  if ($link->getLinkType() != $type) {
95  $newLinks[] = $link;
96  }
97  }
98  $newLinks = array_merge($newLinks, $items);
99  } else {
100  $newLinks = $items;
101  }
102  $product->setProductLinks($newLinks);
103  try {
104  $this->productRepository->save($product);
105  } catch (\Exception $exception) {
106  throw new CouldNotSaveException(__('The linked products data is invalid. Verify the data and try again.'));
107  }
108 
109  return true;
110  }
111 }
__()
Definition: __.php:13
$type
Definition: item.phtml:13
$newLinks
$items