Пример #1
0
 /**
  * @param \Magento\Framework\Object $processingParams
  * @param \Magento\Catalog\Model\Product\Option $option
  * @return array
  * @throws LocalizedException
  * @throws ProductException
  * @throws \Exception
  * @throws \Magento\Framework\Exception\InputException
  * @throws \Magento\Framework\Validator\Exception
  * @throws \Zend_File_Transfer_Exception
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function validate($processingParams, $option)
 {
     $upload = $this->httpFactory->create();
     $file = $processingParams->getFilesPrefix() . 'options_' . $option->getId() . '_file';
     try {
         $runValidation = $option->getIsRequire() || $upload->isUploaded($file);
         if (!$runValidation) {
             throw new \Magento\Framework\Validator\Exception(__('Validation failed. Required options were not filled or file was not uploaded.'));
         }
         $fileInfo = $upload->getFileInfo($file)[$file];
         $fileInfo['title'] = $fileInfo['name'];
     } catch (\Magento\Framework\Validator\Exception $e) {
         throw $e;
     } catch (\Exception $e) {
         // when file exceeds the upload_max_filesize, $_FILES is empty
         if ($this->validateContentLength()) {
             $value = $this->fileSize->getMaxFileSizeInMb();
             throw new LocalizedException(__('The file you uploaded is larger than %1 Megabytes allowed by server', $value));
         } else {
             throw new ProductException(__('Option required.'));
         }
     }
     /**
      * Option Validations
      */
     $upload = $this->buildImageValidator($upload, $option);
     /**
      * Upload process
      */
     $this->initFilesystem();
     $userValue = [];
     if ($upload->isUploaded($file) && $upload->isValid($file)) {
         $extension = pathinfo(strtolower($fileInfo['name']), PATHINFO_EXTENSION);
         $fileName = \Magento\MediaStorage\Model\File\Uploader::getCorrectFileName($fileInfo['name']);
         $dispersion = \Magento\MediaStorage\Model\File\Uploader::getDispretionPath($fileName);
         $filePath = $dispersion;
         $tmpDirectory = $this->filesystem->getDirectoryRead(DirectoryList::SYS_TMP);
         $fileHash = md5($tmpDirectory->readFile($tmpDirectory->getRelativePath($fileInfo['tmp_name'])));
         $filePath .= '/' . $fileHash . '.' . $extension;
         $fileFullPath = $this->mediaDirectory->getAbsolutePath($this->quotePath . $filePath);
         $upload->addFilter(new \Zend_Filter_File_Rename(['target' => $fileFullPath, 'overwrite' => true]));
         if ($this->product !== null) {
             $this->product->getTypeInstance()->addFileQueue(['operation' => 'receive_uploaded_file', 'src_name' => $file, 'dst_name' => $fileFullPath, 'uploader' => $upload, 'option' => $this]);
         }
         $_width = 0;
         $_height = 0;
         if ($tmpDirectory->isReadable($tmpDirectory->getRelativePath($fileInfo['tmp_name']))) {
             $imageSize = getimagesize($fileInfo['tmp_name']);
             if ($imageSize) {
                 $_width = $imageSize[0];
                 $_height = $imageSize[1];
             }
         }
         $uri = $this->filesystem->getUri(DirectoryList::MEDIA);
         $userValue = ['type' => $fileInfo['type'], 'title' => $fileInfo['name'], 'quote_path' => $uri . $this->quotePath . $filePath, 'order_path' => $uri . $this->orderPath . $filePath, 'fullpath' => $fileFullPath, 'size' => $fileInfo['size'], 'width' => $_width, 'height' => $_height, 'secret_key' => substr($fileHash, 0, 20)];
     } elseif ($upload->getErrors()) {
         $errors = $this->getValidatorErrors($upload->getErrors(), $fileInfo, $option);
         if (count($errors) > 0) {
             throw new LocalizedException(__(implode("\n", $errors)));
         }
     } else {
         throw new LocalizedException(__('Please specify the product\'s required option(s).'));
     }
     return $userValue;
 }
Пример #2
0
 /**
  * Add image to media gallery and return new filename
  *
  * @param \Magento\Catalog\Model\Product $product
  * @param string $file file path of image in file system
  * @param string|string[] $mediaAttribute code of attribute with type 'media_image',
  *                                                      leave blank if image should be only in gallery
  * @param boolean $move if true, it will move source file
  * @param boolean $exclude mark image as disabled in product page view
  * @return string
  * @throws \Magento\Framework\Exception\LocalizedException
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function addImage(\Magento\Catalog\Model\Product $product, $file, $mediaAttribute = null, $move = false, $exclude = true)
 {
     $file = $this->_mediaDirectory->getRelativePath($file);
     if (!$this->_mediaDirectory->isFile($file)) {
         throw new LocalizedException(__('The image does not exist.'));
     }
     $pathinfo = pathinfo($file);
     $imgExtensions = ['jpg', 'jpeg', 'gif', 'png'];
     if (!isset($pathinfo['extension']) || !in_array(strtolower($pathinfo['extension']), $imgExtensions)) {
         throw new LocalizedException(__('Please correct the image file type.'));
     }
     $fileName = \Magento\MediaStorage\Model\File\Uploader::getCorrectFileName($pathinfo['basename']);
     $dispretionPath = \Magento\MediaStorage\Model\File\Uploader::getDispretionPath($fileName);
     $fileName = $dispretionPath . '/' . $fileName;
     $fileName = $this->_getNotDuplicatedFilename($fileName, $dispretionPath);
     $destinationFile = $this->_mediaConfig->getTmpMediaPath($fileName);
     try {
         /** @var $storageHelper \Magento\MediaStorage\Helper\File\Storage\Database */
         $storageHelper = $this->_fileStorageDb;
         if ($move) {
             $this->_mediaDirectory->renameFile($file, $destinationFile);
             //If this is used, filesystem should be configured properly
             $storageHelper->saveFile($this->_mediaConfig->getTmpMediaShortUrl($fileName));
         } else {
             $this->_mediaDirectory->copyFile($file, $destinationFile);
             $storageHelper->saveFile($this->_mediaConfig->getTmpMediaShortUrl($fileName));
             $this->_mediaDirectory->changePermissions($destinationFile, 0777);
         }
     } catch (\Exception $e) {
         throw new LocalizedException(__('We couldn\'t move this file: %1.', $e->getMessage()));
     }
     $fileName = str_replace('\\', '/', $fileName);
     $attrCode = $this->getAttribute()->getAttributeCode();
     $mediaGalleryData = $product->getData($attrCode);
     $position = 0;
     if (!is_array($mediaGalleryData)) {
         $mediaGalleryData = ['images' => []];
     }
     foreach ($mediaGalleryData['images'] as &$image) {
         if (isset($image['position']) && $image['position'] > $position) {
             $position = $image['position'];
         }
     }
     $position++;
     $mediaGalleryData['images'][] = ['file' => $fileName, 'position' => $position, 'label' => '', 'disabled' => (int) $exclude];
     $product->setData($attrCode, $mediaGalleryData);
     if ($mediaAttribute !== null) {
         $this->setMediaAttribute($product, $mediaAttribute, $fileName);
     }
     return $fileName;
 }