/** * @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(); }
/** * Save uploaded file before saving config value * * @return $this * @throws \Magento\Framework\Exception\LocalizedException */ public function beforeSave() { $value = $this->getValue(); $tmpName = $this->_requestData->getTmpName($this->getPath()); $file = []; if ($tmpName) { $file['tmp_name'] = $tmpName; $file['name'] = $this->_requestData->getName($this->getPath()); } elseif (!empty($value['tmp_name'])) { $file['tmp_name'] = $value['tmp_name']; $file['name'] = $value['value']; } if (!empty($file)) { $uploadDir = $this->_getUploadDir(); try { $uploader = $this->_uploaderFactory->create(['fileId' => $file]); $uploader->setAllowedExtensions($this->_getAllowedExtensions()); $uploader->setAllowRenameFiles(true); $uploader->addValidateCallback('size', $this, 'validateMaxSize'); $result = $uploader->save($uploadDir); } catch (\Exception $e) { throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage())); } $filename = $result['file']; if ($filename) { if ($this->_addWhetherScopeInfo()) { $filename = $this->_prependScopeInfo($filename); } $this->setValue($filename); } } else { if (is_array($value) && !empty($value['delete'])) { $this->setValue(''); } else { $this->unsValue(); } } return $this; }
/** * Receiving uploaded file data * * @return array */ protected function getFileData() { $file = []; $value = $this->getValue(); $tmpName = $this->_requestData->getTmpName($this->getPath()); if ($tmpName) { $file['tmp_name'] = $tmpName; $file['name'] = $this->_requestData->getName($this->getPath()); } elseif (!empty($value['tmp_name'])) { $file['tmp_name'] = $value['tmp_name']; $file['name'] = isset($value['value']) ? $value['value'] : $value['name']; } return $file; }