Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Post.php
Go to the documentation of this file.
1 <?php
9 
10 use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
17 use Psr\Log\LoggerInterface;
20 
21 class Post extends \Magento\Contact\Controller\Index implements HttpPostActionInterface
22 {
26  private $dataPersistor;
27 
31  private $context;
32 
36  private $mail;
37 
41  private $logger;
42 
50  public function __construct(
51  Context $context,
52  ConfigInterface $contactsConfig,
53  MailInterface $mail,
54  DataPersistorInterface $dataPersistor,
55  LoggerInterface $logger = null
56  ) {
57  parent::__construct($context, $contactsConfig);
58  $this->context = $context;
59  $this->mail = $mail;
60  $this->dataPersistor = $dataPersistor;
61  $this->logger = $logger ?: ObjectManager::getInstance()->get(LoggerInterface::class);
62  }
63 
69  public function execute()
70  {
71  if (!$this->getRequest()->isPost()) {
72  return $this->resultRedirectFactory->create()->setPath('*/*/');
73  }
74  try {
75  $this->sendEmail($this->validatedParams());
76  $this->messageManager->addSuccessMessage(
77  __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.')
78  );
79  $this->dataPersistor->clear('contact_us');
80  } catch (LocalizedException $e) {
81  $this->messageManager->addErrorMessage($e->getMessage());
82  $this->dataPersistor->set('contact_us', $this->getRequest()->getParams());
83  } catch (\Exception $e) {
84  $this->logger->critical($e);
85  $this->messageManager->addErrorMessage(
86  __('An error occurred while processing your form. Please try again later.')
87  );
88  $this->dataPersistor->set('contact_us', $this->getRequest()->getParams());
89  }
90  return $this->resultRedirectFactory->create()->setPath('contact/index');
91  }
92 
97  private function sendEmail($post)
98  {
99  $this->mail->send(
100  $post['email'],
101  ['data' => new DataObject($post)]
102  );
103  }
104 
109  private function validatedParams()
110  {
111  $request = $this->getRequest();
112  if (trim($request->getParam('name')) === '') {
113  throw new LocalizedException(__('Enter the Name and try again.'));
114  }
115  if (trim($request->getParam('comment')) === '') {
116  throw new LocalizedException(__('Enter the comment and try again.'));
117  }
118  if (false === \strpos($request->getParam('email'), '@')) {
119  throw new LocalizedException(__('The email address is invalid. Verify the email address and try again.'));
120  }
121  if (trim($request->getParam('hideit')) !== '') {
122  throw new \Exception();
123  }
124 
125  return $request->getParams();
126  }
127 }
__()
Definition: __.php:13
execute()
Definition: Post.php:69
__construct(Context $context, ConfigInterface $contactsConfig, MailInterface $mail, DataPersistorInterface $dataPersistor, LoggerInterface $logger=null)
Definition: Post.php:50
Definition: Post.php:21