Example #1
0
 /**
  * @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();
 }
Example #2
0
 /**
  * @expectedException \Magento\Framework\Exception\LocalizedException
  */
 public function testUploadInvalidJsFile()
 {
     $fileName = 'file.name';
     $this->_service = new \Magento\Theme\Model\Uploader\Service($this->_filesystemMock, $this->_fileSizeMock, $this->_uploaderFactory, ['js' => '100M']);
     $this->_uploader->expects($this->once())->method('getFileSize')->will($this->returnValue(499 * self::MB_MULTIPLIER));
     $this->_service->uploadJsFile($fileName);
 }
Example #3
0
 /**
  * @expectedException \Magento\Framework\Exception\LocalizedException
  * @expectedExceptionMessage Exception!
  */
 public function testBeforeSaveWithException()
 {
     $value = 'value';
     $groupId = 1;
     $field = 'field';
     $tmpFileName = 'tmp_file_name';
     $name = 'name';
     $path = 'path';
     $scope = 'scope';
     $scopeId = 2;
     $uploadDir = 'upload_dir';
     $fieldConfig = ['upload_dir' => $uploadDir];
     $fileData = ['tmp_name' => $tmpFileName, 'name' => $name];
     $exception = 'Exception!';
     $this->model->setValue($value);
     $this->model->setPath($path);
     $this->model->setScope($scope);
     $this->model->setScopeId($scopeId);
     $this->model->setFieldConfig($fieldConfig);
     $_FILES['groups']['tmp_name'][$groupId]['fields'][$field]['value'] = $tmpFileName;
     $this->requestDataMock->expects($this->once())->method('getTmpName')->with($path)->willReturn($tmpFileName);
     $this->requestDataMock->expects($this->once())->method('getName')->with($path)->willReturn($name);
     $this->uploaderFactoryMock->expects($this->any())->method('create')->with(['fileId' => $fileData])->willReturn($this->uploaderMock);
     $this->uploaderMock->expects($this->once())->method('save')->with($uploadDir, null)->willThrowException(new \Exception($exception));
     $this->model->beforeSave();
 }
Example #4
0
 /**
  * Upload js file
  *
  * @param string $file - Key in the $_FILES array
  * @return array
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function uploadJsFile($file)
 {
     /** @var $fileUploader \Magento\MediaStorage\Model\File\Uploader */
     $fileUploader = $this->_uploaderFactory->create(['fileId' => $file]);
     $fileUploader->setAllowedExtensions(['js']);
     $fileUploader->setAllowRenameFiles(true);
     $fileUploader->setAllowCreateFolders(true);
     $isValidFileSize = $this->_validateFileSize($fileUploader->getFileSize(), $this->getJsUploadMaxSize());
     if (!$isValidFileSize) {
         throw new \Magento\Framework\Exception\LocalizedException(__('The JS file must be less than %1M.', $this->getJsUploadMaxSizeInMb()));
     }
     $file = $fileUploader->validateFile();
     return ['filename' => $file['name'], 'content' => $this->getFileContent($file['tmp_name'])];
 }
 public function testSaveToTmp()
 {
     $path = 'design/header/logo_src';
     $fieldCode = 'header_logo_src';
     $metadata = [$fieldCode => ['path' => $path, 'backend_model' => 'Magento\\Theme\\Model\\Design\\Backend\\Image']];
     $this->metadataProvider->expects($this->once())->method('get')->willReturn($metadata);
     $this->backendModelFactory->expects($this->once())->method('createByPath')->with($path)->willReturn($this->backendModel);
     $this->uploaderFactory->expects($this->once())->method('create')->with(['fileId' => $fieldCode])->willReturn($this->uploader);
     $this->uploader->expects($this->once())->method('setAllowRenameFiles')->with(true);
     $this->uploader->expects($this->once())->method('setFilesDispersion')->with(false);
     $this->backendModel->expects($this->once())->method('getAllowedExtensions')->willReturn(['png', 'jpg']);
     $this->uploader->expects($this->once())->method('setAllowedExtensions')->with(['png', 'jpg']);
     $this->uploader->expects($this->once())->method('addValidateCallback')->with('size', $this->backendModel, 'validateMaxSize');
     $this->imageConfig->expects($this->once())->method('getAbsoluteTmpMediaPath')->willReturn('absolute/path/to/tmp/media');
     $this->uploader->expects($this->once())->method('save')->with('absolute/path/to/tmp/media')->willReturn(['file' => 'file.jpg', 'size' => '234234']);
     $this->imageConfig->expects($this->once())->method('getTmpMediaUrl')->with('file.jpg')->willReturn('http://magento2.com/pub/media/tmp/file.jpg');
     $this->assertEquals(['file' => 'file.jpg', 'size' => '234234', 'url' => 'http://magento2.com/pub/media/tmp/file.jpg'], $this->imageProcessor->saveToTmp($fieldCode));
 }
Example #6
0
 /**
  * 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;
 }
Example #7
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;
 }
Example #8
0
 /**
  * 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;
 }
Example #9
0
 /**
  * Check whether file to move exists. Getting unique name
  *
  * @param string $file
  * @param bool $forTmp
  * @return string
  */
 protected function getUniqueFileName($file, $forTmp = false)
 {
     if ($this->fileStorageDb->checkDbUsage()) {
         $destFile = $this->fileStorageDb->getUniqueFilename($this->mediaConfig->getBaseMediaUrlAddition(), $file);
     } else {
         $destinationFile = $forTmp ? $this->mediaDirectory->getAbsolutePath($this->mediaConfig->getTmpMediaPath($file)) : $this->mediaDirectory->getAbsolutePath($this->mediaConfig->getMediaPath($file));
         $destFile = dirname($file) . '/' . FileUploader::getNewFileName($destinationFile);
     }
     return $destFile;
 }
Example #10
0
 /**
  * Move file from tmp path to base path
  *
  * @param string $baseTmpPath
  * @param string $basePath
  * @param string $file
  * @return string
  */
 protected function _moveFileFromTmp($baseTmpPath, $basePath, $file)
 {
     if (strrpos($file, '.tmp') == strlen($file) - 4) {
         $file = substr($file, 0, strlen($file) - 4);
     }
     $destFile = dirname($file) . '/' . \Magento\MediaStorage\Model\File\Uploader::getNewFileName($this->getFilePath($basePath, $file));
     $this->_coreFileStorageDatabase->copyFile($this->getFilePath($baseTmpPath, $file), $this->getFilePath($basePath, $destFile));
     $this->_mediaDirectory->renameFile($this->getFilePath($baseTmpPath, $file), $this->getFilePath($basePath, $destFile));
     return str_replace('\\', '/', $destFile);
 }