Beispiel #1
0
 /**
  * @param string $formCode
  * @param RequestInterface $request
  * @return \Magento\Customer\Service\V1\Data\Customer
  */
 public function extract($formCode, RequestInterface $request)
 {
     $customerForm = $this->formFactory->create('customer', $formCode);
     $allowedAttributes = $customerForm->getAllowedAttributes();
     $isGroupIdEmpty = true;
     $customerData = array();
     foreach ($allowedAttributes as $attribute) {
         // confirmation in request param is the repeated password, not a confirmation code.
         if ($attribute === 'confirmation') {
             continue;
         }
         $attributeCode = $attribute->getAttributeCode();
         if ($attributeCode == 'group_id') {
             $isGroupIdEmpty = false;
         }
         $customerData[$attributeCode] = $request->getParam($attributeCode);
     }
     $this->customerBuilder->populateWithArray($customerData);
     $store = $this->storeManager->getStore();
     if ($isGroupIdEmpty) {
         $this->customerBuilder->setGroupId($this->groupService->getDefaultGroup($store->getId())->getId());
     }
     $this->customerBuilder->setWebsiteId($store->getWebsiteId());
     $this->customerBuilder->setStoreId($store->getId());
     return $this->customerBuilder->create();
 }
 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]);
 }
 /**
  * Prepare Form and add elements to form
  *
  * @return $this
  */
 protected function _prepareForm()
 {
     /** @var \Magento\Customer\Model\Metadata\Form $customerForm */
     $customerForm = $this->_metadataFormFactory->create('customer', 'adminhtml_checkout');
     // prepare customer attributes to show
     $attributes = [];
     // add system required attributes
     foreach ($customerForm->getSystemAttributes() as $attribute) {
         if ($attribute->isRequired()) {
             $attributes[$attribute->getAttributeCode()] = $attribute;
         }
     }
     if ($this->getQuote()->getCustomerIsGuest()) {
         unset($attributes['group_id']);
     }
     // add user defined attributes
     foreach ($customerForm->getUserAttributes() as $attribute) {
         $attributes[$attribute->getAttributeCode()] = $attribute;
     }
     $fieldset = $this->_form->addFieldset('main', []);
     $this->_addAttributesToForm($attributes, $fieldset);
     $this->_form->addFieldNameSuffix('order[account]');
     $this->_form->setValues($this->getFormValues());
     return $this;
 }
 /**
  * @param string $formCode
  * @param RequestInterface $request
  * @return \Magento\Customer\Api\Data\CustomerInterface
  */
 public function extract($formCode, RequestInterface $request)
 {
     $customerForm = $this->formFactory->create('customer', $formCode);
     $customerData = $customerForm->extractData($request);
     $allowedAttributes = $customerForm->getAllowedAttributes();
     $isGroupIdEmpty = isset($allowedAttributes['group_id']);
     $customerDataObject = $this->customerFactory->create();
     $this->dataObjectHelper->populateWithArray($customerDataObject, $customerData, '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     $store = $this->storeManager->getStore();
     if ($isGroupIdEmpty) {
         $customerDataObject->setGroupId($this->customerGroupManagement->getDefaultGroup($store->getId())->getId());
     }
     $customerDataObject->setWebsiteId($store->getWebsiteId());
     $customerDataObject->setStoreId($store->getId());
     return $customerDataObject;
 }
Beispiel #5
0
 public function testSetAccountData()
 {
     $taxClassId = 1;
     $attributes = [['email', '*****@*****.**'], ['group_id', 1]];
     $attributeMocks = [];
     foreach ($attributes as $attribute) {
         $attributeMock = $this->getMock('Magento\\Customer\\Api\\Data\\AttributeMetadataInterface', [], [], '', false);
         $attributeMock->expects($this->any())->method('getAttributeCode')->will($this->returnValue($attribute[0]));
         $attributeMocks[] = $attributeMock;
     }
     $customerGroupMock = $this->getMockForAbstractClass('Magento\\Customer\\Api\\Data\\GroupInterface', [], '', false, true, true, ['getTaxClassId']);
     $customerGroupMock->expects($this->once())->method('getTaxClassId')->will($this->returnValue($taxClassId));
     $customerFormMock = $this->getMock('Magento\\Customer\\Model\\Metadata\\Form', [], [], '', false);
     $customerFormMock->expects($this->any())->method('getAttributes')->will($this->returnValue($attributeMocks));
     $customerFormMock->expects($this->any())->method('extractData')->will($this->returnValue([]));
     $customerFormMock->expects($this->any())->method('restoreData')->will($this->returnValue([]));
     $customerFormMock->expects($this->any())->method('prepareRequest')->will($this->returnValue($this->getMock('Magento\\Framework\\App\\RequestInterface')));
     $customerMock = $this->getMock('Magento\\Customer\\Api\\Data\\CustomerInterface', [], [], '', false);
     $this->customerMapper->expects($this->atLeastOnce())->method('toFlatArray')->willReturn(['email' => '*****@*****.**', 'group_id' => 1, 'gender' => 1]);
     $quoteMock = $this->getMock('Magento\\Quote\\Model\\Quote', [], [], '', false);
     $quoteMock->expects($this->any())->method('getCustomer')->will($this->returnValue($customerMock));
     $quoteMock->expects($this->once())->method('addData')->with(['customer_email' => $attributes[0][1], 'customer_group_id' => $attributes[1][1], 'customer_tax_class_id' => $taxClassId]);
     $this->dataObjectHelper->expects($this->once())->method('populateWithArray')->with($customerMock, ['email' => '*****@*****.**', 'group_id' => 1, 'gender' => 1], '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     $this->formFactoryMock->expects($this->any())->method('create')->will($this->returnValue($customerFormMock));
     $this->sessionQuoteMock->expects($this->any())->method('getQuote')->will($this->returnValue($quoteMock));
     $this->customerFactoryMock->expects($this->any())->method('create')->will($this->returnValue($customerMock));
     $this->groupRepositoryMock->expects($this->once())->method('getById')->will($this->returnValue($customerGroupMock));
     $this->adminOrderCreate->setAccountData([]);
 }
 /**
  * Add address to customer during create account
  *
  * @return AddressInterface|null
  */
 protected function extractAddress()
 {
     if (!$this->getRequest()->getPost('create_address')) {
         return null;
     }
     $addressForm = $this->formFactory->create('customer_address', 'customer_register_address');
     $allowedAttributes = $addressForm->getAllowedAttributes();
     $addressData = [];
     $regionDataObject = $this->regionDataFactory->create();
     foreach ($allowedAttributes as $attribute) {
         $attributeCode = $attribute->getAttributeCode();
         $value = $this->getRequest()->getParam($attributeCode);
         if ($value === null) {
             continue;
         }
         switch ($attributeCode) {
             case 'region_id':
                 $regionDataObject->setRegionId($value);
                 break;
             case 'region':
                 $regionDataObject->setRegion($value);
                 break;
             default:
                 $addressData[$attributeCode] = $value;
         }
     }
     $addressDataObject = $this->addressDataFactory->create();
     $this->dataObjectHelper->populateWithArray($addressDataObject, $addressData, '\\Magento\\Customer\\Api\\Data\\AddressInterface');
     $addressDataObject->setRegion($regionDataObject);
     $addressDataObject->setIsDefaultBilling($this->getRequest()->getParam('default_billing', false))->setIsDefaultShipping($this->getRequest()->getParam('default_shipping', false));
     return $addressDataObject;
 }
Beispiel #7
0
 /**
  * Add address to customer during create account
  *
  * @return \Magento\Customer\Service\V1\Data\Address|null
  */
 protected function _extractAddress()
 {
     if (!$this->getRequest()->getPost('create_address')) {
         return null;
     }
     $addressForm = $this->_formFactory->create('customer_address', 'customer_register_address');
     $allowedAttributes = $addressForm->getAllowedAttributes();
     $addressData = array();
     foreach ($allowedAttributes as $attribute) {
         $attributeCode = $attribute->getAttributeCode();
         $value = $this->getRequest()->getParam($attributeCode);
         if (is_null($value)) {
             continue;
         }
         switch ($attributeCode) {
             case 'region_id':
                 $this->_regionBuilder->setRegionId($value);
                 break;
             case 'region':
                 $this->_regionBuilder->setRegion($value);
                 break;
             default:
                 $addressData[$attributeCode] = $value;
         }
     }
     $this->_addressBuilder->populateWithArray($addressData);
     $this->_addressBuilder->setRegion($this->_regionBuilder->create());
     $this->_addressBuilder->setDefaultBilling($this->getRequest()->getParam('default_billing', false))->setDefaultShipping($this->getRequest()->getParam('default_shipping', false));
     return $this->_addressBuilder->create();
 }
Beispiel #8
0
 /**
  * Initialize customer form
  *
  * @return \Magento\Customer\Model\Metadata\Form $customerForm
  */
 protected function _getCustomerForm()
 {
     if (is_null($this->_customerForm)) {
         $this->_customerForm = $this->_customerFormFactory->create('customer', 'adminhtml_customer', DataObjectConverter::toFlatArray($this->_getCustomerDataObject()));
     }
     return $this->_customerForm;
 }
Beispiel #9
0
 public function testSetAccountData()
 {
     $taxClassId = 1;
     $attributes = array(array('email', '*****@*****.**'), array('group_id', 1));
     $attributeMocks = array();
     foreach ($attributes as $attribute) {
         $attributeMock = $this->getMock('Magento\\Customer\\Service\\V1\\Data\\Eav\\AttributeMetadata', array(), array(), '', false);
         $attributeMock->expects($this->any())->method('getAttributeCode')->will($this->returnValue($attribute[0]));
         $attributeMocks[] = $attributeMock;
     }
     $customerGroupMock = $this->getMock('Magento\\Customer\\Service\\V1\\Data\\CustomerGroup', array(), array(), '', false);
     $customerGroupMock->expects($this->once())->method('getTaxClassId')->will($this->returnValue($taxClassId));
     $customerFormMock = $this->getMock('Magento\\Customer\\Model\\Metadata\\Form', array(), array(), '', false);
     $customerFormMock->expects($this->any())->method('getAttributes')->will($this->returnValue($attributeMocks));
     $customerFormMock->expects($this->any())->method('extractData')->will($this->returnValue(array()));
     $customerFormMock->expects($this->any())->method('restoreData')->will($this->returnValue(array()));
     $customerFormMock->expects($this->any())->method('prepareRequest')->will($this->returnValue($this->getMock('Magento\\Framework\\App\\RequestInterface')));
     $customerMock = $this->getMock('Magento\\Customer\\Service\\V1\\Data\\Customer', array(), array(), '', false);
     $customerMock->expects($this->any())->method('__toArray')->will($this->returnValue(array('email' => '*****@*****.**', 'group_id' => 1)));
     $quoteMock = $this->getMock('Magento\\Sales\\Model\\Quote', array(), array(), '', false);
     $quoteMock->expects($this->any())->method('getCustomerData')->will($this->returnValue($customerMock));
     $quoteMock->expects($this->once())->method('addData')->with(array('customer_email' => $attributes[0][1], 'customer_group_id' => $attributes[1][1], 'customer_tax_class_id' => $taxClassId));
     $this->formFactoryMock->expects($this->any())->method('create')->will($this->returnValue($customerFormMock));
     $this->sessionQuoteMock->expects($this->any())->method('getQuote')->will($this->returnValue($quoteMock));
     $this->customerBuilderMock->expects($this->any())->method('populateWithArray')->will($this->returnSelf());
     $this->customerBuilderMock->expects($this->any())->method('create')->will($this->returnValue($customerMock));
     $this->customerBuilderMock->expects($this->any())->method('mergeDataObjectWithArray')->will($this->returnArgument(0));
     $this->customerGroupServiceMock->expects($this->once())->method('getGroup')->will($this->returnValue($customerGroupMock));
     $this->adminOrderCreate->setAccountData(array());
 }
Beispiel #10
0
 /**
  * Initialize customer form
  *
  * @return \Magento\Customer\Model\Metadata\Form $customerForm
  */
 protected function _getCustomerForm()
 {
     if ($this->_customerForm === null) {
         $this->_customerForm = $this->_customerFormFactory->create('customer', 'adminhtml_customer', $this->_extensibleDataObjectConverter->toFlatArray($this->_getCustomerDataObject()));
     }
     return $this->_customerForm;
 }
 /**
  * @dataProvider saveBillingDataProvider
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 public function testSaveBilling($data, $customerAddressId, $quoteCustomerId, $addressCustomerId, $isAddress, $validateDataResult, $validateResult, $checkoutMethod, $customerPassword, $confirmPassword, $validationResultMessages, $isEmailAvailable, $isVirtual, $getStepDataResult, $expected)
 {
     $useForShipping = (int) $data['use_for_shipping'];
     $passwordHash = 'password hash';
     $this->requestMock->expects($this->any())->method('isAjax')->will($this->returnValue(false));
     $customerValidationResultMock = $this->getMock('Magento\\Customer\\Api\\Data\\ValidationResultsInterface', [], [], '', false);
     $customerValidationResultMock->expects($this->any())->method('isValid')->will($this->returnValue(empty($validationResultMessages)));
     $customerValidationResultMock->expects($this->any())->method('getMessages')->will($this->returnValue($validationResultMessages));
     $this->accountManagementMock->expects($this->any())->method('getPasswordHash')->with($customerPassword)->will($this->returnValue($passwordHash));
     $this->accountManagementMock->expects($this->any())->method('validate')->will($this->returnValue($customerValidationResultMock));
     $this->accountManagementMock->expects($this->any())->method('isEmailAvailable')->will($this->returnValue($isEmailAvailable));
     /** @var \Magento\Quote\Model\Quote|\PHPUnit_Framework_MockObject_MockObject $quoteMock */
     $quoteMock = $this->getMock('Magento\\Quote\\Model\\Quote', ['getData', 'getCustomerId', '__wakeup', 'getBillingAddress', 'setPasswordHash', 'getCheckoutMethod', 'isVirtual', 'getShippingAddress', 'getCustomerData', 'collectTotals', 'save', 'getCustomer'], [], '', false);
     $customerMock = $this->getMockForAbstractClass('Magento\\Framework\\Api\\AbstractExtensibleObject', [], '', false, true, true, ['__toArray']);
     $shippingAddressMock = $this->getMock('Magento\\Quote\\Model\\Quote\\Address', ['setSameAsBilling', 'save', 'collectTotals', 'addData', 'setShippingMethod', 'setCollectShippingRates', '__wakeup'], [], '', false);
     $quoteMock->expects($this->any())->method('getShippingAddress')->will($this->returnValue($shippingAddressMock));
     $shippingAddressMock->expects($useForShipping ? $this->any() : $this->once())->method('setSameAsBilling')->with($useForShipping)->will($this->returnSelf());
     $expects = !$useForShipping || $checkoutMethod != Onepage::METHOD_REGISTER ? $this->once() : $this->never();
     $shippingAddressMock->expects($expects)->method('save');
     $shippingAddressMock->expects($useForShipping ? $this->once() : $this->never())->method('addData')->will($this->returnSelf());
     $shippingAddressMock->expects($this->any())->method('setSaveInAddressBook')->will($this->returnSelf());
     $shippingAddressMock->expects($useForShipping ? $this->once() : $this->never())->method('setShippingMethod')->will($this->returnSelf());
     $shippingAddressMock->expects($useForShipping ? $this->once() : $this->never())->method('setCollectShippingRates')->will($this->returnSelf());
     $shippingAddressMock->expects($useForShipping ? $this->once() : $this->never())->method('collectTotals');
     $quoteMock->expects($this->any())->method('setPasswordHash')->with($passwordHash);
     $quoteMock->expects($this->any())->method('getCheckoutMethod')->will($this->returnValue($checkoutMethod));
     $quoteMock->expects($this->any())->method('isVirtual')->will($this->returnValue($isVirtual));
     $addressMock = $this->getMock('Magento\\Quote\\Model\\Quote\\Address', ['setSaveInAddressBook', 'getData', 'setEmail', '__wakeup', 'importCustomerAddressData', 'validate', 'save'], [], '', false);
     $addressMock->expects($this->any())->method('importCustomerAddressData')->will($this->returnSelf());
     $addressMock->expects($this->atLeastOnce())->method('validate')->will($this->returnValue($validateResult));
     $addressMock->expects($this->any())->method('getData')->will($this->returnValue([]));
     $quoteMock->expects($this->any())->method('getBillingAddress')->will($this->returnValue($addressMock));
     $quoteMock->expects($this->any())->method('getCustomerId')->will($this->returnValue($quoteCustomerId));
     $this->quoteRepositoryMock->expects($checkoutMethod === Onepage::METHOD_REGISTER ? $this->once() : $this->never())->method('save')->with($quoteMock);
     $addressMock->expects($checkoutMethod === Onepage::METHOD_REGISTER ? $this->never() : $this->once())->method('save');
     $quoteMock->expects($this->any())->method('getCustomer')->will($this->returnValue($customerMock));
     $data1 = [];
     $extensibleDataObjectConverterMock = $this->getMock('Magento\\Framework\\Api\\ExtensibleDataObjectConverter', ['toFlatArray'], [], '', false);
     $extensibleDataObjectConverterMock->expects($this->any())->method('toFlatArray')->with($customerMock)->will($this->returnValue($data1));
     $formMock = $this->getMock('Magento\\Customer\\Model\\Metadata\\Form', [], [], '', false);
     $formMock->expects($this->atLeastOnce())->method('validateData')->will($this->returnValue($validateDataResult));
     $this->formFactoryMock->expects($this->any())->method('create')->will($this->returnValue($formMock));
     $formMock->expects($this->any())->method('prepareRequest')->will($this->returnValue($this->requestMock));
     $formMock->expects($this->any())->method('extractData')->with($this->requestMock)->will($this->returnValue([]));
     $formMock->expects($this->any())->method('validateData')->with([])->will($this->returnValue(false));
     $customerDataMock = $this->getMock('Magento\\Customer\\Api\\Data\\CustomerInterface', [], [], '', false);
     $this->customerDataFactoryMock->expects($this->any())->method('create')->will($this->returnValue($customerDataMock));
     $this->checkoutSessionMock->expects($this->any())->method('getQuote')->will($this->returnValue($quoteMock));
     $this->checkoutSessionMock->expects($this->any())->method('getStepData')->will($this->returnValue($useForShipping ? true : $getStepDataResult));
     $this->checkoutSessionMock->expects($this->any())->method('setStepData')->will($this->returnSelf());
     $customerAddressMock = $this->getMockForAbstractClass('Magento\\Customer\\Api\\Data\\AddressInterface', [], '', false);
     $customerAddressMock->expects($this->any())->method('getCustomerId')->will($this->returnValue($addressCustomerId));
     $this->addressRepositoryMock->expects($this->any())->method('getById')->will($isAddress ? $this->returnValue($customerAddressMock) : $this->throwException(new \Exception()));
     $websiteMock = $this->getMock('Magento\\Store\\Model\\Website', [], [], '', false);
     $this->storeManagerMock->expects($this->any())->method('getWebsite')->will($this->returnValue($websiteMock));
     $this->assertEquals($expected, $this->onepage->saveBilling($data, $customerAddressId));
 }
 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));
 }
Beispiel #13
0
 /**
  * Prepare Form and add elements to form
  *
  * @return $this
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 protected function _prepareForm()
 {
     $fieldset = $this->_form->addFieldset('main', array('no_container' => true));
     $addressForm = $this->_customerFormFactory->create('customer_address', 'adminhtml_customer_address');
     $attributes = $addressForm->getAttributes();
     $this->_addAttributesToForm($attributes, $fieldset);
     $prefixElement = $this->_form->getElement('prefix');
     if ($prefixElement) {
         $prefixOptions = $this->_customerHelper->getNamePrefixOptions($this->getStore());
         if (!empty($prefixOptions)) {
             $fieldset->removeField($prefixElement->getId());
             $prefixField = $fieldset->addField($prefixElement->getId(), 'select', $prefixElement->getData(), '^');
             $prefixField->setValues($prefixOptions);
             if ($this->getAddressId()) {
                 $prefixField->addElementValues($this->getAddress()->getPrefix());
             }
         }
     }
     $suffixElement = $this->_form->getElement('suffix');
     if ($suffixElement) {
         $suffixOptions = $this->_customerHelper->getNameSuffixOptions($this->getStore());
         if (!empty($suffixOptions)) {
             $fieldset->removeField($suffixElement->getId());
             $suffixField = $fieldset->addField($suffixElement->getId(), 'select', $suffixElement->getData(), $this->_form->getElement('lastname')->getId());
             $suffixField->setValues($suffixOptions);
             if ($this->getAddressId()) {
                 $suffixField->addElementValues($this->getAddress()->getSuffix());
             }
         }
     }
     $regionElement = $this->_form->getElement('region_id');
     if ($regionElement) {
         $regionElement->setNoDisplay(true);
     }
     $this->_form->setValues($this->getFormValues());
     if ($this->_form->getElement('country_id')->getValue()) {
         $countryId = $this->_form->getElement('country_id')->getValue();
         $this->_form->getElement('country_id')->setValue(null);
         foreach ($this->_form->getElement('country_id')->getValues() as $country) {
             if ($country['value'] == $countryId) {
                 $this->_form->getElement('country_id')->setValue($countryId);
             }
         }
     }
     if (is_null($this->_form->getElement('country_id')->getValue())) {
         $this->_form->getElement('country_id')->setValue($this->_coreData->getDefaultCountry($this->getStore()));
     }
     // Set custom renderer for VAT field if needed
     $vatIdElement = $this->_form->getElement('vat_id');
     if ($vatIdElement && $this->getDisplayVatValidationButton() !== false) {
         $vatIdElement->setRenderer($this->getLayout()->createBlock('Magento\\Customer\\Block\\Adminhtml\\Sales\\Order\\Address\\Form\\Renderer\\Vat')->setJsVariablePrefix($this->getJsVariablePrefix()));
     }
     return $this;
 }
Beispiel #14
0
 /**
  * Perform customer data filtration based on form code and form object
  *
  * @param \Magento\Framework\App\RequestInterface $request
  * @param string $formCode The code of EAV form to take the list of attributes from
  * @param string $entityType entity type for the form
  * @param string[] $additionalAttributes The list of attribute codes to skip filtration for
  * @param string $scope scope of the request
  * @param \Magento\Customer\Model\Metadata\Form $metadataForm to use for extraction
  * @return array Filtered customer data
  */
 protected function _extractData(\Magento\Framework\App\RequestInterface $request, $formCode, $entityType, $additionalAttributes = [], $scope = null, \Magento\Customer\Model\Metadata\Form $metadataForm = null)
 {
     if ($metadataForm === null) {
         $metadataForm = $this->_formFactory->create($entityType, $formCode, [], false, \Magento\Customer\Model\Metadata\Form::DONT_IGNORE_INVISIBLE);
     }
     $filteredData = $metadataForm->extractData($request, $scope);
     $object = $this->_objectFactory->create(['data' => $request->getPostValue()]);
     $requestData = $object->getData($scope);
     foreach ($additionalAttributes as $attributeCode) {
         $filteredData[$attributeCode] = isset($requestData[$attributeCode]) ? $requestData[$attributeCode] : false;
     }
     $formAttributes = $metadataForm->getAttributes();
     /** @var \Magento\Customer\Api\Data\AttributeMetadataInterface $attribute */
     foreach ($formAttributes as $attribute) {
         $attributeCode = $attribute->getAttributeCode();
         $frontendInput = $attribute->getFrontendInput();
         if ($frontendInput != 'boolean' && $filteredData[$attributeCode] === false) {
             unset($filteredData[$attributeCode]);
         }
     }
     return $filteredData;
 }
 /**
  * @dataProvider saveBillingDataProvider
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function testSaveBilling($data, $customerAddressId, $quoteCustomerId, $addressCustomerId, $isAddress, $validateDataResult, $validateResult, $checkoutMethod, $customerPassword, $confirmPassword, $validationResultMessages, $isEmailAvailable, $isVirtual, $getStepDataResult, $expected)
 {
     $passwordHash = 'password hash';
     $this->requestMock->expects($this->any())->method('isAjax')->will($this->returnValue(false));
     $customerValidationResultMock = $this->getMock('Magento\\Customer\\Service\\V1\\Data\\CustomerValidationResults', [], [], '', false);
     $customerValidationResultMock->expects($this->any())->method('isValid')->will($this->returnValue(empty($validationResultMessages)));
     $customerValidationResultMock->expects($this->any())->method('getMessages')->will($this->returnValue($validationResultMessages));
     $this->customerAccountServiceMock->expects($this->any())->method('getPasswordHash')->with($customerPassword)->will($this->returnValue($passwordHash));
     $this->customerAccountServiceMock->expects($this->any())->method('validateCustomerData')->will($this->returnValue($customerValidationResultMock));
     $this->customerAccountServiceMock->expects($this->any())->method('isEmailAvailable')->will($this->returnValue($isEmailAvailable));
     /** @var \Magento\Sales\Model\Quote|\PHPUnit_Framework_MockObject_MockObject $quoteMock */
     $quoteMock = $this->getMock('Magento\\Sales\\Model\\Quote', ['getCustomerId', '__wakeup', 'getBillingAddress', 'setPasswordHash', 'getCheckoutMethod', 'isVirtual', 'getShippingAddress', 'getCustomerData', 'collectTotals', 'save'], [], '', false);
     $shippingAddressMock = $this->getMock('Magento\\Sales\\Model\\Quote\\Address', ['setSameAsBilling', '__wakeup', 'unserialize'], [], '', false);
     $shippingAddressMock->expects($this->any())->method('setSameAsBilling')->with((int) $data['use_for_shipping']);
     $quoteMock->expects($this->any())->method('setPasswordHash')->with($passwordHash);
     $quoteMock->expects($this->any())->method('getCheckoutMethod')->will($this->returnValue($checkoutMethod));
     $quoteMock->expects($this->any())->method('isVirtual')->will($this->returnValue($isVirtual));
     $quoteMock->expects($this->any())->method('getShippingAddress')->will($this->returnValue($shippingAddressMock));
     $addressMock = $this->getMock('Magento\\Sales\\Model\\Quote\\Address', ['setSaveInAddressBook', 'getData', 'setEmail', '__wakeup', 'importCustomerAddressData', 'validate'], [], '', false);
     $addressMock->expects($this->any())->method('importCustomerAddressData')->will($this->returnSelf());
     $addressMock->expects($this->atLeastOnce())->method('validate')->will($this->returnValue($validateResult));
     $addressMock->expects($this->any())->method('getData')->will($this->returnValue([]));
     $quoteMock->expects($this->any())->method('getBillingAddress')->will($this->returnValue($addressMock));
     $quoteMock->expects($this->any())->method('getCustomerId')->will($this->returnValue($quoteCustomerId));
     $formMock = $this->getMock('Magento\\Customer\\Model\\Metadata\\Form', [], [], '', false);
     $formMock->expects($this->atLeastOnce())->method('validateData')->will($this->returnValue($validateDataResult));
     $this->requestMock->expects($this->any())->method('getParam')->will($this->returnValueMap([['customer_password', $customerPassword], ['confirm_password', $confirmPassword]]));
     $formMock->expects($this->any())->method('prepareRequest')->will($this->returnValue($this->requestMock));
     $this->customerFormFactoryMock->expects($this->any())->method('create')->will($this->returnValue($formMock));
     $customerDataMock = $this->getMock('Magento\\Customer\\Service\\V1\\Data\\Customer', [], [], '', false);
     $customerDataMock->expects($this->any())->method('__toArray')->will($this->returnValue([]));
     $this->customerBuilderMock->expects($this->any())->method('create')->will($this->returnValue($customerDataMock));
     $quoteMock->expects($this->atLeastOnce())->method('getCustomerData')->will($this->returnValue($customerDataMock));
     $this->checkoutSessionMock->expects($this->any())->method('getQuote')->will($this->returnValue($quoteMock));
     $this->checkoutSessionMock->expects($this->any())->method('getStepData')->will($this->returnValue((int) $data['use_for_shipping'] === 1 ? true : $getStepDataResult));
     $this->checkoutSessionMock->expects($this->any())->method('setStepData')->will($this->returnSelf());
     $customerAddressMock = $this->getMock('Magento\\Customer\\Service\\V1\\Data\\Address', [], [], '', false);
     $customerAddressMock->expects($this->any())->method('getCustomerId')->will($this->returnValue($addressCustomerId));
     $this->customerAddressServiceMock->expects($this->any())->method('getAddress')->will($isAddress ? $this->returnValue($customerAddressMock) : $this->throwException(new \Exception()));
     $this->customerBuilderMock->expects($checkoutMethod === Onepage::METHOD_REGISTER ? $this->never() : $this->once())->method('populate');
     $this->customerBuilderMock->expects($checkoutMethod === Onepage::METHOD_REGISTER ? $this->never() : $this->once())->method('setGroupId');
     $websiteMock = $this->getMock('Magento\\Store\\Model\\Website', [], [], '', false);
     $this->storeManagerMock->expects($this->any())->method('getWebsite')->will($this->returnValue($websiteMock));
     $this->assertEquals($expected, $this->onepage->saveBilling($data, $customerAddressId));
 }
 /**
  * @param $customerData
  * @param $isSingleStoreMode
  * @param $canModifyCustomer
  *
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 private function _setupStoreMode($customerData, $isSingleStoreMode, $canModifyCustomer)
 {
     $backendSessionMock = $this->getMock('\\Magento\\Backend\\Model\\Session', ['getCustomerData'], [], '', false);
     $backendSessionMock->expects($this->any())->method('getCustomerData')->will($this->returnValue([]));
     $layoutMock = $this->getMock('\\Magento\\Framework\\View\\Layout\\Element\\Layout', ['createBlock'], [], '', false);
     $layoutMock->expects($this->at(0))->method('createBlock')->with('Magento\\Customer\\Block\\Adminhtml\\Edit\\Renderer\\Attribute\\Group')->will($this->returnValue($this->objectManagerHelper->getObject('Magento\\Customer\\Block\\Adminhtml\\Edit\\Renderer\\Attribute\\Group')));
     $layoutMock->expects($this->at(1))->method('createBlock')->with('Magento\\Backend\\Block\\Store\\Switcher\\Form\\Renderer\\Fieldset\\Element')->will($this->returnValue($this->objectManagerHelper->getObject('Magento\\Backend\\Block\\Store\\Switcher\\Form\\Renderer\\Fieldset\\Element')));
     if (empty($customerData['id'])) {
         $layoutMock->expects($this->at(2))->method('createBlock')->with('Magento\\Customer\\Block\\Adminhtml\\Edit\\Renderer\\Attribute\\Sendemail')->will($this->returnValue($this->objectManagerHelper->getObject('Magento\\Customer\\Block\\Adminhtml\\Edit\\Renderer\\Attribute\\Sendemail')));
     }
     $urlBuilderMock = $this->getMock('\\Magento\\Backend\\Model\\Url', ['getBaseUrl'], [], '', false);
     $urlBuilderMock->expects($this->once())->method('getBaseUrl')->will($this->returnValue('someUrl'));
     $storeManagerMock = $this->getMock('Magento\\Store\\Model\\StoreManager', [], [], '', false);
     $storeManagerMock->expects($this->any())->method('isSingleStoreMode')->will($this->returnValue($isSingleStoreMode));
     $customerObject = $this->getMock('\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     if (!empty($customerData['id'])) {
         $customerObject->expects($this->any())->method('getId')->will($this->returnValue($customerData['id']));
     }
     $fieldset = $this->getMockBuilder('\\Magento\\Framework\\Data\\Form\\Element\\Fieldset')->setMethods(['getForm', 'addField', 'removeField'])->disableOriginalConstructor()->getMock();
     $accountForm = $this->getMockBuilder('Magento\\Framework\\Data\\Form')->setMethods(['create', 'addFieldset', 'getElement', 'setValues'])->disableOriginalConstructor()->getMock();
     $accountForm->expects($this->any())->method('addFieldset')->with('base_fieldset')->will($this->returnValue($fieldset));
     $accountForm->expects($this->any())->method('setValues')->will($this->returnValue($accountForm));
     $fieldset->expects($this->any())->method('getForm')->will($this->returnValue($accountForm));
     $formElement = $this->getMockBuilder('\\Magento\\Framework\\Data\\Form\\Element\\Select')->setMethods(['setRenderer', 'addClass', 'setDisabled'])->disableOriginalConstructor()->getMock();
     $formElement->expects($this->any())->method('setRenderer')->will($this->returnValue(null));
     $formElement->expects($this->any())->method('addClass')->will($this->returnValue(null));
     $formElement->expects($this->any())->method('setDisabled')->will($this->returnValue(null));
     $accountForm->expects($this->any())->method('getElement')->withAnyParameters()->will($this->returnValue($formElement));
     $fieldset->expects($this->any())->method('addField')->will($this->returnValue($formElement));
     $customerForm = $this->getMock('\\Magento\\Customer\\Model\\Metadata\\Form', ['getAttributes'], [], '', false);
     $customerForm->expects($this->any())->method('getAttributes')->will($this->returnValue([]));
     $this->contextMock->expects($this->any())->method('getBackendSession')->will($this->returnValue($backendSessionMock));
     $this->contextMock->expects($this->any())->method('getLayout')->will($this->returnValue($layoutMock));
     $this->contextMock->expects($this->any())->method('getUrlBuilder')->will($this->returnValue($urlBuilderMock));
     $this->contextMock->expects($this->any())->method('getStoreManager')->will($this->returnValue($storeManagerMock));
     $this->customerFactoryMock->expects($this->any())->method('create')->will($this->returnValue($customerObject));
     $this->dataObjectHelperMock->expects($this->once())->method('populateWithArray');
     $this->options->expects($this->any())->method('getNamePrefixOptions')->will($this->returnValue(['Pref1', 'Pref2']));
     $this->options->expects($this->any())->method('getNameSuffixOptions')->will($this->returnValue(['Suf1', 'Suf2']));
     $this->formFactoryMock->expects($this->any())->method('create')->will($this->returnValue($accountForm));
     $this->extensibleDataObjectConverterMock->expects($this->any())->method('toFlatArray')->will($this->returnValue($customerData));
     $this->customerFormFactoryMock->expects($this->any())->method('create')->with('customer', 'adminhtml_customer', $this->extensibleDataObjectConverterMock->toFlatArray($customerObject, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface'))->will($this->returnValue($customerForm));
     $this->accountManagementMock->expects($this->any())->method('isReadOnly')->withAnyParameters()->will($this->returnValue(!$canModifyCustomer));
     $this->accountManagementMock->expects($this->any())->method('getConfirmationStatus')->withAnyParameters()->will($this->returnValue(AccountManagementInterface::ACCOUNT_CONFIRMED));
 }
Beispiel #17
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());
 }
Beispiel #18
0
 /**
  * Get order data jason
  *
  * @return string
  */
 public function getOrderDataJson()
 {
     $data = array();
     if ($this->getCustomerId()) {
         $data['customer_id'] = $this->getCustomerId();
         $data['addresses'] = array();
         $addresses = $this->_addressService->getAddresses($this->getCustomerId());
         foreach ($addresses as $addressData) {
             $addressForm = $this->_customerFormFactory->create('customer_address', 'adminhtml_customer_address', AddressConverter::toFlatArray($addressData));
             $data['addresses'][$addressData->getId()] = $addressForm->outputData(\Magento\Eav\Model\AttributeDataFactory::OUTPUT_FORMAT_JSON);
         }
     }
     if (!is_null($this->getStoreId())) {
         $data['store_id'] = $this->getStoreId();
         $currency = $this->_localeCurrency->getCurrency($this->getStore()->getCurrentCurrencyCode());
         $symbol = $currency->getSymbol() ? $currency->getSymbol() : $currency->getShortName();
         $data['currency_symbol'] = $symbol;
         $data['shipping_method_reseted'] = !(bool) $this->getQuote()->getShippingAddress()->getShippingMethod();
         $data['payment_method'] = $this->getQuote()->getPayment()->getMethod();
     }
     return $this->_jsonEncoder->encode($data);
 }
Beispiel #19
0
 /**
  * Initialize form object
  *
  * @return $this
  *
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function initForm()
 {
     $customerData = $this->_backendSession->getCustomerData();
     /** @var \Magento\Framework\Data\Form $form */
     $form = $this->_formFactory->create();
     $fieldset = $form->addFieldset('address_fieldset', ['legend' => __("Edit Customer's Address")]);
     $account = $customerData['account'];
     $address = $this->addressDataFactory->create();
     if (!empty($account) && isset($account['store_id'])) {
         $address->setCountryId($this->_directoryHelper->getDefaultCountry($this->_storeManager->getStore($account['store_id'])));
     } else {
         $address->setCountryId($this->_directoryHelper->getDefaultCountry());
     }
     $addressForm = $this->_metadataFormFactory->create('customer_address', 'adminhtml_customer_address', $this->addressMapper->toFlatArray($address));
     $attributes = $addressForm->getAttributes();
     if (isset($attributes['street'])) {
         if ($attributes['street']->getMultilineCount() <= 0) {
             $attributes['street']->setMultilineCount(self::DEFAULT_STREET_LINES_COUNT);
         }
     }
     foreach ($attributes as $key => $attribute) {
         $attributes[$key]->setFrontendLabel(__($attribute->getFrontendLabel()))->setIsVisible(false);
     }
     $this->_setFieldset($attributes, $fieldset);
     $regionElement = $form->getElement('region');
     if ($regionElement) {
         $regionElement->setRenderer($this->_regionFactory->create());
     }
     $regionElement = $form->getElement('region_id');
     if ($regionElement) {
         $regionElement->setNoDisplay(true);
     }
     $country = $form->getElement('country_id');
     if ($country) {
         $country->addClass('countries');
     }
     $postcode = $form->getElement('postcode');
     if ($postcode) {
         $postcode->removeClass('required-entry')->setRequired(!$this->_directoryHelper->isZipCodeOptional($address->getCountryId()));
     }
     if ($this->isReadonly()) {
         foreach ($this->_addressMetadataService->getAllAttributesMetadata() as $attribute) {
             $element = $form->getElement($attribute->getAttributeCode());
             if ($element) {
                 $element->setReadonly(true, true);
             }
         }
     }
     $customerStoreId = null;
     if (!empty($account) && isset($account['id']) && isset($account['website_id'])) {
         $customerStoreId = $this->_storeManager->getWebsite($account['website_id'])->getDefaultStore()->getId();
     }
     $prefixElement = $form->getElement('prefix');
     if ($prefixElement) {
         $prefixOptions = $this->options->getNamePrefixOptions($customerStoreId);
         if (!empty($prefixOptions)) {
             $fieldset->removeField($prefixElement->getId());
             $prefixField = $fieldset->addField($prefixElement->getId(), 'select', $prefixElement->getData(), '^');
             $prefixField->setValues($prefixOptions);
         }
     }
     $suffixElement = $form->getElement('suffix');
     if ($suffixElement) {
         $suffixOptions = $this->options->getNameSuffixOptions($customerStoreId);
         if (!empty($suffixOptions)) {
             $fieldset->removeField($suffixElement->getId());
             $suffixField = $fieldset->addField($suffixElement->getId(), 'select', $suffixElement->getData(), $form->getElement('lastname')->getId());
             $suffixField->setValues($suffixOptions);
         }
     }
     $customerDataObject = $this->customerDataFactory->create();
     $this->dataObjectHelper->populateWithArray($customerDataObject, $account, '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     $this->assign('customer', $customerDataObject);
     $addressCollection = [];
     foreach ($customerData['address'] as $key => $addressData) {
         $addressDataObject = $this->addressDataFactory->create();
         $this->dataObjectHelper->populateWithArray($addressDataObject, $addressData, '\\Magento\\Customer\\Api\\Data\\AddressInterface');
         $addressCollection[$key] = $addressDataObject;
     }
     $this->assign('addressCollection', $addressCollection);
     $form->setValues($this->addressMapper->toFlatArray($address));
     $this->setForm($form);
     return $this;
 }
Beispiel #20
0
 /**
  * Save checkout shipping address
  *
  * @param   array $data
  * @param   int $customerAddressId
  * @return  array
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function saveShipping($data, $customerAddressId)
 {
     if (empty($data)) {
         return ['error' => -1, 'message' => __('Invalid data')];
     }
     $address = $this->getQuote()->getShippingAddress();
     $addressForm = $this->_formFactory->create('customer_address', 'customer_address_edit', [], $this->_request->isAjax(), Form::IGNORE_INVISIBLE, []);
     if (!empty($customerAddressId)) {
         $addressData = null;
         try {
             $addressData = $this->addressRepository->getById($customerAddressId);
         } catch (NoSuchEntityException $e) {
             // do nothing if customer is not found by id
         }
         if ($addressData->getCustomerId() != $this->getQuote()->getCustomerId()) {
             return ['error' => 1, 'message' => __('The customer address is not valid.')];
         }
         $address->importCustomerAddressData($addressData)->setSaveInAddressBook(0);
         $addressErrors = $addressForm->validateData($address->getData());
         if ($addressErrors !== true) {
             return ['error' => 1, 'message' => $addressErrors];
         }
     } else {
         // emulate request object
         $addressData = $addressForm->extractData($addressForm->prepareRequest($data));
         $addressErrors = $addressForm->validateData($addressData);
         if ($addressErrors !== true) {
             return ['error' => 1, 'message' => $addressErrors];
         }
         $compactedData = $addressForm->compactData($addressData);
         // unset shipping address attributes which were not shown in form
         foreach ($addressForm->getAttributes() as $attribute) {
             $attributeCode = $attribute->getAttributeCode();
             if (!isset($data[$attributeCode])) {
                 $address->setData($attributeCode, null);
             } else {
                 $address->setDataUsingMethod($attributeCode, $compactedData[$attributeCode]);
             }
         }
         $address->setCustomerAddressId(null);
         // Additional form data, not fetched by extractData (as it fetches only attributes)
         $address->setSaveInAddressBook(empty($data['save_in_address_book']) ? 0 : 1);
         $address->setSameAsBilling(empty($data['same_as_billing']) ? 0 : 1);
     }
     $address->setCollectShippingRates(true);
     if (($validateRes = $address->validate()) !== true) {
         return ['error' => 1, 'message' => $validateRes];
     }
     $address->collectTotals()->save();
     $this->getCheckout()->setStepData('shipping', 'complete', true)->setStepData('shipping_method', 'allow', true);
     return [];
 }
Beispiel #21
0
 /**
  * Set and validate Quote address
  * All errors added to _errors
  *
  * @param \Magento\Quote\Model\Quote\Address $address
  * @param array $data
  * @return $this
  */
 protected function _setQuoteAddress(\Magento\Quote\Model\Quote\Address $address, array $data)
 {
     $isAjax = !$this->getIsValidate();
     // Region is a Data Object, so it is represented by an array. validateData() doesn't understand arrays, so we
     // need to merge region data with address data. This is going to be removed when we switch to use address Data
     // Object instead of the address model.
     // Note: if we use getRegion() here it will pull region from db using the region_id
     $data = isset($data['region']) && is_array($data['region']) ? array_merge($data, $data['region']) : $data;
     $addressForm = $this->_metadataFormFactory->create(AddressMetadataInterface::ENTITY_TYPE_ADDRESS, 'adminhtml_customer_address', $data, $isAjax, CustomerForm::DONT_IGNORE_INVISIBLE, []);
     // prepare request
     // save original request structure for files
     if ($address->getAddressType() == \Magento\Quote\Model\Quote\Address::TYPE_SHIPPING) {
         $requestData = ['order' => ['shipping_address' => $data]];
         $requestScope = 'order/shipping_address';
     } else {
         $requestData = ['order' => ['billing_address' => $data]];
         $requestScope = 'order/billing_address';
     }
     $request = $addressForm->prepareRequest($requestData);
     $addressData = $addressForm->extractData($request, $requestScope);
     if ($this->getIsValidate()) {
         $errors = $addressForm->validateData($addressData);
         if ($errors !== true) {
             if ($address->getAddressType() == \Magento\Quote\Model\Quote\Address::TYPE_SHIPPING) {
                 $typeName = __('Shipping Address: ');
             } else {
                 $typeName = __('Billing Address: ');
             }
             foreach ($errors as $error) {
                 $this->_errors[] = $typeName . $error;
             }
             $address->setData($addressForm->restoreData($addressData));
         } else {
             $address->setData($addressForm->compactData($addressData));
         }
     } else {
         $address->addData($addressForm->restoreData($addressData));
     }
     return $this;
 }
Beispiel #22
0
 /**
  * Perform customer data filtration based on form code and form object
  *
  * @param \Magento\Framework\App\RequestInterface $request
  * @param string $formCode The code of EAV form to take the list of attributes from
  * @param string $entityType entity type for the form
  * @param string[] $additionalAttributes The list of attribute codes to skip filtration for
  * @param string $scope scope of the request
  * @param \Magento\Customer\Model\Metadata\Form $metadataForm to use for extraction
  * @return array Filtered customer data
  */
 public function extractCustomerData(\Magento\Framework\App\RequestInterface $request, $formCode, $entityType, $additionalAttributes = array(), $scope = null, \Magento\Customer\Model\Metadata\Form $metadataForm = null)
 {
     if (is_null($metadataForm)) {
         $metadataForm = $this->_formFactory->create($entityType, $formCode, array(), false, \Magento\Customer\Model\Metadata\Form::DONT_IGNORE_INVISIBLE);
     }
     $filteredData = $metadataForm->extractData($request, $scope);
     $requestData = $request->getPost($scope);
     foreach ($additionalAttributes as $attributeCode) {
         $filteredData[$attributeCode] = isset($requestData[$attributeCode]) ? $requestData[$attributeCode] : false;
     }
     $formAttributes = $metadataForm->getAttributes();
     /** @var \Magento\Customer\Service\V1\Data\Eav\AttributeMetadata $attribute */
     foreach ($formAttributes as $attribute) {
         $attributeCode = $attribute->getAttributeCode();
         $frontendInput = $attribute->getFrontendInput();
         if ($frontendInput != 'boolean' && $filteredData[$attributeCode] === false) {
             unset($filteredData[$attributeCode]);
         }
     }
     return $filteredData;
 }