/** * @param CustomerInterface $entity * @param array $arguments * @return CustomerInterface * @throws \Exception * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function execute($entity, $arguments = []) { $extensionAttribute = $entity->getExtensionAttributes()->getExtensionAttribute(); $extensionAttribute->setCustomerId($entity->getId()); $extensionAttribute = $this->entityManager->save($extensionAttribute); $entity->getExtensionAttributes()->setExtensionAttribute($extensionAttribute); return $entity; }
public function setUp() { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } $this->customer = $this->getMockForAbstractClass('Magento\\Customer\\Api\\Data\\CustomerInterface', [], '', false, true, true); $this->customer->expects($this->once())->method('getWebsiteId')->willReturn(2); $this->customerDataFactory = $this->getMock('Magento\\Customer\\Api\\Data\\CustomerInterfaceFactory', ['create'], [], '', false); $this->customerDataFactory->expects($this->once())->method('create')->willReturn($this->customer); $this->form = $this->getMock('Magento\\Customer\\Model\\Metadata\\Form', [], [], '', false); $this->request = $this->getMockForAbstractClass('Magento\\Framework\\App\\RequestInterface', [], '', false, true, true, ['getPost']); $this->response = $this->getMockForAbstractClass('Magento\\Framework\\App\\ResponseInterface', [], '', false); $this->formFactory = $this->getMock('Magento\\Customer\\Model\\Metadata\\FormFactory', ['create'], [], '', false); $this->formFactory->expects($this->atLeastOnce())->method('create')->willReturn($this->form); $this->extensibleDataObjectConverter = $this->getMock('Magento\\Framework\\Api\\ExtensibleDataObjectConverter', [], [], '', false); $this->dataObjectHelper = $this->getMock('Magento\\Framework\\Api\\DataObjectHelper', [], [], '', false); $this->dataObjectHelper->expects($this->once())->method('populateWithArray'); $this->customerAccountManagement = $this->getMockForAbstractClass('Magento\\Customer\\Api\\AccountManagementInterface', [], '', false, true, true); $this->resultJson = $this->getMock('Magento\\Framework\\Controller\\Result\\Json', [], [], '', false); $this->resultJson->expects($this->once())->method('setData'); $this->resultJsonFactory = $this->getMock('Magento\\Framework\\Controller\\Result\\JsonFactory', ['create'], [], '', false); $this->resultJsonFactory->expects($this->once())->method('create')->willReturn($this->resultJson); $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->controller = $objectHelper->getObject('Magento\\Customer\\Controller\\Adminhtml\\Index\\Validate', ['request' => $this->request, 'response' => $this->response, 'customerDataFactory' => $this->customerDataFactory, 'formFactory' => $this->formFactory, 'extensibleDataObjectConverter' => $this->extensibleDataObjectConverter, 'customerAccountManagement' => $this->customerAccountManagement, 'resultJsonFactory' => $this->resultJsonFactory, 'dataObjectHelper' => $this->dataObjectHelper]); }
/** * @param CustomerInterface $customer * @return \Openpay\Client\Type\OpenpayCustomerType * @throws LocalizedException */ public function save(CustomerInterface $customer) { $params = ['name' => $customer->getFirstname(), 'last_name' => $customer->getLastname(), 'email' => $customer->getEmail(), 'requires_account' => self::CUSTOMER_REQUIRES_ACCOUNT, 'external_id' => $customer->getId()]; try { $openpayCustomer = $this->customerAdapter->store($params); } catch (OpenpayException $e) { throw new LocalizedException(__($e->getDescription()), $e); } return $openpayCustomer; }
/** * @param CustomerInterface $entity * @param array $arguments * @return CustomerInterface * @throws \Exception * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function execute($entity, $arguments = []) { $newAddresses = []; foreach ($entity->getAddresses() as $address) { $address->setCustomerId($entity->getId()); $newAddresses[] = $this->entityManager->save($address); } $entity->setAddresses($newAddresses); return $entity; }
/** * test getCustomer method, method returns depersonalized customer Data */ public function testGetCustomerDepersonalizeCustomerData() { $this->requestMock->expects($this->once())->method('isAjax')->will($this->returnValue(false)); $this->layoutMock->expects($this->once())->method('isCacheable')->will($this->returnValue(true)); $this->viewMock->expects($this->once())->method('isLayoutLoaded')->will($this->returnValue(true)); $this->moduleManagerMock->expects($this->once())->method('isEnabled')->with($this->equalTo('Magento_PageCache'))->will($this->returnValue(true)); $this->customerSessionMock->expects($this->once())->method('getCustomerGroupId')->will($this->returnValue($this->customerGroupId)); $this->customerInterfaceFactoryMock->expects($this->once())->method('create')->will($this->returnValue($this->customerDataMock)); $this->customerDataMock->expects($this->once())->method('setGroupId')->with($this->equalTo($this->customerGroupId))->will($this->returnSelf()); $this->assertEquals($this->customerDataMock, $this->currentCustomer->getCustomer()); }
/** @inheritdoc */ public function getBusCodeForCustomerGroup(\Magento\Customer\Api\Data\CustomerInterface $customer) { $result = self::B_CUST_GROUP_RETAIL; $groupId = $customer->getGroupId(); if ($groupId == self::M_CUST_GROUP_DISTRIBUTOR) { $result = self::B_CUST_GROUP_DISTRIBUTOR; } elseif ($groupId == self::M_CUST_GROUP_WHOLESALE) { $result = self::B_CUST_GROUP_WHOLESALE; } return $result; }
/** * @param CustomerInterface $entity * @param array $arguments * @return CustomerInterface * @throws \Exception * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function execute($entity, $arguments = []) { $metadata = $this->metadataPool->getMetadata(ExtensionAttributeInterface::class); $connection = $this->resourceConnection->getConnectionByName($metadata->getEntityConnectionName()); $id = $connection->fetchOne($connection->select()->from($metadata->getEntityTable(), [$metadata->getIdentifierField()])->where('customer_id = ?', $entity->getId())->limit(1)); $extensionAttribute = $this->extensionAttributeFactory->create(); $extensionAttribute = $this->entityManager->load($extensionAttribute, $id); $customerExtension = $this->customerExtensionFactory->create(['data' => ['extension_attribute' => $extensionAttribute]]); $entity->setExtensionAttributes($customerExtension); return $entity; }
public function testPopulateCustomerInfo() { $this->quoteMock->expects($this->once())->method('getCustomer')->willReturn($this->customerMock); $this->customerMock->expects($this->atLeastOnce())->method('getId')->willReturn(null); $this->customerMock->expects($this->atLeastOnce())->method('getDefaultBilling')->willReturn(100500); $this->quoteMock->expects($this->atLeastOnce())->method('getBillingAddress')->willReturn($this->quoteAddressMock); $this->quoteMock->expects($this->atLeastOnce())->method('getShippingAddress')->willReturn($this->quoteAddressMock); $this->quoteMock->expects($this->atLeastOnce())->method('setCustomer')->with($this->customerMock)->willReturnSelf(); $this->quoteMock->expects($this->once())->method('getPasswordHash')->willReturn('password hash'); $this->quoteAddressMock->expects($this->atLeastOnce())->method('getId')->willReturn(null); $this->customerAddressRepositoryMock->expects($this->atLeastOnce())->method('getById')->with(100500)->willReturn($this->customerAddressMock); $this->quoteAddressMock->expects($this->atLeastOnce())->method('importCustomerAddressData')->willReturnSelf(); $this->accountManagementMock->expects($this->once())->method('createAccountWithPasswordHash')->with($this->customerMock, 'password hash')->willReturn($this->customerMock); $this->customerManagement->populateCustomerInfo($this->quoteMock); }
/** * @Given I have a new address with :street :city :region :zip :country */ public function iHaveANewAddressWith($street, $city, $region, $zip, $country) { $countryId = $this->getCountryId($country); $region = $this->loadRegionByName($region, $countryId); $address = $this->addressFactory->create()->setStreet((array) $street)->setCity($city)->setPostcode($zip)->setCountryId($countryId)->setRegion($region)->setRegionId($region->getRegionId())->setFirstname($this->customer->getFirstname())->setLastname($this->customer->getLastname())->setTelephone('555-555-5555')->setCustomerId($this->customer->getId()); $this->customerAddress = $address; }
/** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function testEditPostActionWithoutErrors() { $customerId = 24; $address = $this->getMockForAbstractClass('Magento\\Customer\\Api\\Data\\AddressInterface', [], '', false); $loadedCustomer = $this->getMockForAbstractClass('Magento\\Customer\\Api\\Data\\CustomerInterface', [], 'loadedCustomer', false); $loadedCustomer->expects($this->once())->method('getAddresses')->willReturn([$address, $address]); $this->resultRedirectFactory->expects($this->once())->method('create')->willReturn($this->redirectResultMock); $this->formKeyValidator->expects($this->once())->method('validate')->willReturn(true); $this->request->expects($this->once())->method('isPost')->willReturn(true); $this->customerSession->expects($this->once())->method('getCustomerId')->willReturn($customerId); $this->customerExtractor->expects($this->once())->method('extract')->willReturn($this->customer); $this->customer->expects($this->once())->method('setId')->with($customerId); $this->customer->expects($this->once())->method('getAddresses')->willReturn(null); $this->customerRepository->expects($this->exactly(2))->method('getById')->with($customerId)->willReturn($loadedCustomer); $this->customer->expects($this->once())->method('setAddresses')->with([$address, $address]); $this->request->expects($this->once())->method('getParam')->with('change_password')->willReturn(true); $this->request->expects($this->at(2))->method('getPost')->with('current_password', null)->willReturn(123); $this->request->expects($this->at(3))->method('getPost')->with('password', null)->willReturn(321); $this->request->expects($this->at(4))->method('getPost')->with('password_confirmation', null)->willReturn(321); $this->customerAccountManagement->expects($this->once())->method('changePassword'); $this->customerRepository->expects($this->once())->method('save'); $messageCollection = $this->getMock('Magento\\Framework\\Message\\Collection', [], [], '', false); $messageCollection->expects($this->once())->method('getCount')->willReturn(0); $this->messageManager->expects($this->once())->method('getMessages')->willReturn($messageCollection); $this->messageManager->expects($this->once())->method('addSuccess')->with('You saved the account information.'); $this->redirectResultMock->expects($this->once())->method('setPath')->with('customer/account')->willReturn('http://test.com/customer/account/edit'); $this->assertSame($this->redirectResultMock, $this->getController()->execute()); }
public function _populateQuoteAddrShipping(\Magento\Quote\Model\Quote $quote, \Magento\Customer\Api\Data\CustomerInterface $customerDo) { /** @var \Magento\Quote\Model\Quote\Address $addr */ $addr = $this->_manObj->create(\Magento\Quote\Model\Quote\Address::class); $addr->setFirstname($customerDo->getFirstname()); $addr->setLastname($customerDo->getLastname()); $addr->setEmail($customerDo->getEmail()); $addr->setTelephone('23344556'); $addr->setStreet('Liela iela'); $addr->setCity('Riga'); $addr->setRegionId(362); // Riga region $addr->setPostcode('1010'); $addr->setCountryId('LV'); $quote->setShippingAddress($addr); return $quote; }
public function testExtract() { $customerData = ['firstname' => 'firstname', 'lastname' => 'firstname', 'email' => 'email.example.com']; $this->formFactory->expects($this->once())->method('create')->with('customer', 'form-code')->willReturn($this->customerForm); $this->customerForm->expects($this->once())->method('extractData')->with($this->request)->willReturn($customerData); $this->customerForm->expects($this->once())->method('getAllowedAttributes')->willReturn(['group_id' => 'attribute object']); $this->customerFactory->expects($this->once())->method('create')->willReturn($this->customerData); $this->dataObjectHelper->expects($this->once())->method('populateWithArray')->with($this->customerData, $customerData, '\\Magento\\Customer\\Api\\Data\\CustomerInterface')->willReturn($this->customerData); $this->storeManager->expects($this->once())->method('getStore')->willReturn($this->store); $this->store->expects($this->exactly(2))->method('getId')->willReturn(1); $this->customerGroupManagement->expects($this->once())->method('getDefaultGroup')->with(1)->willReturn($this->customerGroup); $this->customerGroup->expects($this->once())->method('getId')->willReturn(1); $this->customerData->expects($this->once())->method('setGroupId')->with(1); $this->store->expects($this->once())->method('getWebsiteId')->willReturn(1); $this->customerData->expects($this->once())->method('setWebsiteId')->with(1); $this->customerData->expects($this->once())->method('setStoreId')->with(1); $this->assertSame($this->customerData, $this->customerExtractor->extract('form-code', $this->request)); }
/** * Assign customer address to quote address and save quote address * * @param bool $unsetId */ protected function _setCustomerAddressAndSave($unsetId) { $shippingAddress = $this->_quote->getShippingAddress(); if ($unsetId) { $shippingAddress->setId(null); } /** @var \Magento\Customer\Api\AddressRepositoryInterface $addressRepository */ $addressRepository = Bootstrap::getObjectManager()->create('Magento\\Customer\\Api\\AddressRepositoryInterface'); $shippingAddress->setSameAsBilling(0)->setCustomerAddressData($addressRepository->getById($this->_customer->getDefaultBilling()))->save(); }
public function testDelete() { $customerId = 14; $customerModel = $this->getMock('Magento\\Customer\\Model\\Customer', ['delete'], [], '', false); $this->customer->expects($this->once())->method('getId')->willReturn($customerId); $this->customerRegistry->expects($this->once())->method('retrieve')->with($customerId)->willReturn($customerModel); $customerModel->expects($this->once())->method('delete'); $this->customerRegistry->expects($this->once())->method('remove')->with($customerId); $this->assertTrue($this->model->delete($this->customer)); }
public function testExecuteException() { $exception = new \Exception('Exception message'); $this->prepareMocksForTesting(); $this->customerData->expects($this->once())->method('getDefaultBilling')->willReturn(false); $this->customerRepository->expects($this->once())->method('save')->with($this->customerData)->willThrowException($exception); $this->messageManager->expects($this->once())->method('addError')->with('[Customer ID: 12] We can\'t save the customer.'); $this->logger->expects($this->once())->method('critical')->with($exception); $this->prepareMocksForErrorMessagesProcessing(); $this->assertSame($this->resultJson, $this->controller->execute()); }
/** * Concatenate all customer name parts into full customer name. * * @param CustomerInterface $customerData * @return string */ public function getCustomerName(CustomerInterface $customerData) { $name = ''; $prefixMetadata = $this->_customerMetadataService->getAttributeMetadata('prefix'); if ($prefixMetadata->isVisible() && $customerData->getPrefix()) { $name .= $customerData->getPrefix() . ' '; } $name .= $customerData->getFirstname(); $middleNameMetadata = $this->_customerMetadataService->getAttributeMetadata('middlename'); if ($middleNameMetadata->isVisible() && $customerData->getMiddlename()) { $name .= ' ' . $customerData->getMiddlename(); } $name .= ' ' . $customerData->getLastname(); $suffixMetadata = $this->_customerMetadataService->getAttributeMetadata('suffix'); if ($suffixMetadata->isVisible() && $customerData->getSuffix()) { $name .= ' ' . $customerData->getSuffix(); } return $name; }
/** * Send customer email * * @return bool * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function send() { if ($this->_website === null || $this->_customer === null) { return false; } if ($this->_type == 'price' && count($this->_priceProducts) == 0 || $this->_type == 'stock' && count($this->_stockProducts) == 0) { return false; } if (!$this->_website->getDefaultGroup() || !$this->_website->getDefaultGroup()->getDefaultStore()) { return false; } if ($this->_customer->getStoreId() > 0) { $store = $this->_storeManager->getStore($this->_customer->getStoreId()); } else { $store = $this->_website->getDefaultStore(); } $storeId = $store->getId(); if ($this->_type == 'price' && !$this->_scopeConfig->getValue(self::XML_PATH_EMAIL_PRICE_TEMPLATE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId)) { return false; } elseif ($this->_type == 'stock' && !$this->_scopeConfig->getValue(self::XML_PATH_EMAIL_STOCK_TEMPLATE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId)) { return false; } if ($this->_type != 'price' && $this->_type != 'stock') { return false; } $this->_appEmulation->startEnvironmentEmulation($storeId); if ($this->_type == 'price') { $this->_getPriceBlock()->setStore($store)->reset(); foreach ($this->_priceProducts as $product) { $product->setCustomerGroupId($this->_customer->getGroupId()); $this->_getPriceBlock()->addProduct($product); } $block = $this->_getPriceBlock(); $templateId = $this->_scopeConfig->getValue(self::XML_PATH_EMAIL_PRICE_TEMPLATE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId); } else { $this->_getStockBlock()->setStore($store)->reset(); foreach ($this->_stockProducts as $product) { $product->setCustomerGroupId($this->_customer->getGroupId()); $this->_getStockBlock()->addProduct($product); } $block = $this->_getStockBlock(); $templateId = $this->_scopeConfig->getValue(self::XML_PATH_EMAIL_STOCK_TEMPLATE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId); } $alertGrid = $this->_appState->emulateAreaCode(\Magento\Framework\App\Area::AREA_FRONTEND, [$block, 'toHtml']); $this->_appEmulation->stopEnvironmentEmulation(); $transport = $this->_transportBuilder->setTemplateIdentifier($templateId)->setTemplateOptions(['area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => $storeId])->setTemplateVars(['customerName' => $this->_customerHelper->getCustomerName($this->_customer), 'alertGrid' => $alertGrid])->setFrom($this->_scopeConfig->getValue(self::XML_PATH_EMAIL_IDENTITY, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId))->addTo($this->_customer->getEmail(), $this->_customerHelper->getCustomerName($this->_customer))->getTransport(); $transport->sendMessage(); return true; }
/** * @param $customerId * @param $key * @param $backUrl * @param $successUrl * @param $resultUrl * @param $isSetFlag * @param $successMessage * * @dataProvider getSuccessRedirectDataProvider */ public function testSuccessRedirect($customerId, $key, $backUrl, $successUrl, $resultUrl, $isSetFlag, $successMessage) { $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); $this->requestMock->expects($this->any())->method('getParam')->willReturnMap([['id', false, $customerId], ['key', false, $key], ['back_url', false, $backUrl]]); $this->customerRepositoryMock->expects($this->any())->method('getById')->with($customerId)->will($this->returnValue($this->customerDataMock)); $email = '*****@*****.**'; $this->customerDataMock->expects($this->once())->method('getEmail')->will($this->returnValue($email)); $this->customerAccountManagementMock->expects($this->once())->method('activate')->with($this->equalTo($email), $this->equalTo($key))->will($this->returnValue($this->customerDataMock)); $this->customerSessionMock->expects($this->any())->method('setCustomerDataAsLoggedIn')->with($this->equalTo($this->customerDataMock))->willReturnSelf(); $this->messageManagerMock->expects($this->any())->method('addSuccess')->with($this->stringContains($successMessage))->willReturnSelf(); $this->storeMock->expects($this->any())->method('getFrontendName')->will($this->returnValue('frontend')); $this->storeManagerMock->expects($this->any())->method('getStore')->will($this->returnValue($this->storeMock)); $this->urlMock->expects($this->any())->method('getUrl')->with($this->equalTo('*/*/index'), ['_secure' => true])->will($this->returnValue($successUrl)); $this->redirectMock->expects($this->never())->method('success')->with($this->equalTo($resultUrl))->willReturn($resultUrl); $this->scopeConfigMock->expects($this->never())->method('isSetFlag')->with(Url::XML_PATH_CUSTOMER_STARTUP_REDIRECT_TO_DASHBOARD, ScopeInterface::SCOPE_STORE)->willReturn($isSetFlag); $this->model->execute(); }
/** * Create or update user by using data from facebook and login to store * * @param GraphUser $facebookUser * @param AccessToken $accessToken * * @return CustomerInterface */ private function createOrUpdateAndLogin(GraphUser $facebookUser, AccessToken $accessToken) { if (!$this->customer->getId()) { $this->customer->setEmail($facebookUser->getEmail()); $this->customer->setFirstname($facebookUser->getFirstName()); $this->customer->setLastname($facebookUser->getLastName()); $this->customer->setMiddlename($facebookUser->getMiddleName()); $this->customer->setGender((int) ($facebookUser->getGender() == 'male')); } $this->customer->setCustomAttribute('sf_id', $facebookUser->getId()); $this->customer->setCustomAttribute('sf_access_token', serialize($accessToken)); if ($this->customer->getId()) { $customer = $this->customerRepository->save($this->customer); } else { $customer = $this->accountManagement->createAccount($this->customer); } $this->login($customer->getId()); return $customer; }
/** * @param $customerId * @param $password * @param $confirmationStatus * @param $successUrl * @param $isSetFlag * @param $successMessage * * @dataProvider getSuccessRedirectDataProvider */ public function testSuccessRedirect($customerId, $password, $confirmationStatus, $successUrl, $isSetFlag, $successMessage) { $this->customerSessionMock->expects($this->once())->method('isLoggedIn')->will($this->returnValue(false)); $this->registration->expects($this->once())->method('isAllowed')->will($this->returnValue(true)); $this->customerSessionMock->expects($this->once())->method('regenerateId'); $this->customerMock->expects($this->any())->method('getId')->will($this->returnValue($customerId)); $this->customerExtractorMock->expects($this->any())->method('extract')->with($this->equalTo('customer_account_create'), $this->equalTo($this->requestMock))->will($this->returnValue($this->customerMock)); $this->requestMock->expects($this->once())->method('isPost')->will($this->returnValue(true)); $this->requestMock->expects($this->any())->method('getPost')->will($this->returnValue(false)); $this->requestMock->expects($this->any())->method('getParam')->willReturnMap([['password', null, $password], ['password_confirmation', null, $password], ['is_subscribed', false, true]]); $this->customerMock->expects($this->once())->method('setAddresses')->with($this->equalTo([]))->will($this->returnSelf()); $this->accountManagement->expects($this->once())->method('createAccount')->with($this->equalTo($this->customerDetailsMock), $this->equalTo($password), '')->will($this->returnValue($this->customerMock)); $this->accountManagement->expects($this->once())->method('getConfirmationStatus')->with($this->equalTo($customerId))->will($this->returnValue($confirmationStatus)); $this->subscriberMock->expects($this->once())->method('subscribeCustomerById')->with($this->equalTo($customerId)); $this->messageManagerMock->expects($this->any())->method('addSuccess')->with($this->stringContains($successMessage))->will($this->returnSelf()); $this->urlMock->expects($this->any())->method('getUrl')->willReturnMap([['*/*/index', ['_secure' => true], $successUrl], ['*/*/create', ['_secure' => true], $successUrl]]); $this->redirectMock->expects($this->once())->method('success')->with($this->equalTo($successUrl))->will($this->returnValue($successUrl)); $this->scopeConfigMock->expects($this->once())->method('isSetFlag')->with($this->equalTo(Url::XML_PATH_CUSTOMER_STARTUP_REDIRECT_TO_DASHBOARD), $this->equalTo(ScopeInterface::SCOPE_STORE))->will($this->returnValue($isSetFlag)); $this->storeMock->expects($this->any())->method('getFrontendName')->will($this->returnValue('frontend')); $this->storeManagerMock->expects($this->any())->method('getStore')->will($this->returnValue($this->storeMock)); $this->model->execute(); }
/** * Create a quote object with customer * * @param array $quoteData * @param \Magento\Customer\Api\Data\CustomerInterface $customer * @return \Magento\Quote\Model\Quote */ protected function createQuote($quoteData, $customer) { /** @var \Magento\Customer\Api\AddressRepositoryInterface $addressService */ $addressService = $this->objectManager->create('Magento\\Customer\\Api\\AddressRepositoryInterface'); /** @var array $shippingAddressOverride */ $shippingAddressOverride = empty($quoteData['shipping_address']) ? [] : $quoteData['shipping_address']; /** @var \Magento\Customer\Model\Address $shippingAddress */ $shippingAddress = $this->createCustomerAddress($shippingAddressOverride, $customer->getId()); /** @var \Magento\Quote\Model\Quote\Address $quoteShippingAddress */ $quoteShippingAddress = $this->objectManager->create('Magento\\Quote\\Model\\Quote\\Address'); $quoteShippingAddress->importCustomerAddressData($addressService->getById($shippingAddress->getId())); /** @var array $billingAddressOverride */ $billingAddressOverride = empty($quoteData['billing_address']) ? [] : $quoteData['billing_address']; /** @var \Magento\Customer\Model\Address $billingAddress */ $billingAddress = $this->createCustomerAddress($billingAddressOverride, $customer->getId()); /** @var \Magento\Quote\Model\Quote\Address $quoteBillingAddress */ $quoteBillingAddress = $this->objectManager->create('Magento\\Quote\\Model\\Quote\\Address'); $quoteBillingAddress->importCustomerAddressData($addressService->getById($billingAddress->getId())); /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->objectManager->create('Magento\\Quote\\Model\\Quote'); $quote->setStoreId(1)->setIsActive(true)->setIsMultiShipping(false)->assignCustomerWithAddressChange($customer, $quoteBillingAddress, $quoteShippingAddress)->setCheckoutMethod('register')->setPasswordHash($this->accountManagement->getPasswordHash(static::CUSTOMER_PASSWORD)); return $quote; }
/** * Process change email request * * @param \Magento\Customer\Api\Data\CustomerInterface $currentCustomerDataObject * @return void * @throws InvalidEmailOrPasswordException * @throws UserLockedException */ private function processChangeEmailRequest(\Magento\Customer\Api\Data\CustomerInterface $currentCustomerDataObject) { if ($this->getRequest()->getParam('change_email')) { // authenticate user for changing email try { $this->getAuthentication()->authenticate($currentCustomerDataObject->getId(), $this->getRequest()->getPost('current_password')); } catch (InvalidEmailOrPasswordException $e) { throw new InvalidEmailOrPasswordException(__('The password doesn\'t match this account.')); } } }
/** * @param CustomerInterface $customerDataModel * @return string */ protected function getOpenpayCustomerId(CustomerInterface $customerDataModel) { $openpayCustomer = $customerDataModel->getCustomAttribute(UpgradeData::OPENPAY_CUSTOMER_ID_CUSTOM_ATTRIBUTE); $openpayCustomerId = is_null($openpayCustomer) ? null : $openpayCustomer->getValue(); return $openpayCustomerId; }
/** * Create an object with data merged from Customer and CustomerSecure * * @param CustomerInterface $customer * @return Data\CustomerSecure */ protected function getFullCustomerObject($customer) { // No need to flatten the custom attributes or nested objects since the only usage is for email templates and // object passed for events $mergedCustomerData = $this->customerRegistry->retrieveSecureData($customer->getId()); $customerData = $this->dataProcessor->buildOutputDataArray($customer, '\\Magento\\Customer\\Api\\Data\\CustomerInterface'); $mergedCustomerData->addData($customerData); $mergedCustomerData->setData('name', $this->customerViewHelper->getCustomerName($customer)); return $mergedCustomerData; }
/** * Get checkout quote instance by current session * * @return Quote * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function getQuote() { $this->_eventManager->dispatch('custom_quote_process', ['checkout_session' => $this]); if ($this->_quote === null) { $quote = $this->quoteFactory->create(); if ($this->getQuoteId()) { try { if ($this->_loadInactive) { $quote = $this->quoteRepository->get($this->getQuoteId()); } else { $quote = $this->quoteRepository->getActive($this->getQuoteId()); } /** * If current currency code of quote is not equal current currency code of store, * need recalculate totals of quote. It is possible if customer use currency switcher or * store switcher. */ if ($quote->getQuoteCurrencyCode() != $this->_storeManager->getStore()->getCurrentCurrencyCode()) { $quote->setStore($this->_storeManager->getStore()); $this->quoteRepository->save($quote->collectTotals()); /* * We mast to create new quote object, because collectTotals() * can to create links with other objects. */ $quote = $this->quoteRepository->get($this->getQuoteId()); } } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { $this->setQuoteId(null); } } if (!$this->getQuoteId()) { if ($this->_customerSession->isLoggedIn() || $this->_customer) { $customerId = $this->_customer ? $this->_customer->getId() : $this->_customerSession->getCustomerId(); try { $quote = $this->quoteRepository->getActiveForCustomer($customerId); $this->setQuoteId($quote->getId()); } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { } } else { $quote->setIsCheckoutCart(true); $this->_eventManager->dispatch('checkout_quote_init', ['quote' => $quote]); } } if ($this->_customer) { $quote->setCustomer($this->_customer); } elseif ($this->_customerSession->isLoggedIn()) { $quote->setCustomer($this->customerRepository->getById($this->_customerSession->getCustomerId())); } $quote->setStore($this->_storeManager->getStore()); $this->_quote = $quote; } if (!$this->isQuoteMasked() && !$this->_customerSession->isLoggedIn() && $this->getQuoteId()) { $quoteId = $this->getQuoteId(); /** @var $quoteIdMask \Magento\Quote\Model\QuoteIdMask */ $quoteIdMask = $this->quoteIdMaskFactory->create()->load($quoteId, 'quote_id'); if ($quoteIdMask->getMaskedId() === null) { $quoteIdMask->setQuoteId($quoteId)->save(); } $this->setIsQuoteMasked(true); } $remoteAddress = $this->_remoteAddress->getRemoteAddress(); if ($remoteAddress) { $this->_quote->setRemoteIp($remoteAddress); $xForwardIp = $this->request->getServer('HTTP_X_FORWARDED_FOR'); $this->_quote->setXForwardedFor($xForwardIp); } return $this->_quote; }
/** * Create customer address and save it in the quote so that it can be used to persist later. * * @param \Magento\Customer\Api\Data\CustomerInterface $customer * @param \Magento\Quote\Model\Quote\Address $quoteCustomerAddress * @return void * @throws \InvalidArgumentException * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ protected function _prepareCustomerAddress($customer, $quoteCustomerAddress) { // Possible that customerId is null for new customers $quoteCustomerAddress->setCustomerId($customer->getId()); $customerAddress = $quoteCustomerAddress->exportCustomerAddress(); $quoteAddressId = $quoteCustomerAddress->getCustomerAddressId(); $addressType = $quoteCustomerAddress->getAddressType(); if ($quoteAddressId) { /** Update existing address */ $existingAddressDataObject = $this->addressRepository->getById($quoteAddressId); /** Update customer address data */ $this->dataObjectHelper->mergeDataObjects(get_class($existingAddressDataObject), $existingAddressDataObject, $customerAddress); $customerAddress = $existingAddressDataObject; } elseif ($addressType == \Magento\Quote\Model\Quote\Address::ADDRESS_TYPE_SHIPPING) { try { $billingAddressDataObject = $this->accountManagement->getDefaultBillingAddress($customer->getId()); } catch (\Exception $e) { /** Billing address does not exist. */ } $isShippingAsBilling = $quoteCustomerAddress->getSameAsBilling(); if (isset($billingAddressDataObject) && $isShippingAsBilling) { /** Set existing billing address as default shipping */ $customerAddress = $billingAddressDataObject; $customerAddress->setIsDefaultShipping(true); } } switch ($addressType) { case \Magento\Quote\Model\Quote\Address::ADDRESS_TYPE_BILLING: if (is_null($customer->getDefaultBilling())) { $customerAddress->setIsDefaultBilling(true); } break; case \Magento\Quote\Model\Quote\Address::ADDRESS_TYPE_SHIPPING: if (is_null($customer->getDefaultShipping())) { $customerAddress->setIsDefaultShipping(true); } break; default: throw new \InvalidArgumentException('Customer address type is invalid.'); } $this->getQuote()->setCustomer($customer); $this->getQuote()->addCustomerAddress($customerAddress); }
/** * Define customer object * * @param \Magento\Customer\Api\Data\CustomerInterface $customer * @return $this */ public function setCustomer(\Magento\Customer\Api\Data\CustomerInterface $customer = null) { /* @TODO: Remove the method after all external usages are refactored in MAGETWO-19930 */ $this->_customer = $customer; $this->setCustomerId($customer->getId()); $origAddresses = $customer->getAddresses(); $customer->setAddresses([]); $customerDataFlatArray = $this->objectFactory->create($this->extensibleDataObjectConverter->toFlatArray($customer, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface')); $customer->setAddresses($origAddresses); $this->_objectCopyService->copyFieldsetToTarget('customer_account', 'to_quote', $customerDataFlatArray, $this); return $this; }
/** * Validate customer attribute values. * * @param \Magento\Customer\Api\Data\CustomerInterface $customer * @throws InputException * @return void * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ private function validate(\Magento\Customer\Api\Data\CustomerInterface $customer) { $exception = new InputException(); if (!\Zend_Validate::is(trim($customer->getFirstname()), 'NotEmpty')) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'firstname'])); } if (!\Zend_Validate::is(trim($customer->getLastname()), 'NotEmpty')) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'lastname'])); } $isEmailAddress = \Zend_Validate::is($customer->getEmail(), 'EmailAddress'); if (!$isEmailAddress) { $exception->addError(__(InputException::INVALID_FIELD_VALUE, ['fieldName' => 'email', 'value' => $customer->getEmail()])); } $dob = $this->getAttributeMetadata('dob'); if ($dob !== null && $dob->isRequired() && '' == trim($customer->getDob())) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'dob'])); } $taxvat = $this->getAttributeMetadata('taxvat'); if ($taxvat !== null && $taxvat->isRequired() && '' == trim($customer->getTaxvat())) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'taxvat'])); } $gender = $this->getAttributeMetadata('gender'); if ($gender !== null && $gender->isRequired() && '' == trim($customer->getGender())) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'gender'])); } if ($exception->wasErrorAdded()) { throw $exception; } }
/** * Load subscriber by customer * * @param \Magento\Customer\Api\Data\CustomerInterface $customer * @return array */ public function loadByCustomerData(\Magento\Customer\Api\Data\CustomerInterface $customer) { $select = $this->connection->select()->from($this->getMainTable())->where('customer_id=:customer_id'); $result = $this->connection->fetchRow($select, ['customer_id' => $customer->getId()]); if ($result) { return $result; } $select = $this->connection->select()->from($this->getMainTable())->where('subscriber_email=:subscriber_email'); $result = $this->connection->fetchRow($select, ['subscriber_email' => $customer->getEmail()]); if ($result) { return $result; } return []; }
/** * @param CustomerInterface $entity * @return CustomerInterface * @throws \Exception * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function execute($entity, $arguments = []) { $searchCriteria = $this->searchCriteriaBuilder->addFilter('parent_id', $entity->getId())->create(); $addressesResult = $this->addressRepository->getList($searchCriteria); $entity->setAddresses($addressesResult->getItems()); return $entity; }