/** * Save image information to DB. * * @param \Magento\Catalog\Model\Product $product * @param array $images * @return void */ protected function storeImage($product, $images) { $baseImage = ''; $i = 1; $mediaAttribute = $this->eavConfig->getAttribute('catalog_product', 'media_gallery'); foreach ($images as $image) { if (empty($image)) { $this->errors[] = $product->getSku(); continue; } if (strpos($image, '_main') !== false) { $baseImage = $image; } $id = $this->galleryResource->insertGallery(['attribute_id' => $mediaAttribute->getAttributeId(), 'entity_id' => $product->getId(), 'value' => $image]); $this->galleryResource->insertGalleryValueInStore(['value_id' => $id, 'store_id' => \Magento\Store\Model\Store::DEFAULT_STORE_ID, 'entity_id' => $product->getId(), 'label' => 'Image', 'position' => $i, 'disables' => 0]); $this->galleryResource->bindValueToEntity($id, $product->getId()); $i++; } if (empty($baseImage)) { $baseImage = $images[0]; } if ($baseImage) { $imageAttribute = $product->getResource()->getAttribute('image'); $smallImageAttribute = $product->getResource()->getAttribute('small_image'); $thumbnailAttribute = $product->getResource()->getAttribute('thumbnail'); $adapter = $product->getResource()->getConnection(); foreach ([$imageAttribute, $smallImageAttribute, $thumbnailAttribute] as $attribute) { $table = $imageAttribute->getBackend()->getTable(); /** @var \Magento\Framework\DB\Adapter\AdapterInterface $adapter*/ $data = [$attribute->getBackend()->getEntityIdField() => $product->getId(), 'attribute_id' => $attribute->getId(), 'value' => $baseImage]; $adapter->insertOnDuplicate($table, $data, ['value']); } } }
/** * Check whether attribute instance (attribute, backend, frontend or source) has method and applicable * * @param AbstractAttribute|\Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend|\Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend|\Magento\Eav\Model\Entity\Attribute\Source\AbstractSource $instance * @param string $method * @param array $args array of arguments * @return boolean */ protected function _isCallableAttributeInstance($instance, $method, $args) { if ($instance instanceof \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend && ($method == 'beforeSave' || $method == 'afterSave')) { $attributeCode = $instance->getAttribute()->getAttributeCode(); if (isset($args[0]) && $args[0] instanceof \Magento\Framework\DataObject && $args[0]->getData($attributeCode) === false) { return false; } } return parent::_isCallableAttributeInstance($instance, $method, $args); }