filesystem = $filesystem; $this->ioFile = $ioFile; $this->fileUploaderFactory = $fileUploaderFactory; $this->synonymRepository = $synonymRepository; $this->synonymFactory = $synonymFactory; $this->csv = $csv; $this->indexerFactory = $indexerFactory; } /** * {@inheritdoc} */ public function execute() { $resultRedirect = $this->resultRedirectFactory->create(); $data = $this->getRequest()->getPostValue(); $storeId = (int) $this->getRequest()->getParam(SynonymInterface::STORE_ID); $count = 0; if ($data) { try { $file = $this->uploadFile(); $csvData = $this->csv->getData($file); foreach ($csvData as $data) { $term = ($data && is_array($data)) ? implode(',', $data) : null; if ($term) { try { $model = $this->synonymFactory->create() ->setStoreId($storeId) ->setTerm($term); $this->synonymRepository->save($model); } catch (AlreadyExistsException $ex) { continue; } catch (CouldNotSaveException $ex) { continue; } $count++; } } $this->invalidateIndex(); $this->ioFile->rm($file); } catch (LocalizedException $ex) { $this->messageManager->addErrorMessage($ex->getMessage()); return $resultRedirect->setPath('*/*/import'); } catch (\Exception $ex) { $this->messageManager->addErrorMessage(__('Something went wrong. Please try again')); return $resultRedirect->setPath('*/*/import'); } if ($count > 0) { $this->messageManager->addSuccessMessage(__('%1 Synonym(s) has been imported', $count)); } else { $this->messageManager->addWarningMessage('Imported file was empty or all terms are already exist'); } } else { $this->messageManager->addErrorMessage('There are no data to import'); return $resultRedirect->setPath('*/*/import'); } return $resultRedirect->setPath('*/*/'); } /** * @return string * @throws LocalizedException * @throws \Exception */ private function uploadFile() { $path = $this->filesystem->getDirectoryRead( DirectoryList::MEDIA )->getAbsolutePath( self::MEDIA_PATH ); $this->ioFile->checkAndCreateFolder($path); try { /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */ $uploader = $this->fileUploaderFactory->create(['fileId' => 'amasty_elastic_file_upload']); $uploader->setAllowedExtensions(['csv']); $uploader->setAllowRenameFiles(true); $result = $uploader->save($path); } catch (\Exception $ex) { throw new LocalizedException(__($ex->getMessage())); } if (isset($result['file']) && $this->ioFile->fileExists($path . '/' . $result['file'])) { $file = $path . '/' . $result['file']; } else { throw new LocalizedException(__('Something wend wrong during saving file')); } return $file; } private function invalidateIndex() { $indexer = $this->indexerFactory->create()->load(DataMapperResolver::DEFAULT_DATA_INDEXER); $indexer->invalidate(); } }