13
13
14
14
/**
15
15
* This is a plugin to \Magento\Catalog\Model\Product.
16
- * It is to add media gallery identities to product identities.
16
+ * It is used to add media gallery identities to product identities for invalidation purposes .
17
17
*/
18
18
class UpdateIdentities
19
19
{
@@ -31,15 +31,15 @@ public function __construct(SerializerInterface $serializer)
31
31
}
32
32
33
33
/**
34
- * Set product media gallery changed after add image to the product
34
+ * Flag product media gallery as changed after adding or updating image, or on product removal
35
35
*
36
36
* @param Product $subject
37
37
* @param array $result
38
38
* @return array
39
39
*/
40
40
public function afterGetIdentities (Product $ subject , array $ result ): array
41
41
{
42
- if ($ subject ->isDeleted () || $ this ->isMediaGalleryChanged ($ subject )) {
42
+ if (! $ subject ->isObjectNew () && ( $ subject -> isDeleted () || $ this ->isMediaGalleryChanged ($ subject) )) {
43
43
$ result [] = sprintf ('%s_%s ' , ResolverCacheIdentity::CACHE_TAG , $ subject ->getId ());
44
44
}
45
45
return $ result ;
@@ -53,12 +53,29 @@ public function afterGetIdentities(Product $subject, array $result): array
53
53
*/
54
54
private function isMediaGalleryChanged (Product $ product ): bool
55
55
{
56
- $ mediaGalleryImages = $ product ->getMediaGallery ('images ' );
56
+ if (!$ product ->hasDataChanges ()) {
57
+ return false ;
58
+ }
59
+
60
+ $ mediaGalleryImages = $ product ->getMediaGallery ('images ' ) ?? [];
61
+
62
+ $ origMediaGalleryImages = $ product ->getOrigData ('media_gallery ' )['images ' ] ?? [];
63
+
64
+ $ origMediaGalleryImageKeys = array_keys ($ origMediaGalleryImages );
65
+ $ mediaGalleryImageKeys = array_keys ($ mediaGalleryImages );
66
+
67
+ if ($ origMediaGalleryImageKeys !== $ mediaGalleryImageKeys ) {
68
+ return false ;
69
+ }
70
+
71
+ // remove keys from original array that are not in new array; some keys are omitted from the new array on save
72
+ foreach ($ mediaGalleryImages as $ key => $ mediaGalleryImage ) {
73
+ $ origMediaGalleryImages [$ key ] = array_intersect_key ($ origMediaGalleryImages [$ key ], $ mediaGalleryImage );
74
+ }
75
+
57
76
$ mediaGalleryImagesSerializedString = $ this ->serializer ->serialize ($ mediaGalleryImages );
58
- $ origMediaGallery = $ product ->getOrigData ('media_gallery ' );
59
- $ origMediaGalleryImages = is_array ($ origMediaGallery ) && array_key_exists ('images ' , $ origMediaGallery )
60
- ? $ origMediaGallery ['images ' ] : null ;
61
77
$ origMediaGalleryImagesSerializedString = $ this ->serializer ->serialize ($ origMediaGalleryImages );
78
+
62
79
return $ origMediaGalleryImagesSerializedString != $ mediaGalleryImagesSerializedString ;
63
80
}
64
81
}
0 commit comments