public function __construct(\Dotdigitalgroup\Email\Model\AutomationFactory $automationFactory, \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory, \Dotdigitalgroup\Email\Model\ContactFactory $contactFactory, \Magento\Framework\Registry $registry, \Dotdigitalgroup\Email\Helper\Data $data, \Magento\Store\Model\StoreManagerInterface $storeManagerInterface)
 {
     $this->_automationFactory = $automationFactory;
     $this->_subscriberFactory = $subscriberFactory->create();
     $this->_contactFactory = $contactFactory;
     $this->_helper = $data;
     $this->_storeManager = $storeManagerInterface;
     $this->_registry = $registry;
 }
Example #2
0
 /**
  * Save newsletter subscription preference action
  *
  * @return void|null
  */
 public function executeInternal()
 {
     if (!$this->formKeyValidator->validate($this->getRequest())) {
         return $this->_redirect('customer/account/');
     }
     $customerId = $this->_customerSession->getCustomerId();
     if ($customerId === null) {
         $this->messageManager->addError(__('Something went wrong while saving your subscription.'));
     } else {
         try {
             $customer = $this->customerRepository->getById($customerId);
             $storeId = $this->storeManager->getStore()->getId();
             $customer->setStoreId($storeId);
             $this->customerRepository->save($customer);
             if ((bool) $this->getRequest()->getParam('is_subscribed', false)) {
                 $this->subscriberFactory->create()->subscribeCustomerById($customerId);
                 $this->messageManager->addSuccess(__('We saved the subscription.'));
             } else {
                 $this->subscriberFactory->create()->unsubscribeCustomerById($customerId);
                 $this->messageManager->addSuccess(__('We removed the subscription.'));
             }
         } catch (\Exception $e) {
             $this->messageManager->addError(__('Something went wrong while saving your subscription.'));
         }
     }
     $this->_redirect('customer/account/');
 }
Example #3
0
 /**
  * Get html code
  *
  * @return string
  */
 protected function _toHtml()
 {
     /* @var $template \Magento\Newsletter\Model\Template */
     $template = $this->_templateFactory->create();
     if ($id = (int) $this->getRequest()->getParam('id')) {
         $this->loadTemplate($template, $id);
     } else {
         $previewData = $this->getPreviewData();
         $template->setTemplateType($previewData['type']);
         $template->setTemplateText($previewData['text']);
         $template->setTemplateStyles($previewData['styles']);
     }
     \Magento\Framework\Profiler::start($this->profilerName);
     $vars = [];
     $vars['subscriber'] = $this->_subscriberFactory->create();
     if ($this->getRequest()->getParam('subscriber')) {
         $vars['subscriber']->load($this->getRequest()->getParam('subscriber'));
     }
     $template->emulateDesign($this->getStoreId());
     $templateProcessed = $this->_appState->emulateAreaCode(\Magento\Newsletter\Model\Template::DEFAULT_DESIGN_AREA, [$template, 'getProcessedTemplate'], [$vars]);
     $template->revertDesign();
     if ($template->isPlain()) {
         $templateProcessed = "<pre>" . htmlspecialchars($templateProcessed) . "</pre>";
     }
     \Magento\Framework\Profiler::stop($this->profilerName);
     return $templateProcessed;
 }
 public function setUp()
 {
     $this->subscriber = $this->getMockBuilder('\\Magento\\Newsletter\\Model\\Subscriber')->setMethods(['loadByEmail', 'getId', 'delete', 'updateSubscription'])->disableOriginalConstructor()->getMock();
     $this->subscriberFactory->expects($this->any())->method('create')->willReturn($this->subscriber);
     $this->plugin = $this->objectManager->getObject('Ebizmarts\\MageMonkey\\Model\\Plugin\\Subscriber', ['subscriberFactory' => $this->subscriberFactory]);
     $this->resource = $this->getMock('Magento\\Newsletter\\Model\\Resource\\Subscriber', ['loadByEmail', 'getIdFieldName', 'save', 'loadByCustomerData', 'received'], [], '', false);
 }
Example #5
0
 /**
  * Get html code
  *
  * @return string
  */
 protected function _toHtml()
 {
     /* @var $template \Magento\Newsletter\Model\Template */
     $template = $this->_templateFactory->create();
     if ($id = (int) $this->getRequest()->getParam('id')) {
         $template->load($id);
     } else {
         $template->setTemplateType($this->getRequest()->getParam('type'));
         $template->setTemplateText($this->getRequest()->getParam('text'));
         $template->setTemplateStyles($this->getRequest()->getParam('styles'));
     }
     $storeId = (int) $this->getRequest()->getParam('store_id');
     if (!$storeId) {
         $storeId = $this->_storeManager->getDefaultStoreView()->getId();
     }
     \Magento\Framework\Profiler::start("newsletter_template_proccessing");
     $vars = array();
     $vars['subscriber'] = $this->_subscriberFactory->create();
     if ($this->getRequest()->getParam('subscriber')) {
         $vars['subscriber']->load($this->getRequest()->getParam('subscriber'));
     }
     $template->emulateDesign($storeId);
     $templateProcessed = $this->_appState->emulateAreaCode(\Magento\Newsletter\Model\Template::DEFAULT_DESIGN_AREA, array($template, 'getProcessedTemplate'), array($vars, true));
     $template->revertDesign();
     if ($template->isPlain()) {
         $templateProcessed = "<pre>" . htmlspecialchars($templateProcessed) . "</pre>";
     }
     \Magento\Framework\Profiler::stop("newsletter_template_proccessing");
     return $templateProcessed;
 }
 public function setUp()
 {
     $this->subscriberFactory = $this->getMockBuilder('\\Magento\\Newsletter\\Model\\SubscriberFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock();
     $this->subscriber = $this->getMockBuilder('\\Magento\\Newsletter\\Model\\Subscriber')->setMethods(['loadByEmail', 'getId', 'delete', 'updateSubscription'])->disableOriginalConstructor()->getMock();
     $this->subscriberFactory->expects($this->any())->method('create')->willReturn($this->subscriber);
     $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
     $this->plugin = $this->objectManager->getObject('Magento\\Newsletter\\Model\\Plugin\\CustomerPlugin', ['subscriberFactory' => $this->subscriberFactory]);
 }
Example #7
0
 public function testToHtmlWithSubscriber()
 {
     $this->request->expects($this->any())->method('getParam')->willReturnMap([['id', null, 2], ['store', null, 1], ['subscriber', null, 3]]);
     $subscriber = $this->getMock('Magento\\Newsletter\\Model\\Subscriber', [], [], '', false);
     $subscriber->expects($this->atLeastOnce())->method('load')->with(3)->willReturnSelf();
     $this->subscriberFactory->expects($this->atLeastOnce())->method('create')->willReturn($subscriber);
     $this->template->expects($this->atLeastOnce())->method('emulateDesign')->with(1);
     $this->template->expects($this->atLeastOnce())->method('revertDesign');
     $this->appState->expects($this->atLeastOnce())->method('emulateAreaCode')->with(\Magento\Newsletter\Model\Template::DEFAULT_DESIGN_AREA, [$this->template, 'getProcessedTemplate'], [['subscriber' => $subscriber]])->willReturn('Processed Template');
     $this->assertEquals('Processed Template', $this->preview->toHtml());
 }
 /**
  * Plugin around delete customer that updates any newsletter subscription that may have existed.
  *
  * @param CustomerRepository $subject
  * @param callable $deleteCustomer Function we are wrapping around
  * @param CustomerInterface $customer Input to the function
  * @return bool
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function aroundDelete(CustomerRepository $subject, callable $deleteCustomer, $customer)
 {
     $result = $deleteCustomer($customer);
     /** @var \Magento\Newsletter\Model\Subscriber $subscriber */
     $subscriber = $this->subscriberFactory->create();
     $subscriber->loadByEmail($customer->getEmail());
     if ($subscriber->getId()) {
         $subscriber->delete();
     }
     return $result;
 }
 /**
  * Subscriber status for Customer.
  *
  * @return mixed
  */
 public function getSubscriberStatus()
 {
     $subscriberModel = $this->subscriberFactory->create()->loadByCustomerId($this->customer->getId());
     if ($subscriberModel->getCustomerId()) {
         return $this->subscriberStatus[$subscriberModel->getSubscriberStatus()];
     }
 }
 /**
  * Initialize the form.
  *
  * @return $this
  */
 public function initForm()
 {
     if (!$this->canShowTab()) {
         return $this;
     }
     /**@var \Magento\Framework\Data\Form $form */
     $form = $this->_formFactory->create();
     $form->setHtmlIdPrefix('_newsletter');
     $customerId = $this->_coreRegistry->registry(RegistryConstants::CURRENT_CUSTOMER_ID);
     $subscriber = $this->_subscriberFactory->create()->loadByCustomerId($customerId);
     $this->_coreRegistry->register('subscriber', $subscriber);
     $fieldset = $form->addFieldset('base_fieldset', ['legend' => __('Newsletter Information')]);
     $fieldset->addField('subscription', 'checkbox', ['label' => __('Subscribed to Newsletter'), 'name' => 'subscription', 'data-form-part' => $this->getData('target_form'), 'onchange' => 'this.value = this.checked;']);
     if ($this->customerAccountManagement->isReadOnly($customerId)) {
         $form->getElement('subscription')->setReadonly(true, true);
     }
     $isSubscribed = $subscriber->isSubscribed();
     $form->setValues(['subscription' => $isSubscribed ? 'true' : 'false']);
     $form->getElement('subscription')->setIsChecked($isSubscribed);
     $changedDate = $this->getStatusChangedDate();
     if ($changedDate) {
         $fieldset->addField('change_status_date', 'label', ['label' => $isSubscribed ? __('Last Date Subscribed') : __('Last Date Unsubscribed'), 'value' => $changedDate, 'bold' => true]);
     }
     $this->setForm($form);
     return $this;
 }
 /**
  * Export subscribers per website.
  *
  * @param $website
  *
  * @return int
  *
  * @throws LocalizedException
  */
 public function exportSubscribersPerWebsite($website)
 {
     $updated = 0;
     $limit = $this->helper->getSyncLimit($website->getId());
     //subscriber collection to import
     $subscribers = $this->contactFactory->create()->getSubscribersToImport($website, $limit);
     if ($subscribers->getSize()) {
         $subscribersFilename = strtolower($website->getCode() . '_subscribers_' . date('d_m_Y_Hi') . '.csv');
         //get mapped storename
         $subscriberStoreName = $this->helper->getMappedStoreName($website);
         //file headers
         $this->file->outputCSV($this->file->getFilePath($subscribersFilename), ['Email', 'emailType', $subscriberStoreName]);
         $emails = $subscribers->getColumnValues('email');
         $subscriberFactory = $this->subscriberFactory->create();
         $subscribersData = $subscriberFactory->getCollection()->addFieldToFilter('subscriber_email', ['in' => $emails])->addFieldToSelect(['subscriber_email', 'store_id'])->toArray();
         foreach ($subscribers as $subscriber) {
             $email = $subscriber->getEmail();
             $storeId = $this->getStoreIdForSubscriber($email, $subscribersData['items']);
             $storeName = $this->storeManager->getStore($storeId)->getName();
             // save data for subscribers
             $this->file->outputCSV($this->file->getFilePath($subscribersFilename), [$email, 'Html', $storeName]);
             //@codingStandardsIgnoreStart
             $subscriber->setSubscriberImported(1)->save();
             //@codingStandardsIgnoreEnd
             ++$updated;
         }
         $this->helper->log('Subscriber filename: ' . $subscribersFilename);
         //register in queue with importer
         $this->importerFactory->create()->registerQueue(\Dotdigitalgroup\Email\Model\Importer::IMPORT_TYPE_SUBSCRIBERS, '', \Dotdigitalgroup\Email\Model\Importer::MODE_BULK, $website->getId(), $subscribersFilename);
     }
     //add updated number for the website
     $this->countSubscriber += $updated;
     return $updated;
 }
 /**
  * Customer mass unsubscribe action
  *
  * @param AbstractCollection $collection
  * @return \Magento\Backend\Model\View\Result\Redirect
  */
 protected function massAction(AbstractCollection $collection)
 {
     $customersUpdated = 0;
     foreach ($collection->getAllIds() as $customerId) {
         // Verify customer exists
         $this->customerRepository->getById($customerId);
         $this->subscriberFactory->create()->unsubscribeCustomerById($customerId);
         $customersUpdated++;
     }
     if ($customersUpdated) {
         $this->messageManager->addSuccess(__('A total of %1 record(s) were updated.', $customersUpdated));
     }
     /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
     $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
     $resultRedirect->setPath($this->getComponentRefererUrl());
     return $resultRedirect;
 }
Example #13
0
 /**
  * Create customer account action
  *
  * @return void
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 public function execute()
 {
     if ($this->_getSession()->isLoggedIn() || !$this->isRegistrationAllowed()) {
         $this->_redirect('*/*/');
         return;
     }
     if (!$this->getRequest()->isPost()) {
         $url = $this->_createUrl()->getUrl('*/*/create', array('_secure' => true));
         $this->getResponse()->setRedirect($this->_redirect->error($url));
         return;
     }
     $this->_session->regenerateId();
     try {
         $customer = $this->customerExtractor->extract('customer_account_create', $this->_request);
         $address = $this->_extractAddress();
         $addresses = is_null($address) ? array() : array($address);
         $password = $this->getRequest()->getParam('password');
         $redirectUrl = $this->_getSession()->getBeforeAuthUrl();
         $customerDetails = $this->_customerDetailsBuilder->setCustomer($customer)->setAddresses($addresses)->create();
         $customer = $this->_customerAccountService->createCustomer($customerDetails, $password, $redirectUrl);
         if ($this->getRequest()->getParam('is_subscribed', false)) {
             $this->_subscriberFactory->create()->subscribeCustomerById($customer->getId());
         }
         $this->_eventManager->dispatch('customer_register_success', array('account_controller' => $this, 'customer' => $customer));
         $confirmationStatus = $this->_customerAccountService->getConfirmationStatus($customer->getId());
         if ($confirmationStatus === CustomerAccountServiceInterface::ACCOUNT_CONFIRMATION_REQUIRED) {
             $email = $this->_customerHelperData->getEmailConfirmationUrl($customer->getEmail());
             // @codingStandardsIgnoreStart
             $this->messageManager->addSuccess(__('Account confirmation is required. Please, check your email for the confirmation link. To resend the confirmation email please <a href="%1">click here</a>.', $email));
             // @codingStandardsIgnoreEnd
             $url = $this->_createUrl()->getUrl('*/*/index', array('_secure' => true));
             $this->getResponse()->setRedirect($this->_redirect->success($url));
         } else {
             $this->_getSession()->setCustomerDataAsLoggedIn($customer);
             $url = $this->_welcomeCustomer($customer);
             $this->getResponse()->setRedirect($this->_redirect->success($url));
         }
         return;
     } catch (StateException $e) {
         $url = $this->_createUrl()->getUrl('customer/account/forgotpassword');
         // @codingStandardsIgnoreStart
         $message = __('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.', $url);
         // @codingStandardsIgnoreEnd
         $this->messageManager->addError($message);
     } catch (InputException $e) {
         $this->messageManager->addError($this->escaper->escapeHtml($e->getMessage()));
         foreach ($e->getErrors() as $error) {
             $this->messageManager->addError($this->escaper->escapeHtml($error->getMessage()));
         }
     } catch (\Exception $e) {
         $this->messageManager->addException($e, __('Cannot save the customer.'));
     }
     $this->_getSession()->setCustomerFormData($this->getRequest()->getPost());
     $defaultUrl = $this->_createUrl()->getUrl('*/*/create', array('_secure' => true));
     $this->getResponse()->setRedirect($this->_redirect->error($defaultUrl));
 }
Example #14
0
 /**
  * Retrieve Subscriber
  *
  * @return \Magento\Newsletter\Model\Subscriber
  */
 public function getSubscriber()
 {
     if (!$this->getSubscriberId()) {
         return null;
     }
     if ($this->_subscriber === null) {
         $this->_subscriber = $this->_subscriberFactory->create()->load($this->getSubscriberId());
     }
     return $this->_subscriber;
 }
Example #15
0
 /**
  * Plugin after delete customer that updates any newsletter subscription that may have existed.
  *
  * @param CustomerAccountServiceInterface $subject
  * @param callable $deleteCustomer Function we are wrapping around
  * @param int $customerId Input to the function
  * @return bool
  */
 public function aroundDeleteCustomer(CustomerAccountServiceInterface $subject, callable $deleteCustomer, $customerId)
 {
     $customer = $subject->getCustomer($customerId);
     $result = $deleteCustomer($customerId);
     /** @var \Magento\Newsletter\Model\Subscriber $subscriber */
     $subscriber = $this->subscriberFactory->create();
     $subscriber->loadByEmail($customer->getEmail());
     if ($subscriber->getId()) {
         $subscriber->delete();
     }
     return $result;
 }
Example #16
0
 /**
  * Initialize the form.
  *
  * @return $this
  */
 public function initForm()
 {
     /**@var \Magento\Framework\Data\Form $form */
     $form = $this->_formFactory->create();
     $form->setHtmlIdPrefix('_newsletter');
     $customerId = $this->_coreRegistry->registry(RegistryConstants::CURRENT_CUSTOMER_ID);
     $subscriber = $this->_subscriberFactory->create()->loadByCustomerId($customerId);
     $this->_coreRegistry->register('subscriber', $subscriber);
     $fieldset = $form->addFieldset('base_fieldset', array('legend' => __('Newsletter Information')));
     $fieldset->addField('subscription', 'checkbox', array('label' => __('Subscribed to Newsletter'), 'name' => 'subscription'));
     if (!$this->_customerAccountService->canModify($customerId)) {
         $form->getElement('subscription')->setReadonly(true, true);
     }
     $form->getElement('subscription')->setIsChecked($subscriber->isSubscribed());
     $changedDate = $this->getStatusChangedDate();
     if ($changedDate) {
         $fieldset->addField('change_status_date', 'label', array('label' => $subscriber->isSubscribed() ? __('Last Date Subscribed') : __('Last Date Unsubscribed'), 'value' => $changedDate, 'bold' => true));
     }
     $this->setForm($form);
     return $this;
 }
Example #17
0
 /**
  * Contact constructor.
  *
  * @param \Dotdigitalgroup\Email\Model\ProccessorFactory                   $proccessorFactory
  * @param CustomerFactory                                                  $customerFactory
  * @param \Magento\Framework\Registry                                      $registry
  * @param \Magento\Framework\App\ResourceConnection                        $resource
  * @param \Dotdigitalgroup\Email\Helper\File                               $file
  * @param \Dotdigitalgroup\Email\Helper\Data                               $helper
  * @param \Dotdigitalgroup\Email\Helper\Config                             $config
  * @param \Magento\Backend\App\Action\Context                              $context
  * @param \Magento\Newsletter\Model\SubscriberFactory                      $subscriberFactory
  * @param \Magento\Framework\App\Config\ScopeConfigInterface               $scopeConfig
  * @param \Magento\Store\Model\StoreManagerInterface                       $storeManagerInterface
  * @param \Dotdigitalgroup\Email\Model\ContactFactory                      $contactFactory
  * @param \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $customerCollectionFactory
  * @param \Dotdigitalgroup\Email\Model\Resource\Contact\CollectionFactory  $contactCollectionFactory
  */
 public function __construct(\Dotdigitalgroup\Email\Model\ProccessorFactory $proccessorFactory, \Dotdigitalgroup\Email\Model\Apiconnector\CustomerFactory $customerFactory, \Magento\Framework\Registry $registry, \Magento\Framework\App\ResourceConnection $resource, \Dotdigitalgroup\Email\Helper\File $file, \Dotdigitalgroup\Email\Helper\Data $helper, \Dotdigitalgroup\Email\Helper\Config $config, \Magento\Backend\App\Action\Context $context, \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Store\Model\StoreManagerInterface $storeManagerInterface, \Dotdigitalgroup\Email\Model\ContactFactory $contactFactory, \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $customerCollectionFactory, \Dotdigitalgroup\Email\Model\Resource\Contact\CollectionFactory $contactCollectionFactory)
 {
     $this->_proccessorFactory = $proccessorFactory;
     $this->_file = $file;
     $this->_config = $config;
     $this->_helper = $helper;
     $this->_registry = $registry;
     $this->_resource = $resource;
     $this->_scopeConfig = $scopeConfig;
     $this->_storeManager = $storeManagerInterface;
     $this->_messageManager = $context->getMessageManager();
     //email contact
     $this->_emailCustomer = $customerFactory;
     $this->_contactFactory = $contactFactory;
     $this->_customerCollection = $customerCollectionFactory->create();
     $this->_customerCollection->addAttributeToSelect('*');
     //email contact collection
     $this->_contactCollection = $contactCollectionFactory->create();
     $this->_contactCollection->addFieldToSelect('*');
     //newsletter subscriber
     $this->_subscriberFactory = $subscriberFactory->create();
 }
Example #18
0
 /**
  * @covers \Magento\Customer\Controller\Adminhtml\Index\Index::execute
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function testExecuteWithNewCustomerAndException()
 {
     $subscription = 'false';
     $postValue = ['customer' => ['coolness' => false, 'disable_auto_group_change' => 'false'], 'subscription' => $subscription];
     $filteredData = ['coolness' => false, 'disable_auto_group_change' => 'false'];
     /** @var AttributeMetadataInterface|\PHPUnit_Framework_MockObject_MockObject $formMock */
     $attributeMock = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\AttributeMetadataInterface')->disableOriginalConstructor()->getMock();
     $attributeMock->expects($this->once())->method('getAttributeCode')->willReturn('coolness');
     $attributeMock->expects($this->once())->method('getFrontendInput')->willReturn('int');
     $attributes = [$attributeMock];
     $this->requestMock->expects($this->exactly(2))->method('getPostValue')->willReturn($postValue);
     $this->requestMock->expects($this->exactly(2))->method('getPost')->willReturnMap([['customer', null, $postValue['customer']], ['address', null, null]]);
     /** @var \Magento\Customer\Model\Metadata\Form|\PHPUnit_Framework_MockObject_MockObject $formMock */
     $formMock = $this->getMockBuilder('Magento\\Customer\\Model\\Metadata\\Form')->disableOriginalConstructor()->getMock();
     $this->formFactoryMock->expects($this->once())->method('create')->with(\Magento\Customer\Api\CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER, 'adminhtml_customer', [], false, \Magento\Customer\Model\Metadata\Form::DONT_IGNORE_INVISIBLE)->willReturn($formMock);
     $formMock->expects($this->once())->method('extractData')->with($this->requestMock, 'customer')->willReturn($filteredData);
     /** @var \Magento\Framework\DataObject|\PHPUnit_Framework_MockObject_MockObject $objectMock */
     $objectMock = $this->getMockBuilder('Magento\\Framework\\DataObject')->disableOriginalConstructor()->getMock();
     $this->objectFactoryMock->expects($this->once())->method('create')->with(['data' => $postValue])->willReturn($objectMock);
     $objectMock->expects($this->once())->method('getData')->with('customer')->willReturn($postValue['customer']);
     $formMock->expects($this->once())->method('getAttributes')->willReturn($attributes);
     /** @var \Magento\Customer\Api\Data\CustomerInterface|\PHPUnit_Framework_MockObject_MockObject $customerMock */
     $customerMock = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\CustomerInterface')->disableOriginalConstructor()->getMock();
     $this->customerDataFactoryMock->expects($this->once())->method('create')->willReturn($customerMock);
     $exception = new \Exception(__('Exception'));
     $this->managementMock->expects($this->once())->method('createAccount')->with($customerMock, null, '')->willThrowException($exception);
     $customerMock->expects($this->never())->method('getId');
     $this->authorizationMock->expects($this->never())->method('isAllowed');
     $this->subscriberFactoryMock->expects($this->never())->method('create');
     $this->sessionMock->expects($this->never())->method('unsCustomerData');
     $this->registryMock->expects($this->never())->method('register');
     $this->messageManagerMock->expects($this->never())->method('addSuccess');
     $this->messageManagerMock->expects($this->once())->method('addException')->with($exception, __('Something went wrong while saving the customer.'));
     $this->sessionMock->expects($this->once())->method('setCustomerData')->with($postValue);
     /** @var Redirect|\PHPUnit_Framework_MockObject_MockObject $redirectMock */
     $redirectMock = $this->getMockBuilder('Magento\\Framework\\Controller\\Result\\Redirect')->disableOriginalConstructor()->getMock();
     $this->redirectFactoryMock->expects($this->once())->method('create')->with([])->willReturn($redirectMock);
     $redirectMock->expects($this->once())->method('setPath')->with('customer/*/new', ['_current' => true])->willReturn(true);
     $this->assertEquals($redirectMock, $this->model->execute());
 }
Example #19
0
 /**
  * Create customer account action
  *
  * @return void
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 public function execute()
 {
     /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
     $resultRedirect = $this->resultRedirectFactory->create();
     if ($this->session->isLoggedIn() || !$this->registration->isAllowed()) {
         $resultRedirect->setPath('*/*/');
         return $resultRedirect;
     }
     if (!$this->getRequest()->isPost()) {
         $url = $this->urlModel->getUrl('*/*/create', ['_secure' => true]);
         $resultRedirect->setUrl($this->_redirect->error($url));
         return $resultRedirect;
     }
     $this->session->regenerateId();
     try {
         $address = $this->extractAddress();
         $addresses = $address === null ? [] : [$address];
         $customer = $this->customerExtractor->extract('customer_account_create', $this->_request);
         $customer->setAddresses($addresses);
         $password = $this->getRequest()->getParam('password');
         $confirmation = $this->getRequest()->getParam('password_confirmation');
         $redirectUrl = $this->session->getBeforeAuthUrl();
         $this->checkPasswordConfirmation($password, $confirmation);
         $customer = $this->accountManagement->createAccount($customer, $password, $redirectUrl);
         if ($this->getRequest()->getParam('is_subscribed', false)) {
             $this->subscriberFactory->create()->subscribeCustomerById($customer->getId());
         }
         $this->_eventManager->dispatch('customer_register_success', ['account_controller' => $this, 'customer' => $customer]);
         $confirmationStatus = $this->accountManagement->getConfirmationStatus($customer->getId());
         if ($confirmationStatus === AccountManagementInterface::ACCOUNT_CONFIRMATION_REQUIRED) {
             $email = $this->customerUrl->getEmailConfirmationUrl($customer->getEmail());
             // @codingStandardsIgnoreStart
             $this->messageManager->addSuccess(__('You must confirm your account. Please check your email for the confirmation link or <a href="%1">click here</a> for a new link.', $email));
             // @codingStandardsIgnoreEnd
             $url = $this->urlModel->getUrl('*/*/index', ['_secure' => true]);
             $resultRedirect->setUrl($this->_redirect->success($url));
         } else {
             $this->session->setCustomerDataAsLoggedIn($customer);
             $this->messageManager->addSuccess($this->getSuccessMessage());
             $resultRedirect = $this->accountRedirect->getRedirect();
         }
         return $resultRedirect;
     } catch (StateException $e) {
         $url = $this->urlModel->getUrl('customer/account/forgotpassword');
         // @codingStandardsIgnoreStart
         $message = __('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.', $url);
         // @codingStandardsIgnoreEnd
         $this->messageManager->addError($message);
     } catch (InputException $e) {
         $this->messageManager->addError($this->escaper->escapeHtml($e->getMessage()));
         foreach ($e->getErrors() as $error) {
             $this->messageManager->addError($this->escaper->escapeHtml($error->getMessage()));
         }
     } catch (\Exception $e) {
         $this->messageManager->addException($e, __('We can\'t save the customer.'));
     }
     $this->session->setCustomerFormData($this->getRequest()->getPostValue());
     $defaultUrl = $this->urlModel->getUrl('*/*/create', ['_secure' => true]);
     $resultRedirect->setUrl($this->_redirect->error($defaultUrl));
     return $resultRedirect;
 }
Example #20
0
 /**
  * Create an instance of a subscriber.
  *
  * @return \Magento\Newsletter\Model\Subscriber
  */
 protected function _createSubscriber()
 {
     return $this->subscriberFactory->create();
 }