@@ -31,6 +31,7 @@ class SaveHandler
31
31
private $ linkResource ;
32
32
33
33
/**
34
+ * SaveHandler constructor.
34
35
* @param MetadataPool $metadataPool
35
36
* @param Link $linkResource
36
37
* @param ProductLinkRepositoryInterface $productLinkRepository
@@ -55,17 +56,50 @@ public function execute($entityType, $entity)
55
56
{
56
57
$ link = $ entity ->getData ($ this ->metadataPool ->getMetadata ($ entityType )->getLinkField ());
57
58
if ($ this ->linkResource ->hasProductLinks ($ link )) {
58
- /** @var \Magento\Catalog\Api\Data\ProductInterface $entity*/
59
+ /** @var \Magento\Catalog\Api\Data\ProductInterface $entity */
59
60
foreach ($ this ->productLinkRepository ->getList ($ entity ) as $ link ) {
60
61
$ this ->productLinkRepository ->delete ($ link );
61
62
}
62
63
}
63
- $ productLinks = $ entity ->getProductLinks ();
64
+
65
+ // Build links per type
66
+ $ linksByType = [];
67
+ foreach ($ entity ->getProductLinks () as $ link ) {
68
+ $ linksByType [$ link ->getLinkType ()][] = $ link ;
69
+ }
70
+
71
+ // Set array position as a fallback position if necessary
72
+ foreach ($ linksByType as $ linkType => $ links ) {
73
+ if (!$ this ->hasPosition ($ links )) {
74
+ array_walk ($ linksByType [$ linkType ], function ($ productLink , $ position ) {
75
+ $ productLink ->setPosition (++$ position );
76
+ });
77
+ }
78
+ }
79
+
80
+ // Flatten multi-dimensional linksByType in ProductLinks
81
+ $ productLinks = array_reduce ($ linksByType , 'array_merge ' , []);
82
+
64
83
if (count ($ productLinks ) > 0 ) {
65
84
foreach ($ entity ->getProductLinks () as $ link ) {
66
85
$ this ->productLinkRepository ->save ($ link );
67
86
}
68
87
}
69
88
return $ entity ;
70
89
}
90
+
91
+ /**
92
+ * Check if at least one link without position
93
+ * @param array $links
94
+ * @return bool
95
+ */
96
+ private function hasPosition (array $ links )
97
+ {
98
+ foreach ($ links as $ link ) {
99
+ if (!array_key_exists ('position ' , $ link ->getData ())) {
100
+ return false ;
101
+ }
102
+ }
103
+ return true ;
104
+ }
71
105
}
0 commit comments