context = $context; $this->mail = $mail; $this->dataPersistor = $dataPersistor; $this->logger = $logger ?: ObjectManager::getInstance()->get(LoggerInterface::class); } /** * Post user question * * @return Redirect */ public function execute() { if (!$this->getRequest()->isPost()) { return $this->resultRedirectFactory->create()->setPath('*/*/'); } try { $this->sendEmail($this->validatedParams()); $this->messageManager->addSuccessMessage( __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.') ); $this->dataPersistor->clear('contact_us'); } catch (LocalizedException $e) { $this->messageManager->addErrorMessage($e->getMessage()); $this->dataPersistor->set('contact_us', $this->getRequest()->getParams()); } catch (\Exception $e) { $this->logger->critical($e); $this->messageManager->addErrorMessage( __('An error occurred while processing your form. Please try again later.') ); $this->dataPersistor->set('contact_us', $this->getRequest()->getParams()); } return $this->resultRedirectFactory->create()->setPath('contact/index'); } /** * @param array $post Post data from contact form * @return void */ private function sendEmail($post) { $this->mail->send( $post['email'], ['data' => new DataObject($post)] ); } /** * @return array * @throws \Exception */ private function validatedParams() { $request = $this->getRequest(); if (trim($request->getParam('name')) === '') { throw new LocalizedException(__('Enter the Name and try again.')); } if (trim($request->getParam('comment')) === '') { throw new LocalizedException(__('Enter the comment and try again.')); } if (false === \strpos($request->getParam('email'), '@')) { throw new LocalizedException(__('The email address is invalid. Verify the email address and try again.')); } if (trim($request->getParam('hideit')) !== '') { throw new \Exception(); } return $request->getParams(); } }