<?php

    namespace MNM\Spitzner\Plugin;

    class FilterGalleryImages
    {
        /**
         *
         * @param \Magento\Catalog\Block\Product\View\Gallery $subject
         * @param \Magento\Framework\Data\Collection $images
         * @return \Magento\Framework\Data\Collection
         */
        public function afterGetGalleryImages(\Magento\Catalog\Block\Product\View\Gallery $subject, \Magento\Framework\Data\Collection $images)
        {
            $product = $subject->getProduct();

            foreach ($images->getItems() as $key => $image) {
                foreach (array_keys($product->getMediaAttributes()) as $attribute) {
                    if ($image->getFile() == $product->getData($attribute)) {
                        $types = $image->getData('types') ?? [];
                        $types[] = $attribute;
                        $image->setData('types', $types);
                    }
                }

                if($image->getData('types') && !(count($image->getData('types')) == 0 || in_array('image', $image->getData('types')))) {
                    $images->removeItemByKey($key);
                }
            }

            return $images;
        }
    }