/** * Image upload action in iframe * * @return string */ public function execute() { try { $uploader = $this->uploaderFactory->create(['fileId' => 'datafile']); $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']); /** @var \Magento\Framework\Image\Adapter\AdapterInterface $imageAdapter */ $imageAdapter = $this->adapterFactory->create(); $uploader->addValidateCallback('catalog_product_image', $imageAdapter, 'validateUploadFile'); $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(true); /** @var \Magento\Framework\Filesystem\Directory\Read $mediaDirectory */ $mediaDirectory = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA); $config = $this->config; $result = $uploader->save($mediaDirectory->getAbsolutePath($config->getBaseTmpMediaPath())); $this->_eventManager->dispatch('swatch_gallery_upload_image_after', ['result' => $result, 'action' => $this]); unset($result['tmp_name']); unset($result['path']); $result['url'] = $this->config->getTmpMediaUrl($result['file']); $result['file'] = $result['file'] . '.tmp'; $newFile = $this->swatchHelper->moveImageFromTmp($result['file']); $this->swatchHelper->generateSwatchVariations($newFile); $fileData = ['swatch_path' => $this->swatchHelper->getSwatchMediaUrl(), 'file_path' => $newFile]; $this->getResponse()->setBody(json_encode($fileData)); } catch (\Exception $e) { $result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()]; $this->getResponse()->setBody(json_encode($result)); } }
/** * Get image types data * * @return array */ public function getImageTypes() { $imageTypes = []; foreach ($this->catalogProductMediaConfig->getMediaAttributeCodes() as $attributeCode) { /* @var $attribute Attribute */ $imageTypes[$attributeCode] = ['code' => $attributeCode, 'value' => '', 'label' => $attributeCode, 'scope' => '', 'name' => $attributeCode]; } return $imageTypes; }
/** * @dataProvider dataForExecute */ public function testExecute($fileResult, $expectedResult) { $this->uploaderFactoryMock->expects($this->once())->method('create')->willReturn($this->uploaderMock); $this->adapterFactoryMock->expects($this->once())->method('create')->willReturn($this->adapterMock); $this->filesystemMock->expects($this->once())->method('getDirectoryRead')->with('media')->willReturn($this->mediaDirectoryMock); $this->uploaderMock->expects($this->once())->method('save')->willReturn($fileResult); $this->configMock->expects($this->once())->method('getTmpMediaUrl')->with($fileResult['file'])->willReturn('http://domain.com/tpm_dir/m/a/magento.png'); $this->swatchHelperMock->expects($this->once())->method('moveImageFromTmp')->with('/m/a/magento.png.tmp')->willReturn('/m/a/magento.png'); $this->swatchHelperMock->expects($this->once())->method('generateSwatchVariations'); $this->swatchHelperMock->expects($this->once())->method('getSwatchMediaUrl')->willReturn('http://domain.com/media/path/'); $this->responseMock->expects($this->once())->method('setBody')->willReturn(json_encode($expectedResult)); $this->controller->execute(); }
public function testGetImagesJson() { $url = [['file_1.jpg', 'url_to_the_image/image_1.jpg'], ['file_2.jpg', 'url_to_the_image/image_2.jpg']]; $mediaPath = [['file_1.jpg', 'catalog/product/image_1.jpg'], ['file_2.jpg', 'catalog/product/image_2.jpg']]; $sizeMap = [['catalog/product/image_1.jpg', ['size' => 399659]], ['catalog/product/image_2.jpg', ['size' => 879394]]]; $imagesResult = [['value_id' => '2', 'file' => 'file_2.jpg', 'media_type' => 'image', 'position' => '0', 'url' => 'url_to_the_image/image_2.jpg', 'size' => 879394], ['value_id' => '1', 'file' => 'file_1.jpg', 'media_type' => 'image', 'position' => '1', 'url' => 'url_to_the_image/image_1.jpg', 'size' => 399659]]; $images = ['images' => [['value_id' => '1', 'file' => 'file_1.jpg', 'media_type' => 'image', 'position' => '1'], ['value_id' => '2', 'file' => 'file_2.jpg', 'media_type' => 'image', 'position' => '0']]]; $this->content->setElement($this->galleryMock); $this->galleryMock->expects($this->once())->method('getImages')->willReturn($images); $this->fileSystemMock->expects($this->once())->method('getDirectoryRead')->willReturn($this->readMock); $this->mediaConfigMock->expects($this->any())->method('getMediaUrl')->willReturnMap($url); $this->mediaConfigMock->expects($this->any())->method('getMediaPath')->willReturnMap($mediaPath); $this->readMock->expects($this->any())->method('stat')->willReturnMap($sizeMap); $this->jsonEncoderMock->expects($this->once())->method('encode')->willReturnCallback('json_encode'); $this->assertSame(json_encode($imagesResult), $this->content->getImagesJson()); }
/** * {@inheritdoc} */ public function create($productSku, GalleryEntry $entry, GalleryEntryContent $entryContent, $storeId = 0) { $store = $this->storeFactory->create()->load($storeId); if ($store->getId() != $storeId) { throw new NoSuchEntityException('There is no store with provided ID.'); } if (!$this->contentValidator->isValid($entryContent)) { throw new InputException('The image content is not valid.'); } $product = $this->productLoader->load($productSku); $fileContent = @base64_decode($entryContent->getData(), true); $mediaTmpPath = $this->mediaConfig->getBaseTmpMediaPath(); $mediaDirectory = $this->filesystem->getDirectoryWrite(Filesystem::MEDIA_DIR); $mediaDirectory->create($mediaTmpPath); $fileName = $entryContent->getName() . '.' . $this->mimeTypeExtensionMap[$entryContent->getMimeType()]; $relativeFilePath = $mediaTmpPath . DIRECTORY_SEPARATOR . $fileName; $absoluteFilePath = $mediaDirectory->getAbsolutePath($relativeFilePath); $mediaDirectory->writeFile($relativeFilePath, $fileContent); /** @var $productMediaGallery \Magento\Catalog\Model\Product\Attribute\Backend\Media */ $productMediaGallery = $this->getGalleryAttributeBackend($product); $imageFileUri = $productMediaGallery->addImage($product, $absoluteFilePath, $entry->getTypes(), true, $entry->isDisabled()); // Update additional fields that are still empty after addImage call $productMediaGallery->updateImage($product, $imageFileUri, array('label' => $entry->getLabel(), 'position' => $entry->getPosition(), 'disabled' => $entry->isDisabled())); $product->setStoreId($storeId); $product->save(); // Remove all temporary files $mediaDirectory->delete($relativeFilePath); // File could change its name during the move from tmp dir return $this->entryResolver->getEntryIdByFilePath($product, $productMediaGallery->getRenamedImage($imageFileUri)); }
/** * Check whether file to move exists. Getting unique name * * @param <type> $file * @return string */ protected function getUniqueFileName($file) { if ($this->fileStorageDb->checkDbUsage()) { $destFile = $this->fileStorageDb->getUniqueFilename($this->mediaConfig->getBaseMediaUrlAddition(), $file); } else { $destFile = dirname($file) . '/' . \Magento\MediaStorage\Model\File\Uploader::getNewFileName($this->mediaDirectory->getAbsolutePath($this->getAttributeSwatchPath($file))); } return $destFile; }
public function testGetImagesJson() { $url = [['file_1.jpg', 'url_to_the_image/image_1.jpg'], ['file_2.jpg', 'url_to_the_image/image_2.jpg']]; $mediaPath = [['file_1.jpg', 'catalog/product/image_1.jpg'], ['file_2.jpg', 'catalog/product/image_2.jpg']]; // @codingStandardsIgnoreStart $encodedString = '[{"value_id":"1","file":"image_1.jpg","media_type":"image","url":"http:\\/\\/magento2.dev\\/pub\\/media\\/catalog\\/product\\/image_1.jpg","size":879394},{"value_id":"2","file":"image_2.jpg","media_type":"image","url":"http:\\/\\/magento2.dev\\/pub\\/media\\/catalog\\/product\\/image`_2.jpg","size":399659}]'; // @codingStandardsIgnoreEnd $images = ['images' => [['value_id' => '1', 'file' => 'file_1.jpg', 'media_type' => 'image'], ['value_id' => '2', 'file' => 'file_2.jpg', 'media_type' => 'image']]]; $firstStat = ['size' => 879394]; $secondStat = ['size' => 399659]; $this->content->setElement($this->galleryMock); $this->galleryMock->expects($this->any())->method('getImages')->willReturn($images); $this->fileSystemMock->expects($this->once())->method('getDirectoryRead')->willReturn($this->readMock); $this->mediaConfigMock->expects($this->any())->method('getMediaUrl')->willReturnMap($url); $this->mediaConfigMock->expects($this->any())->method('getMediaPath')->willReturn($mediaPath); $this->readMock->expects($this->at(0))->method('stat')->willReturn($firstStat); $this->readMock->expects($this->at(1))->method('stat')->willReturn($secondStat); $this->jsonEncoderMock->expects($this->once())->method('encode')->willReturn($encodedString); $this->assertSame($encodedString, $this->content->getImagesJson()); }
/** * @param string $fileName * @return mixed */ protected function appendResultSaveRemoteImage($fileName) { $fileInfo = pathinfo($fileName); $tmpFileName = Uploader::getDispretionPath($fileInfo['basename']) . DIRECTORY_SEPARATOR . $fileInfo['basename']; $result['name'] = $fileInfo['basename']; $result['type'] = $this->imageAdapter->getMimeType(); $result['error'] = 0; $result['size'] = filesize($this->appendAbsoluteFileSystemPath($fileName)); $result['url'] = $this->mediaConfig->getTmpMediaUrl($tmpFileName); $result['file'] = $tmpFileName; return $result; }
/** * Get filename which is not duplicated with other files in media temporary and media directories * * @param string $fileName * @param string $dispretionPath * @return string */ protected function _getNotDuplicatedFilename($fileName, $dispretionPath) { $fileMediaName = $dispretionPath . '/' . \Magento\MediaStorage\Model\File\Uploader::getNewFileName($this->_mediaConfig->getMediaPath($fileName)); $fileTmpMediaName = $dispretionPath . '/' . \Magento\MediaStorage\Model\File\Uploader::getNewFileName($this->_mediaConfig->getTmpMediaPath($fileName)); if ($fileMediaName != $fileTmpMediaName) { if ($fileMediaName != $fileName) { return $this->_getNotDuplicatedFileName($fileMediaName, $dispretionPath); } elseif ($fileTmpMediaName != $fileName) { return $this->_getNotDuplicatedFilename($fileTmpMediaName, $dispretionPath); } } return $fileMediaName; }
/** * @return string */ public function getImagesJson() { if (is_array($this->getElement()->getValue())) { $value = $this->getElement()->getValue(); if (is_array($value['images']) && count($value['images']) > 0) { foreach ($value['images'] as &$image) { $image['url'] = $this->_mediaConfig->getMediaUrl($image['file']); } return $this->_jsonEncoder->encode($value['images']); } } return '[]'; }
protected function setUp() { $this->context = $this->getMock('Magento\\Framework\\Model\\Context', [], [], '', false); $this->registry = $this->getMock('Magento\\Framework\\Registry'); $this->storeManager = $this->getMockBuilder('Magento\\Store\\Model\\StoreManager')->disableOriginalConstructor()->setMethods(['getStore', 'getWebsite'])->getMock(); $store = $this->getMockBuilder('\\Magento\\Store\\Model\\Store')->disableOriginalConstructor()->setMethods(['getId', '__sleep', '__wakeup', 'getBaseUrl'])->getMock(); $store->expects($this->any())->method('getId')->will($this->returnValue(1)); $store->expects($this->any())->method('getBaseUrl')->will($this->returnValue('http://magento.com/media/')); $this->storeManager->expects($this->any())->method('getStore')->will($this->returnValue($store)); $this->config = $this->getMockBuilder('Magento\\Catalog\\Model\\Product\\Media\\Config')->setMethods(['getBaseMediaPath'])->disableOriginalConstructor()->getMock(); $this->config->expects($this->any())->method('getBaseMediaPath')->will($this->returnValue('catalog/product')); $this->coreFileHelper = $this->getMockBuilder('Magento\\MediaStorage\\Helper\\File\\Storage\\Database')->setMethods(['saveFile', 'deleteFolder'])->disableOriginalConstructor()->getMock(); $this->mediaDirectory = $this->getMockBuilder('Magento\\Framework\\Filesystem\\Directory\\Write')->disableOriginalConstructor()->setMethods(['create', 'isFile', 'isExist', 'getAbsolutePath'])->getMock(); $this->mediaDirectory->expects($this->once())->method('create')->will($this->returnValue(true)); $this->filesystem = $this->getMock('Magento\\Framework\\Filesystem', [], [], '', false); $this->filesystem->expects($this->once())->method('getDirectoryWrite')->with(DirectoryList::MEDIA)->will($this->returnValue($this->mediaDirectory)); $this->factory = $this->getMock('Magento\\Framework\\Image\\Factory', [], [], '', false); $this->repository = $this->getMock('Magento\\Framework\\View\\Asset\\Repository', [], [], '', false); $this->fileSystem = $this->getMock('Magento\\Framework\\View\\FileSystem', [], [], '', false); $this->scopeConfigInterface = $this->getMock('Magento\\Framework\\App\\Config\\ScopeConfigInterface'); $objectManagerHelper = new ObjectManagerHelper($this); $this->image = $objectManagerHelper->getObject('Magento\\Catalog\\Model\\Product\\Image', ['registry' => $this->registry, 'storeManager' => $this->storeManager, 'catalogProductMediaConfig' => $this->config, 'coreFileStorageDatabase' => $this->coreFileHelper, 'filesystem' => $this->filesystem, 'imageFactory' => $this->factory, 'assetRepo' => $this->repository, 'viewFileSystem' => $this->fileSystem, 'scopeConfig' => $this->scopeConfigInterface]); }
/** * @return string */ public function getImagesJson() { $value = $this->getElement()->getImages(); if (is_array($value) && array_key_exists('images', $value) && is_array($value['images']) && count($value['images'])) { $directory = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA); $images = $this->sortImagesByPosition($value['images']); foreach ($images as &$image) { $image['url'] = $this->_mediaConfig->getMediaUrl($image['file']); $fileHandler = $directory->stat($this->_mediaConfig->getMediaPath($image['file'])); $image['size'] = $fileHandler['size']; } return $this->_jsonEncoder->encode($images); } return '[]'; }
/** * Copy image and return new filename. * * @param string $file * @return string * @throws \Magento\Framework\Exception\LocalizedException */ protected function copyImage($file) { try { $destinationFile = $this->getUniqueFileName($file); if (!$this->mediaDirectory->isFile($this->mediaConfig->getMediaPath($file))) { throw new \Exception(); } if ($this->fileStorageDb->checkDbUsage()) { $this->fileStorageDb->copyFile($this->mediaDirectory->getAbsolutePath($this->mediaConfig->getMediaShortUrl($file)), $this->mediaConfig->getMediaShortUrl($destinationFile)); $this->mediaDirectory->delete($this->mediaConfig->getMediaPath($destinationFile)); } else { $this->mediaDirectory->copyFile($this->mediaConfig->getMediaPath($file), $this->mediaConfig->getMediaPath($destinationFile)); } return str_replace('\\', '/', $destinationFile); } catch (\Exception $e) { $file = $this->mediaConfig->getMediaPath($file); throw new \Magento\Framework\Exception\LocalizedException(__('We couldn\'t copy file %1. Please delete media with non-existing images and try again.', $file)); } }
/** * {@inheritdoc} */ public function create($product) { try { $this->storeManager->getStore($product->getStoreId()); } catch (\Exception $exception) { throw new NoSuchEntityException(__('There is no store with provided ID.')); } /** @var $entry ProductAttributeMediaGalleryEntryInterface */ $entry = $product->getCustomAttribute('media_gallery')->getValue(); $entryContent = $entry->getContent(); if (!$this->contentValidator->isValid($entryContent)) { throw new InputException(__('The image content is not valid.')); } $product = $this->productRepository->get($product->getSku()); $fileContent = @base64_decode($entryContent->getEntryData(), true); $mediaTmpPath = $this->mediaConfig->getBaseTmpMediaPath(); $mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA); $mediaDirectory->create($mediaTmpPath); $fileName = $entryContent->getName() . '.' . $this->mimeTypeExtensionMap[$entryContent->getMimeType()]; $relativeFilePath = $mediaTmpPath . DIRECTORY_SEPARATOR . $fileName; $absoluteFilePath = $mediaDirectory->getAbsolutePath($relativeFilePath); $mediaDirectory->writeFile($relativeFilePath, $fileContent); /** @var $productMediaGallery \Magento\Catalog\Model\Product\Attribute\Backend\Media */ $productMediaGallery = $this->getGalleryAttributeBackend($product); $imageFileUri = $productMediaGallery->addImage($product, $absoluteFilePath, $entry->getTypes(), true, $entry->isDisabled()); // Update additional fields that are still empty after addImage call $productMediaGallery->updateImage($product, $imageFileUri, ['label' => $entry->getLabel(), 'position' => $entry->getPosition(), 'disabled' => $entry->isDisabled()]); try { $this->productRepository->save($product); } catch (\Exception $e) { throw new StateException(__('Cannot save product.')); } // Remove all temporary files $mediaDirectory->delete($relativeFilePath); // File could change its name during the move from tmp dir return $this->entryResolver->getEntryIdByFilePath($product, $productMediaGallery->getRenamedImage($imageFileUri)); }
/** * @param string $localTmpFile * @return string */ protected function appendFileSystemPath($localTmpFile) { $pathToSave = $this->mediaConfig->getBaseTmpMediaPath(); return $pathToSave . $localTmpFile; }
/** * @return void */ public function clearCache() { $directory = $this->_catalogProductMediaConfig->getBaseMediaPath() . '/cache'; $this->_mediaDirectory->delete($directory); $this->_coreFileStorageDatabase->deleteFolder($this->_mediaDirectory->getAbsolutePath($directory)); }
/** * Retrieve assoc array that contains media attribute values of the product * * @return array */ public function getMediaAttributeValues() { $mediaAttributeCodes = $this->_catalogProductMediaConfig->getMediaAttributeCodes(); $mediaAttributeValues = []; foreach ($mediaAttributeCodes as $attributeCode) { $mediaAttributeValues[$attributeCode] = $this->getData($attributeCode); } return $mediaAttributeValues; }