NewAction.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. <?php
  2. /**
  3. *
  4. * Copyright © Magento, Inc. All rights reserved.
  5. * See COPYING.txt for license details.
  6. */
  7. namespace Magento\Newsletter\Controller\Subscriber;
  8. use Magento\Customer\Api\AccountManagementInterface as CustomerAccountManagement;
  9. use Magento\Customer\Model\Session;
  10. use Magento\Customer\Model\Url as CustomerUrl;
  11. use Magento\Framework\App\Action\Context;
  12. use Magento\Framework\App\Action\HttpPostActionInterface;
  13. use Magento\Framework\App\Config\ScopeConfigInterface;
  14. use Magento\Framework\App\ObjectManager;
  15. use Magento\Framework\Exception\LocalizedException;
  16. use Magento\Framework\Phrase;
  17. use Magento\Framework\Validator\EmailAddress as EmailValidator;
  18. use Magento\Newsletter\Controller\Subscriber as SubscriberController;
  19. use Magento\Newsletter\Model\Subscriber;
  20. use Magento\Store\Model\ScopeInterface;
  21. use Magento\Store\Model\StoreManagerInterface;
  22. use Magento\Newsletter\Model\SubscriberFactory;
  23. /**
  24. * New newsletter subscription action
  25. *
  26. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  27. */
  28. class NewAction extends SubscriberController implements HttpPostActionInterface
  29. {
  30. /**
  31. * @var CustomerAccountManagement
  32. */
  33. protected $customerAccountManagement;
  34. /**
  35. * @var EmailValidator
  36. */
  37. private $emailValidator;
  38. /**
  39. * Initialize dependencies.
  40. *
  41. * @param Context $context
  42. * @param SubscriberFactory $subscriberFactory
  43. * @param Session $customerSession
  44. * @param StoreManagerInterface $storeManager
  45. * @param CustomerUrl $customerUrl
  46. * @param CustomerAccountManagement $customerAccountManagement
  47. * @param EmailValidator $emailValidator
  48. */
  49. public function __construct(
  50. Context $context,
  51. SubscriberFactory $subscriberFactory,
  52. Session $customerSession,
  53. StoreManagerInterface $storeManager,
  54. CustomerUrl $customerUrl,
  55. CustomerAccountManagement $customerAccountManagement,
  56. EmailValidator $emailValidator = null
  57. ) {
  58. $this->customerAccountManagement = $customerAccountManagement;
  59. $this->emailValidator = $emailValidator ?: ObjectManager::getInstance()->get(EmailValidator::class);
  60. parent::__construct(
  61. $context,
  62. $subscriberFactory,
  63. $customerSession,
  64. $storeManager,
  65. $customerUrl
  66. );
  67. }
  68. /**
  69. * Validates that the email address isn't being used by a different account.
  70. *
  71. * @param string $email
  72. * @throws LocalizedException
  73. * @return void
  74. */
  75. protected function validateEmailAvailable($email)
  76. {
  77. $websiteId = $this->_storeManager->getStore()->getWebsiteId();
  78. if ($this->_customerSession->isLoggedIn()
  79. && ($this->_customerSession->getCustomerDataObject()->getEmail() !== $email
  80. && !$this->customerAccountManagement->isEmailAvailable($email, $websiteId))
  81. ) {
  82. throw new LocalizedException(
  83. __('This email address is already assigned to another user.')
  84. );
  85. }
  86. }
  87. /**
  88. * Validates that if the current user is a guest, that they can subscribe to a newsletter.
  89. *
  90. * @throws LocalizedException
  91. * @return void
  92. */
  93. protected function validateGuestSubscription()
  94. {
  95. if ($this->_objectManager->get(ScopeConfigInterface::class)
  96. ->getValue(
  97. Subscriber::XML_PATH_ALLOW_GUEST_SUBSCRIBE_FLAG,
  98. ScopeInterface::SCOPE_STORE
  99. ) != 1
  100. && !$this->_customerSession->isLoggedIn()
  101. ) {
  102. throw new LocalizedException(
  103. __(
  104. 'Sorry, but the administrator denied subscription for guests. Please <a href="%1">register</a>.',
  105. $this->_customerUrl->getRegisterUrl()
  106. )
  107. );
  108. }
  109. }
  110. /**
  111. * Validates the format of the email address
  112. *
  113. * @param string $email
  114. * @throws LocalizedException
  115. * @return void
  116. */
  117. protected function validateEmailFormat($email)
  118. {
  119. if (!$this->emailValidator->isValid($email)) {
  120. throw new LocalizedException(__('Please enter a valid email address.'));
  121. }
  122. }
  123. /**
  124. * New subscription action
  125. *
  126. * @return void
  127. */
  128. public function execute()
  129. {
  130. if ($this->getRequest()->isPost() && $this->getRequest()->getPost('email')) {
  131. $email = (string)$this->getRequest()->getPost('email');
  132. try {
  133. $this->validateEmailFormat($email);
  134. $this->validateGuestSubscription();
  135. $this->validateEmailAvailable($email);
  136. $subscriber = $this->_subscriberFactory->create()->loadByEmail($email);
  137. if ($subscriber->getId()
  138. && (int) $subscriber->getSubscriberStatus() === Subscriber::STATUS_SUBSCRIBED
  139. ) {
  140. throw new LocalizedException(
  141. __('This email address is already subscribed.')
  142. );
  143. }
  144. $status = (int) $this->_subscriberFactory->create()->subscribe($email);
  145. $this->messageManager->addSuccessMessage($this->getSuccessMessage($status));
  146. } catch (LocalizedException $e) {
  147. $this->messageManager->addErrorMessage($e->getMessage());
  148. } catch (\Exception $e) {
  149. $this->messageManager->addExceptionMessage($e, __('Something went wrong with the subscription.'));
  150. }
  151. }
  152. $this->getResponse()->setRedirect($this->_redirect->getRedirectUrl());
  153. }
  154. /**
  155. * Get success message
  156. *
  157. * @param int $status
  158. * @return Phrase
  159. */
  160. private function getSuccessMessage(int $status): Phrase
  161. {
  162. if ($status === Subscriber::STATUS_NOT_ACTIVE) {
  163. return __('The confirmation request has been sent.');
  164. }
  165. return __('Thank you for your subscription.');
  166. }
  167. }