/**
  * @param int $testNumber
  * @param string $oldEmail
  * @param string $newEmail
  * @param bool $isPasswordChanged
  *
  * @dataProvider sendNotificationEmailsDataProvider
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function testSendNotificationEmailsIfRequired($testNumber, $oldEmail, $newEmail, $isPasswordChanged)
 {
     $customerId = 1;
     $customerStoreId = 2;
     $customerWebsiteId = 1;
     $customerData = ['key' => 'value'];
     $customerName = 'Customer Name';
     $templateIdentifier = 'Template Identifier';
     $sender = 'Sender';
     switch ($testNumber) {
         case 1:
             $xmlPathTemplate = EmailNotification::XML_PATH_RESET_PASSWORD_TEMPLATE;
             $expects = $this->once();
             break;
         case 2:
             $xmlPathTemplate = EmailNotification::XML_PATH_CHANGE_EMAIL_TEMPLATE;
             $expects = $this->exactly(2);
             break;
         case 3:
             $xmlPathTemplate = EmailNotification::XML_PATH_CHANGE_EMAIL_AND_PASSWORD_TEMPLATE;
             $expects = $this->exactly(2);
             break;
     }
     $origCustomer = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\CustomerInterface')->getMock();
     $origCustomer->expects($this->any())->method('getStoreId')->willReturn(0);
     $origCustomer->expects($this->any())->method('getId')->willReturn($customerId);
     $origCustomer->expects($this->any())->method('getWebsiteId')->willReturn($customerWebsiteId);
     $storeMock = $this->getMockBuilder('Magento\\Store\\Model\\Store')->disableOriginalConstructor()->getMock();
     $storeMock->expects($this->any())->method('getId')->willReturn($customerStoreId);
     $this->storeManagerMock->expects(clone $expects)->method('getStore')->willReturn($storeMock);
     $websiteMock = $this->getMockBuilder('Magento\\Store\\Model\\Website')->disableOriginalConstructor()->setMethods(['getStoreIds'])->getMock();
     $websiteMock->expects($this->any())->method('getStoreIds')->willReturn([$customerStoreId]);
     $this->storeManagerMock->expects(clone $expects)->method('getWebsite')->with($customerWebsiteId)->willReturn($websiteMock);
     $customerSecureMock = $this->getMockBuilder('Magento\\Customer\\Model\\Data\\CustomerSecure')->disableOriginalConstructor()->getMock();
     $this->customerRegistryMock->expects(clone $expects)->method('retrieveSecureData')->with($customerId)->willReturn($customerSecureMock);
     $this->dataProcessorMock->expects(clone $expects)->method('buildOutputDataArray')->with($origCustomer, '\\Magento\\Customer\\Api\\Data\\CustomerInterface')->willReturn($customerData);
     $this->customerViewHelperMock->expects($this->any())->method('getCustomerName')->with($origCustomer)->willReturn($customerName);
     $customerSecureMock->expects(clone $expects)->method('addData')->with($customerData)->willReturnSelf();
     $customerSecureMock->expects(clone $expects)->method('setData')->with('name', $customerName)->willReturnSelf();
     $savedCustomer = clone $origCustomer;
     $origCustomer->expects($this->any())->method('getEmail')->willReturn($oldEmail);
     $savedCustomer->expects($this->any())->method('getEmail')->willReturn($newEmail);
     $this->scopeConfigMock->expects($this->any())->method('getValue')->withConsecutive([$xmlPathTemplate, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $customerStoreId], [\Magento\Customer\Helper\EmailNotification::XML_PATH_FORGOT_EMAIL_IDENTITY, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $customerStoreId], [$xmlPathTemplate, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $customerStoreId], [\Magento\Customer\Helper\EmailNotification::XML_PATH_FORGOT_EMAIL_IDENTITY, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $customerStoreId])->willReturnOnConsecutiveCalls($templateIdentifier, $sender, $templateIdentifier, $sender);
     $this->transportBuilderMock->expects(clone $expects)->method('setTemplateIdentifier')->with($templateIdentifier)->willReturnSelf();
     $this->transportBuilderMock->expects(clone $expects)->method('setTemplateOptions')->with(['area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => $customerStoreId])->willReturnSelf();
     $this->transportBuilderMock->expects(clone $expects)->method('setTemplateVars')->with(['customer' => $customerSecureMock, 'store' => $storeMock])->willReturnSelf();
     $this->transportBuilderMock->expects(clone $expects)->method('setFrom')->with($sender)->willReturnSelf();
     $this->transportBuilderMock->expects(clone $expects)->method('addTo')->withConsecutive([$oldEmail, $customerName], [$newEmail, $customerName])->willReturnSelf();
     $transport = $this->getMockBuilder('Magento\\Framework\\Mail\\TransportInterface')->getMock();
     $this->transportBuilderMock->expects(clone $expects)->method('getTransport')->willReturn($transport);
     $transport->expects(clone $expects)->method('sendMessage');
     $this->assertEquals($this->helper, $this->helper->sendNotificationEmailsIfRequired($origCustomer, $savedCustomer, $isPasswordChanged));
 }
 /**
  * Save customer action
  *
  * @return \Magento\Backend\Model\View\Result\Redirect
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function execute()
 {
     $returnToEdit = false;
     $originalRequestData = $this->getRequest()->getPostValue();
     $customerId = isset($originalRequestData['customer']['entity_id']) ? $originalRequestData['customer']['entity_id'] : null;
     if ($originalRequestData) {
         try {
             // optional fields might be set in request for future processing by observers in other modules
             $customerData = $this->_extractCustomerData();
             $addressesData = $this->_extractCustomerAddressData($customerData);
             $request = $this->getRequest();
             $isExistingCustomer = (bool) $customerId;
             $customer = $this->customerDataFactory->create();
             if ($isExistingCustomer) {
                 $currentCustomer = $this->_customerRepository->getById($customerId);
                 $customerData = array_merge($this->customerMapper->toFlatArray($currentCustomer), $customerData);
                 $customerData['id'] = $customerId;
             }
             $this->dataObjectHelper->populateWithArray($customer, $customerData, '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
             $addresses = [];
             foreach ($addressesData as $addressData) {
                 $region = isset($addressData['region']) ? $addressData['region'] : null;
                 $regionId = isset($addressData['region_id']) ? $addressData['region_id'] : null;
                 $addressData['region'] = ['region' => $region, 'region_id' => $regionId];
                 $addressDataObject = $this->addressDataFactory->create();
                 $this->dataObjectHelper->populateWithArray($addressDataObject, $addressData, '\\Magento\\Customer\\Api\\Data\\AddressInterface');
                 $addresses[] = $addressDataObject;
             }
             $this->_eventManager->dispatch('adminhtml_customer_prepare_save', ['customer' => $customer, 'request' => $request]);
             $customer->setAddresses($addresses);
             $customer->setStoreId($customerData['sendemail_store_id']);
             // Save customer
             if ($isExistingCustomer) {
                 $this->_customerRepository->save($customer);
                 $this->emailNotification->sendNotificationEmailsIfRequired($currentCustomer, $customer);
             } else {
                 $customer = $this->customerAccountManagement->createAccount($customer);
                 $customerId = $customer->getId();
             }
             $isSubscribed = null;
             if ($this->_authorization->isAllowed(null)) {
                 $isSubscribed = $this->getRequest()->getPost('subscription');
             }
             if ($isSubscribed !== null) {
                 if ($isSubscribed !== 'false') {
                     $this->_subscriberFactory->create()->subscribeCustomerById($customerId);
                 } else {
                     $this->_subscriberFactory->create()->unsubscribeCustomerById($customerId);
                 }
             }
             // After save
             $this->_eventManager->dispatch('adminhtml_customer_save_after', ['customer' => $customer, 'request' => $request]);
             $this->_getSession()->unsCustomerData();
             // Done Saving customer, finish save action
             $this->_coreRegistry->register(RegistryConstants::CURRENT_CUSTOMER_ID, $customerId);
             $this->messageManager->addSuccess(__('You saved the customer.'));
             $returnToEdit = (bool) $this->getRequest()->getParam('back', false);
         } catch (\Magento\Framework\Validator\Exception $exception) {
             $messages = $exception->getMessages();
             if (empty($messages)) {
                 $messages = $exception->getMessage();
             }
             $this->_addSessionErrorMessages($messages);
             $this->_getSession()->setCustomerData($originalRequestData);
             $returnToEdit = true;
         } catch (LocalizedException $exception) {
             $this->_addSessionErrorMessages($exception->getMessage());
             $this->_getSession()->setCustomerData($originalRequestData);
             $returnToEdit = true;
         } catch (\Exception $exception) {
             $this->messageManager->addException($exception, __('Something went wrong while saving the customer.'));
             $this->_getSession()->setCustomerData($originalRequestData);
             $returnToEdit = true;
         }
     }
     $resultRedirect = $this->resultRedirectFactory->create();
     if ($returnToEdit) {
         if ($customerId) {
             $resultRedirect->setPath('customer/*/edit', ['id' => $customerId, '_current' => true]);
         } else {
             $resultRedirect->setPath('customer/*/new', ['_current' => true]);
         }
     } else {
         $resultRedirect->setPath('customer/index');
     }
     return $resultRedirect;
 }