|
4 | 4 |
|
5 | 5 | namespace Omikron\Factfinder\Model\Config\Backend; |
6 | 6 |
|
| 7 | +use Exception; |
7 | 8 | use Magento\Config\Model\Config\Backend\File; |
8 | 9 | use Magento\Framework\App\Filesystem\DirectoryList; |
| 10 | +use Magento\Framework\Exception\LocalizedException; |
| 11 | +use Magento\MediaStorage\Model\File\Uploader; |
9 | 12 |
|
| 13 | +/** |
| 14 | + * @SuppressWarnings(PHPMD) |
| 15 | + */ |
10 | 16 | class Rsa extends File |
11 | 17 | { |
| 18 | + public function beforeSave() |
| 19 | + { |
| 20 | + $value = $this->getValue(); |
| 21 | + $file = $this->getFileData(); |
| 22 | + |
| 23 | + if (!empty($file)) { |
| 24 | + $uploadDir = $this->_getUploadDir(); |
| 25 | + try { |
| 26 | + /** @var Uploader $uploader */ |
| 27 | + $uploader = $this->_uploaderFactory->create(['fileId' => $file]); |
| 28 | + $uploader->setAllowedExtensions($this->_getAllowedExtensions()); |
| 29 | + $uploader->setAllowRenameFiles(true); |
| 30 | + $uploader->addValidateCallback('size', $this, 'validateMaxSize'); |
| 31 | + $result = $uploader->save($uploadDir); |
| 32 | + } catch (Exception $e) { |
| 33 | + throw new LocalizedException(__('%1', $e->getMessage())); |
| 34 | + } |
| 35 | + if ($result !== false) { |
| 36 | + $filename = $result['file']; |
| 37 | + if ($this->_addWhetherScopeInfo()) { |
| 38 | + $filename = $this->_prependScopeInfo($filename); |
| 39 | + } |
| 40 | + $this->setValue($filename); |
| 41 | + } |
| 42 | + } else { |
| 43 | + if (is_array($value) && !empty($value['delete'])) { |
| 44 | + $this->setValue(''); |
| 45 | + } elseif (is_array($value) && !empty($value['value'])) { |
| 46 | + $this->setValueAfterValidation($value['value']); |
| 47 | + } else { |
| 48 | + $this->unsValue(); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return $this; |
| 53 | + } |
| 54 | + |
12 | 55 | protected function getUploadDirPath($uploadDir) |
13 | 56 | { |
14 | 57 | return $this->_filesystem->getDirectoryWrite(DirectoryList::CONFIG)->getAbsolutePath($uploadDir); |
15 | 58 | } |
| 59 | + |
| 60 | + private function setValueAfterValidation(string $value): void |
| 61 | + { |
| 62 | + // avoid intercepting value |
| 63 | + if (preg_match('/[^a-z0-9_\/\\-\\.]+/i', $value)) { |
| 64 | + throw new LocalizedException(__('Invalid file name')); |
| 65 | + } |
| 66 | + |
| 67 | + $this->setValue($value); |
| 68 | + } |
16 | 69 | } |
0 commit comments