Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
CreatePost.php
Go to the documentation of this file.
1 <?php
7 
8 use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
9 use Magento\Customer\Model\Account\Redirect as AccountRedirect;
27 use Magento\Newsletter\Model\SubscriberFactory;
28 use Magento\Customer\Api\Data\RegionInterfaceFactory;
29 use Magento\Customer\Api\Data\AddressInterfaceFactory;
30 use Magento\Customer\Api\Data\CustomerInterfaceFactory;
31 use Magento\Customer\Model\Url as CustomerUrl;
39 
45 {
49  protected $accountManagement;
50 
54  protected $addressHelper;
55 
59  protected $formFactory;
60 
64  protected $subscriberFactory;
65 
69  protected $regionDataFactory;
70 
75 
79  protected $registration;
80 
85 
89  protected $customerUrl;
90 
94  protected $escaper;
95 
99  protected $customerExtractor;
100 
104  protected $urlModel;
105 
109  protected $dataObjectHelper;
110 
114  protected $session;
115 
119  private $accountRedirect;
120 
124  private $cookieMetadataFactory;
125 
129  private $cookieMetadataManager;
130 
134  private $formKeyValidator;
135 
159  public function __construct(
160  Context $context,
161  Session $customerSession,
162  ScopeConfigInterface $scopeConfig,
166  UrlFactory $urlFactory,
168  SubscriberFactory $subscriberFactory,
169  RegionInterfaceFactory $regionDataFactory,
170  AddressInterfaceFactory $addressDataFactory,
171  CustomerInterfaceFactory $customerDataFactory,
172  CustomerUrl $customerUrl,
177  AccountRedirect $accountRedirect,
178  Validator $formKeyValidator = null
179  ) {
180  $this->session = $customerSession;
181  $this->scopeConfig = $scopeConfig;
182  $this->storeManager = $storeManager;
183  $this->accountManagement = $accountManagement;
184  $this->addressHelper = $addressHelper;
185  $this->formFactory = $formFactory;
186  $this->subscriberFactory = $subscriberFactory;
187  $this->regionDataFactory = $regionDataFactory;
188  $this->addressDataFactory = $addressDataFactory;
189  $this->customerDataFactory = $customerDataFactory;
190  $this->customerUrl = $customerUrl;
191  $this->registration = $registration;
192  $this->escaper = $escaper;
193  $this->customerExtractor = $customerExtractor;
194  $this->urlModel = $urlFactory->create();
195  $this->dataObjectHelper = $dataObjectHelper;
196  $this->accountRedirect = $accountRedirect;
197  $this->formKeyValidator = $formKeyValidator ?: ObjectManager::getInstance()->get(Validator::class);
198  parent::__construct($context);
199  }
200 
207  private function getCookieManager()
208  {
209  if (!$this->cookieMetadataManager) {
210  $this->cookieMetadataManager = ObjectManager::getInstance()->get(
211  \Magento\Framework\Stdlib\Cookie\PhpCookieManager::class
212  );
213  }
214  return $this->cookieMetadataManager;
215  }
216 
223  private function getCookieMetadataFactory()
224  {
225  if (!$this->cookieMetadataFactory) {
226  $this->cookieMetadataFactory = ObjectManager::getInstance()->get(
227  \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory::class
228  );
229  }
230  return $this->cookieMetadataFactory;
231  }
232 
238  protected function extractAddress()
239  {
240  if (!$this->getRequest()->getPost('create_address')) {
241  return null;
242  }
243 
244  $addressForm = $this->formFactory->create('customer_address', 'customer_register_address');
245  $allowedAttributes = $addressForm->getAllowedAttributes();
246 
247  $addressData = [];
248 
249  $regionDataObject = $this->regionDataFactory->create();
250  foreach ($allowedAttributes as $attribute) {
251  $attributeCode = $attribute->getAttributeCode();
252  $value = $this->getRequest()->getParam($attributeCode);
253  if ($value === null) {
254  continue;
255  }
256  switch ($attributeCode) {
257  case 'region_id':
258  $regionDataObject->setRegionId($value);
259  break;
260  case 'region':
261  $regionDataObject->setRegion($value);
262  break;
263  default:
265  }
266  }
267  $addressDataObject = $this->addressDataFactory->create();
268  $this->dataObjectHelper->populateWithArray(
269  $addressDataObject,
270  $addressData,
271  \Magento\Customer\Api\Data\AddressInterface::class
272  );
273  $addressDataObject->setRegion($regionDataObject);
274 
275  $addressDataObject->setIsDefaultBilling(
276  $this->getRequest()->getParam('default_billing', false)
277  )->setIsDefaultShipping(
278  $this->getRequest()->getParam('default_shipping', false)
279  );
280  return $addressDataObject;
281  }
282 
286  public function createCsrfValidationException(
290  $resultRedirect = $this->resultRedirectFactory->create();
291  $url = $this->urlModel->getUrl('*/*/create', ['_secure' => true]);
292  $resultRedirect->setUrl($this->_redirect->error($url));
293 
294  return new InvalidRequestException(
295  $resultRedirect,
296  [new Phrase('Invalid Form Key. Please refresh the page.')]
297  );
298  }
299 
303  public function validateForCsrf(RequestInterface $request): ?bool
304  {
305  return null;
306  }
307 
315  public function execute()
316  {
318  $resultRedirect = $this->resultRedirectFactory->create();
319  if ($this->session->isLoggedIn() || !$this->registration->isAllowed()) {
320  $resultRedirect->setPath('*/*/');
321  return $resultRedirect;
322  }
323 
324  if (!$this->getRequest()->isPost()
325  || !$this->formKeyValidator->validate($this->getRequest())
326  ) {
327  $url = $this->urlModel->getUrl('*/*/create', ['_secure' => true]);
328  return $this->resultRedirectFactory->create()
329  ->setUrl($this->_redirect->error($url));
330  }
331 
332  $this->session->regenerateId();
333 
334  try {
335  $address = $this->extractAddress();
336  $addresses = $address === null ? [] : [$address];
337 
338  $customer = $this->customerExtractor->extract('customer_account_create', $this->_request);
339  $customer->setAddresses($addresses);
340 
341  $password = $this->getRequest()->getParam('password');
342  $confirmation = $this->getRequest()->getParam('password_confirmation');
343  $redirectUrl = $this->session->getBeforeAuthUrl();
344 
345  $this->checkPasswordConfirmation($password, $confirmation);
346 
347  $customer = $this->accountManagement
348  ->createAccount($customer, $password, $redirectUrl);
349 
350  if ($this->getRequest()->getParam('is_subscribed', false)) {
351  $this->subscriberFactory->create()->subscribeCustomerById($customer->getId());
352  }
353 
354  $this->_eventManager->dispatch(
355  'customer_register_success',
356  ['account_controller' => $this, 'customer' => $customer]
357  );
358 
359  $confirmationStatus = $this->accountManagement->getConfirmationStatus($customer->getId());
360  if ($confirmationStatus === AccountManagementInterface::ACCOUNT_CONFIRMATION_REQUIRED) {
361  $email = $this->customerUrl->getEmailConfirmationUrl($customer->getEmail());
362  // @codingStandardsIgnoreStart
363  $this->messageManager->addSuccess(
364  __(
365  'You must confirm your account. Please check your email for the confirmation link or <a href="%1">click here</a> for a new link.',
366  $email
367  )
368  );
369  // @codingStandardsIgnoreEnd
370  $url = $this->urlModel->getUrl('*/*/index', ['_secure' => true]);
371  $resultRedirect->setUrl($this->_redirect->success($url));
372  } else {
373  $this->session->setCustomerDataAsLoggedIn($customer);
374  $this->messageManager->addSuccess($this->getSuccessMessage());
375  $requestedRedirect = $this->accountRedirect->getRedirectCookie();
376  if (!$this->scopeConfig->getValue('customer/startup/redirect_dashboard') && $requestedRedirect) {
377  $resultRedirect->setUrl($this->_redirect->success($requestedRedirect));
378  $this->accountRedirect->clearRedirectCookie();
379  return $resultRedirect;
380  }
381  $resultRedirect = $this->accountRedirect->getRedirect();
382  }
383  if ($this->getCookieManager()->getCookie('mage-cache-sessid')) {
384  $metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
385  $metadata->setPath('/');
386  $this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);
387  }
388 
389  return $resultRedirect;
390  } catch (StateException $e) {
391  $url = $this->urlModel->getUrl('customer/account/forgotpassword');
392  // @codingStandardsIgnoreStart
393  $message = __(
394  'There is already an account with this email address. If you are sure that it is your email address, <a href="%1">click here</a> to get your password and access your account.',
395  $url
396  );
397  // @codingStandardsIgnoreEnd
398  $this->messageManager->addError($message);
399  } catch (InputException $e) {
400  $this->messageManager->addError($this->escaper->escapeHtml($e->getMessage()));
401  foreach ($e->getErrors() as $error) {
402  $this->messageManager->addError($this->escaper->escapeHtml($error->getMessage()));
403  }
404  } catch (LocalizedException $e) {
405  $this->messageManager->addError($this->escaper->escapeHtml($e->getMessage()));
406  } catch (\Exception $e) {
407  $this->messageManager->addException($e, __('We can\'t save the customer.'));
408  }
409 
410  $this->session->setCustomerFormData($this->getRequest()->getPostValue());
411  $defaultUrl = $this->urlModel->getUrl('*/*/create', ['_secure' => true]);
412  return $resultRedirect->setUrl($this->_redirect->error($defaultUrl));
413  }
414 
423  protected function checkPasswordConfirmation($password, $confirmation)
424  {
425  if ($password != $confirmation) {
426  throw new InputException(__('Please make sure your passwords match.'));
427  }
428  }
429 
435  protected function getSuccessMessage()
436  {
437  if ($this->addressHelper->isVatValidationEnabled()) {
438  if ($this->addressHelper->getTaxCalculationAddressType() == Address::TYPE_SHIPPING) {
439  // @codingStandardsIgnoreStart
440  $message = __(
441  'If you are a registered VAT customer, please <a href="%1">click here</a> to enter your shipping address for proper VAT calculation.',
442  $this->urlModel->getUrl('customer/address/edit')
443  );
444  // @codingStandardsIgnoreEnd
445  } else {
446  // @codingStandardsIgnoreStart
447  $message = __(
448  'If you are a registered VAT customer, please <a href="%1">click here</a> to enter your billing address for proper VAT calculation.',
449  $this->urlModel->getUrl('customer/address/edit')
450  );
451  // @codingStandardsIgnoreEnd
452  }
453  } else {
454  $message = __('Thank you for registering with %1.', $this->storeManager->getStore()->getFrontendName());
455  }
456  return $message;
457  }
458 }
$accountManagement
Definition: CreatePost.php:49
_redirect($path, $arguments=[])
Definition: Action.php:167
$customerExtractor
Definition: CreatePost.php:99
$regionDataFactory
Definition: CreatePost.php:69
$escaper
Definition: CreatePost.php:94
$customer
Definition: customers.php:11
$email
Definition: details.phtml:13
$addresses
Definition: address_list.php:7
$storeManager
__()
Definition: __.php:13
checkPasswordConfirmation($password, $confirmation)
Definition: CreatePost.php:423
$message
$registration
Definition: CreatePost.php:79
$customerDataFactory
Definition: CreatePost.php:84
$address
Definition: customer.php:38
$addressData
Definition: order.php:19
$subscriberFactory
Definition: CreatePost.php:64
__construct(Context $context, Session $customerSession, ScopeConfigInterface $scopeConfig, StoreManagerInterface $storeManager, AccountManagementInterface $accountManagement, Address $addressHelper, UrlFactory $urlFactory, FormFactory $formFactory, SubscriberFactory $subscriberFactory, RegionInterfaceFactory $regionDataFactory, AddressInterfaceFactory $addressDataFactory, CustomerInterfaceFactory $customerDataFactory, CustomerUrl $customerUrl, Registration $registration, Escaper $escaper, CustomerExtractor $customerExtractor, DataObjectHelper $dataObjectHelper, AccountRedirect $accountRedirect, Validator $formKeyValidator=null)
Definition: CreatePost.php:159
$value
Definition: gender.phtml:16
getSuccessMessage()
Definition: CreatePost.php:435
$formFactory
Definition: CreatePost.php:59
$attributeCode
Definition: extend.phtml:12
$addressDataFactory
Definition: CreatePost.php:74
validateForCsrf(RequestInterface $request)
Definition: CreatePost.php:303
$customerUrl
Definition: CreatePost.php:89
extractAddress()
Definition: CreatePost.php:238
createCsrfValidationException(RequestInterface $request)
$dataObjectHelper
Definition: CreatePost.php:109
$addressHelper
Definition: CreatePost.php:54
Definition: CreatePost.php:44
$urlModel
Definition: CreatePost.php:104
$session
Definition: CreatePost.php:114