Skip to content

[2.3] Add fallback for product links position attribute #13437

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 36 additions & 2 deletions app/code/Magento/Catalog/Model/Product/Link/SaveHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ class SaveHandler
private $linkResource;

/**
* SaveHandler constructor.
* @param MetadataPool $metadataPool
* @param Link $linkResource
* @param ProductLinkRepositoryInterface $productLinkRepository
Expand All @@ -55,17 +56,50 @@ public function execute($entityType, $entity)
{
$link = $entity->getData($this->metadataPool->getMetadata($entityType)->getLinkField());
if ($this->linkResource->hasProductLinks($link)) {
/** @var \Magento\Catalog\Api\Data\ProductInterface $entity*/
/** @var \Magento\Catalog\Api\Data\ProductInterface $entity */
foreach ($this->productLinkRepository->getList($entity) as $link) {
$this->productLinkRepository->delete($link);
}
}
$productLinks = $entity->getProductLinks();

// Build links per type
$linksByType = [];
foreach ($entity->getProductLinks() as $link) {
$linksByType[$link->getLinkType()][] = $link;
}

// Set array position as a fallback position if necessary
foreach ($linksByType as $linkType => $links) {
if (!$this->hasPosition($links)) {
array_walk($linksByType[$linkType], function ($productLink, $position) {
$productLink->setPosition(++$position);
});
}
}

// Flatten multi-dimensional linksByType in ProductLinks
$productLinks = array_reduce($linksByType, 'array_merge', []);

if (count($productLinks) > 0) {
foreach ($entity->getProductLinks() as $link) {
$this->productLinkRepository->save($link);
}
}
return $entity;
}

/**
* Check if at least one link without position
* @param array $links
* @return bool
*/
private function hasPosition(array $links)
{
foreach ($links as $link) {
if (!array_key_exists('position', $link->getData())) {
return false;
}
}
return true;
}
}