Example #1
0
 public function testGetProductWeeeAttributes()
 {
     $customerAccountService = Bootstrap::getObjectManager()->create('Magento\\Customer\\Service\\V1\\CustomerAccountServiceInterface');
     $customerMetadataService = Bootstrap::getObjectManager()->create('Magento\\Customer\\Service\\V1\\CustomerMetadataService');
     $customerBuilder = Bootstrap::getObjectManager()->create('Magento\\Customer\\Service\\V1\\Data\\CustomerBuilder', ['metadataService' => $customerMetadataService]);
     $expected = \Magento\Framework\Service\ExtensibleDataObjectConverter::toFlatArray($customerAccountService->getCustomer(1));
     $customerBuilder->populateWithArray($expected);
     $customerDataSet = $customerBuilder->create();
     $fixtureGroupCode = 'custom_group';
     $fixtureTaxClassId = 3;
     /** @var \Magento\Customer\Model\Group $group */
     $group = Bootstrap::getObjectManager()->create('Magento\\Customer\\Model\\Group');
     $fixtureGroupId = $group->load($fixtureGroupCode, 'customer_group_code')->getId();
     /** @var \Magento\Sales\Model\Quote $quote */
     $quote = Bootstrap::getObjectManager()->create('Magento\\Sales\\Model\\Quote');
     $quote->setCustomerGroupId($fixtureGroupId);
     $quote->setCustomerTaxClassId($fixtureTaxClassId);
     $quote->setCustomerData($customerDataSet);
     $shipping = new \Magento\Framework\Object(['quote' => $quote]);
     $product = Bootstrap::getObjectManager()->create('Magento\\Catalog\\Model\\Product');
     $product->load(1);
     $weeeTax = Bootstrap::getObjectManager()->create('Magento\\Weee\\Model\\Tax');
     $weeeTaxData = array('website_id' => '1', 'entity_id' => '1', 'country' => 'US', 'value' => '12.4', 'state' => '0', 'attribute_id' => '75', 'entity_type_id' => '0');
     $weeeTax->setData($weeeTaxData);
     $weeeTax->save();
     $amount = $this->_model->getProductWeeeAttributes($product, $shipping);
     $this->assertEquals('12.4000', $amount[0]->getAmount());
 }
Example #2
0
 /**
  * Customer validation
  *
  * @param \Magento\Framework\Object $response
  * @return Customer|null
  */
 protected function _validateCustomer($response)
 {
     $customer = null;
     $errors = null;
     try {
         /** @var Customer $customer */
         $customer = $this->_customerBuilder->create();
         $customerForm = $this->_formFactory->create('customer', 'adminhtml_customer', \Magento\Framework\Service\ExtensibleDataObjectConverter::toFlatArray($customer), true);
         $customerForm->setInvisibleIgnored(true);
         $data = $customerForm->extractData($this->getRequest(), 'account');
         if ($customer->getWebsiteId()) {
             unset($data['website_id']);
         }
         $customer = $this->_customerBuilder->populateWithArray($data)->create();
         $errors = $this->_customerAccountService->validateCustomerData($customer);
     } catch (\Magento\Framework\Model\Exception $exception) {
         /* @var $error Error */
         foreach ($exception->getMessages(\Magento\Framework\Message\MessageInterface::TYPE_ERROR) as $error) {
             $errors[] = $error->getText();
         }
     }
     if (!$errors->isValid()) {
         foreach ($errors->getMessages() as $error) {
             $this->messageManager->addError($error);
         }
         $response->setError(1);
     }
     return $customer;
 }
 /**
  * @magentoDataFixture Magento/Customer/_files/customer.php
  */
 public function testGetCustomerAttributeMetadata()
 {
     // Expect these attributes to exist but do not check the value
     $expectAttrsWOutVals = array('created_at');
     // Expect these attributes to exist and check the value - values come from _files/customer.php
     $expectAttrsWithVals = array('id' => '1', 'website_id' => '1', 'store_id' => '1', 'group_id' => '1', 'firstname' => 'Firstname', 'lastname' => 'Lastname', 'email' => '*****@*****.**', 'default_billing' => '1', 'default_shipping' => '1', 'disable_auto_group_change' => '0');
     $customer = $this->_customerAccountService->getCustomer(1);
     $this->assertNotNull($customer);
     $attributes = \Magento\Framework\Service\ExtensibleDataObjectConverter::toFlatArray($customer);
     $this->assertNotEmpty($attributes);
     foreach ($attributes as $attributeCode => $attributeValue) {
         $this->assertNotNull($attributeCode);
         $this->assertNotNull($attributeValue);
         $attributeMetadata = $this->_service->getAttributeMetadata($attributeCode);
         $attrMetadataCode = $attributeMetadata->getAttributeCode();
         $this->assertSame($attributeCode, $attrMetadataCode);
         if (($key = array_search($attrMetadataCode, $expectAttrsWOutVals)) !== false) {
             unset($expectAttrsWOutVals[$key]);
         } else {
             $this->assertArrayHasKey($attrMetadataCode, $expectAttrsWithVals);
             $this->assertSame($expectAttrsWithVals[$attrMetadataCode], $attributeValue, "Failed for {$attrMetadataCode}");
             unset($expectAttrsWithVals[$attrMetadataCode]);
         }
     }
     $this->assertEmpty($expectAttrsWOutVals);
     $this->assertEmpty($expectAttrsWithVals);
 }
Example #4
0
 /**
  * Prepare the form.
  *
  * @return $this
  */
 protected function _prepareForm()
 {
     /** @var \Magento\Framework\Data\Form $form */
     $form = $this->_formFactory->create(array('data' => array('id' => 'edit_form', 'action' => $this->getUrl('customer/*/save'), 'method' => 'post', 'enctype' => 'multipart/form-data')));
     $customerId = $this->_coreRegistry->registry(RegistryConstants::CURRENT_CUSTOMER_ID);
     if ($customerId) {
         $form->addField('id', 'hidden', array('name' => 'customer_id'));
         $customer = $this->_customerAccountService->getCustomer($customerId);
         $form->setValues(\Magento\Framework\Service\ExtensibleDataObjectConverter::toFlatArray($customer))->addValues(array('customer_id' => $customerId));
     }
     $form->setUseContainer(true);
     $this->setForm($form);
     return parent::_prepareForm();
 }
Example #5
0
 /**
  * Convert keys to camelCase
  *
  * @param array $dataArray
  * @return \stdClass
  */
 public function convertKeysToCamelCase(array $dataArray)
 {
     $response = [];
     if (isset($dataArray[AbstractExtensibleObject::CUSTOM_ATTRIBUTES_KEY])) {
         $dataArray = ExtensibleDataObjectConverter::convertCustomAttributesToSequentialArray($dataArray);
     }
     foreach ($dataArray as $fieldName => $fieldValue) {
         if (is_array($fieldValue) && !$this->_isSimpleSequentialArray($fieldValue)) {
             $fieldValue = $this->convertKeysToCamelCase($fieldValue);
         }
         $fieldName = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $fieldName))));
         $response[$fieldName] = $fieldValue;
     }
     return $response;
 }
Example #6
0
 /**
  * @param  Product $product
  * @param  \Magento\Catalog\Model\Product $productModel
  * @return \Magento\Catalog\Model\Product
  * @throws \RuntimeException
  */
 public function toModel(Product $product, \Magento\Catalog\Model\Product $productModel = null)
 {
     /** @var \Magento\Catalog\Model\Product $productModel */
     $productModel = $productModel ?: $this->productFactory->create();
     $productModel->addData(ExtensibleDataObjectConverter::toFlatArray($product));
     if (!is_numeric($productModel->getAttributeSetId())) {
         $productModel->setAttributeSetId($productModel->getDefaultAttributeSetId());
     }
     if (!$productModel->hasTypeId()) {
         $productModel->setTypeId(\Magento\Catalog\Model\Product\Type::DEFAULT_TYPE);
     } elseif (!isset($this->productTypes->getTypes()[$productModel->getTypeId()])) {
         throw new \RuntimeException('Illegal product type');
     }
     return $productModel;
 }
Example #7
0
 /**
  * Convert address data object to a flat array
  *
  * @param Address $addressDataObject
  * @return array
  */
 public static function toFlatArray(Address $addressDataObject)
 {
     $flatAddressArray = ExtensibleDataObjectConverter::toFlatArray($addressDataObject);
     //preserve street
     $street = $addressDataObject->getStreet();
     if (!empty($street)) {
         // Unset flat street data
         $streetKeys = array_keys($street);
         foreach ($streetKeys as $key) {
             unset($flatAddressArray[$key]);
         }
         //Restore street as an array
         $flatAddressArray[Address::KEY_STREET] = $street;
     }
     return $flatAddressArray;
 }
Example #8
0
 /**
  * @param  CategoryDataObject $category
  * @param  \Magento\Catalog\Model\Category $categoryModel
  * @return \Magento\Catalog\Model\Category
  * @throws \RuntimeException
  */
 public function toModel(CategoryDataObject $category, \Magento\Catalog\Model\Category $categoryModel = null)
 {
     $categoryModel = $categoryModel ?: $this->categoryFactory->create();
     $data = ExtensibleDataObjectConverter::toFlatArray($category);
     /** @see /app/code/Magento/Catalog/Controller/Adminhtml/Category.php method "_filterCategoryPostData" */
     if (isset($data['image']) && is_array($data['image'])) {
         $data['image_additional_data'] = $data['image'];
         unset($data['image']);
     }
     // this fields should not be changed
     $data[CategoryDataObject::ID] = $categoryModel->getId();
     $data[CategoryDataObject::PARENT_ID] = $categoryModel->getParentId();
     $data[CategoryDataObject::PATH] = $categoryModel->getPath();
     /** fill required fields */
     $data['is_active'] = $category->isActive();
     $data['include_in_menu'] = isset($data['include_in_menu']) ? (bool) $data['include_in_menu'] : false;
     $categoryModel->addData($data);
     if (!is_numeric($categoryModel->getAttributeSetId())) {
         $categoryModel->setAttributeSetId($categoryModel->getDefaultAttributeSetId());
     }
     return $categoryModel;
 }
Example #9
0
 /**
  * Put existing customer data into the backend session
  */
 protected function setupExistingCustomerData()
 {
     /** @var Customer $customer */
     $customer = $this->_customerAccountService->getCustomer(1);
     $this->_customerData = array('customer_id' => $customer->getId(), 'account' => \Magento\Framework\Service\ExtensibleDataObjectConverter::toFlatArray($customer));
     $this->_customerData['account']['id'] = $customer->getId();
     /** @var Address[] $addresses */
     $addresses = $this->_addressService->getAddresses(1);
     foreach ($addresses as $addressData) {
         $this->_customerData['address'][$addressData->getId()] = AddressConverter::toFlatArray($addressData);
         $this->_customerData['address'][$addressData->getId()]['id'] = $addressData->getId();
     }
     $this->_backendSession->setCustomerData($this->_customerData);
 }
Example #10
0
 /**
  * Customer edit action
  *
  * @return void
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function execute()
 {
     $customerId = $this->_initCustomer();
     $this->_view->loadLayout();
     $this->_setActiveMenu('Magento_Customer::customer_manage');
     $customerData = array();
     $customerData['account'] = array();
     $customerData['address'] = array();
     $customer = null;
     $isExistingCustomer = (bool) $customerId;
     if ($isExistingCustomer) {
         try {
             $customer = $this->_customerAccountService->getCustomer($customerId);
             $customerData['account'] = ExtensibleDataObjectConverter::toFlatArray($customer);
             $customerData['account']['id'] = $customerId;
             try {
                 $addresses = $this->_addressService->getAddresses($customerId);
                 foreach ($addresses as $address) {
                     $customerData['address'][$address->getId()] = AddressConverter::toFlatArray($address);
                     $customerData['address'][$address->getId()]['id'] = $address->getId();
                 }
             } catch (NoSuchEntityException $e) {
                 //do nothing
             }
         } catch (NoSuchEntityException $e) {
             $this->messageManager->addException($e, __('An error occurred while editing the customer.'));
             $this->_redirect('customer/*/index');
             return;
         }
     }
     $customerData['customer_id'] = $customerId;
     // set entered data if was error when we do save
     $data = $this->_getSession()->getCustomerData(true);
     // restore data from SESSION
     if ($data && (!isset($data['customer_id']) || isset($data['customer_id']) && $data['customer_id'] == $customerId)) {
         $request = clone $this->getRequest();
         $request->setParams($data);
         if (isset($data['account']) && is_array($data['account'])) {
             $customerForm = $this->_formFactory->create('customer', 'adminhtml_customer', $customerData['account'], true);
             $formData = $customerForm->extractData($request, 'account');
             $customerData['account'] = $customerForm->restoreData($formData);
             $customer = $this->_customerBuilder->populateWithArray($customerData['account'])->create();
         }
         if (isset($data['address']) && is_array($data['address'])) {
             foreach (array_keys($data['address']) as $addressId) {
                 if ($addressId == '_template_') {
                     continue;
                 }
                 try {
                     $address = $this->_addressService->getAddress($addressId);
                     if (!empty($customerId) && $address->getCustomerId() == $customerId) {
                         $this->_addressBuilder->populate($address);
                     }
                 } catch (NoSuchEntityException $e) {
                     $this->_addressBuilder->setId($addressId);
                 }
                 if (!empty($customerId)) {
                     $this->_addressBuilder->setCustomerId($customerId);
                 }
                 $this->_addressBuilder->setDefaultBilling(!empty($data['account'][Customer::DEFAULT_BILLING]) && $data['account'][Customer::DEFAULT_BILLING] == $addressId);
                 $this->_addressBuilder->setDefaultShipping(!empty($data['account'][Customer::DEFAULT_SHIPPING]) && $data['account'][Customer::DEFAULT_SHIPPING] == $addressId);
                 $address = $this->_addressBuilder->create();
                 $requestScope = sprintf('address/%s', $addressId);
                 $addressForm = $this->_formFactory->create('customer_address', 'adminhtml_customer_address', AddressConverter::toFlatArray($address));
                 $formData = $addressForm->extractData($request, $requestScope);
                 $customerData['address'][$addressId] = $addressForm->restoreData($formData);
                 $customerData['address'][$addressId]['id'] = $addressId;
             }
         }
     }
     $this->_getSession()->setCustomerData($customerData);
     if ($isExistingCustomer) {
         $this->_title->add($this->_viewHelper->getCustomerName($customer));
     } else {
         $this->_title->add(__('New Customer'));
     }
     /**
      * Set active menu item
      */
     $this->_setActiveMenu('Magento_Customer::customer');
     $this->_view->renderLayout();
 }
Example #11
0
 /**
  * Save customer action
  *
  * @return void
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 public function execute()
 {
     $returnToEdit = false;
     $customerId = (int) $this->getRequest()->getPost('customer_id');
     $originalRequestData = $this->getRequest()->getPost();
     if ($originalRequestData) {
         try {
             // optional fields might be set in request for future processing by observers in other modules
             $customerData = $this->_extractCustomerData();
             $addressesData = $this->_extractCustomerAddressData();
             $request = $this->getRequest();
             $isExistingCustomer = (bool) $customerId;
             $customerBuilder = $this->_customerBuilder;
             if ($isExistingCustomer) {
                 $savedCustomerData = $this->_customerAccountService->getCustomer($customerId);
                 $customerData = array_merge(\Magento\Framework\Service\ExtensibleDataObjectConverter::toFlatArray($savedCustomerData), $customerData);
             }
             unset($customerData[Customer::DEFAULT_BILLING]);
             unset($customerData[Customer::DEFAULT_SHIPPING]);
             $customerBuilder->populateWithArray($customerData);
             $addresses = array();
             foreach ($addressesData as $addressData) {
                 $addresses[] = $this->_addressBuilder->populateWithArray($addressData)->create();
             }
             $this->_eventManager->dispatch('adminhtml_customer_prepare_save', array('customer' => $customerBuilder, 'request' => $request));
             $customer = $customerBuilder->create();
             // Save customer
             $customerDetails = $this->_customerDetailsBuilder->setCustomer($customer)->setAddresses($addresses)->create();
             if ($isExistingCustomer) {
                 $this->_customerAccountService->updateCustomer($customerDetails);
             } else {
                 $customer = $this->_customerAccountService->createCustomer($customerDetails);
                 $customerId = $customer->getId();
             }
             $isSubscribed = false;
             if ($this->_authorization->isAllowed(null)) {
                 $isSubscribed = $this->getRequest()->getPost('subscription') !== null;
             }
             if ($isSubscribed) {
                 $this->_subscriberFactory->create()->subscribeCustomerById($customerId);
             } else {
                 $this->_subscriberFactory->create()->unsubscribeCustomerById($customerId);
             }
             // After save
             $this->_eventManager->dispatch('adminhtml_customer_save_after', array('customer' => $customer, 'request' => $request));
             $this->_getSession()->unsCustomerData();
             // Done Saving customer, finish save action
             $this->_coreRegistry->register(RegistryConstants::CURRENT_CUSTOMER_ID, $customerId);
             $this->messageManager->addSuccess(__('You saved the customer.'));
             $returnToEdit = (bool) $this->getRequest()->getParam('back', false);
         } catch (\Magento\Framework\Validator\ValidatorException $exception) {
             $this->_addSessionErrorMessages($exception->getMessages());
             $this->_getSession()->setCustomerData($originalRequestData);
             $returnToEdit = true;
         } catch (\Magento\Framework\Model\Exception $exception) {
             $messages = $exception->getMessages(\Magento\Framework\Message\MessageInterface::TYPE_ERROR);
             if (!count($messages)) {
                 $messages = $exception->getMessage();
             }
             $this->_addSessionErrorMessages($messages);
             $this->_getSession()->setCustomerData($originalRequestData);
             $returnToEdit = true;
         } catch (LocalizedException $exception) {
             $this->_addSessionErrorMessages($exception->getMessage());
             $this->_getSession()->setCustomerData($originalRequestData);
             $returnToEdit = true;
         } catch (\Exception $exception) {
             $this->messageManager->addException($exception, __('An error occurred while saving the customer.'));
             $this->_getSession()->setCustomerData($originalRequestData);
             $returnToEdit = true;
         }
     }
     if ($returnToEdit) {
         if ($customerId) {
             $this->_redirect('customer/*/edit', array('id' => $customerId, '_current' => true));
         } else {
             $this->_redirect('customer/*/new', array('_current' => true));
         }
     } else {
         $this->_redirect('customer/index');
     }
 }
Example #12
0
 /**
  * Set customer data object
  *
  * @param CustomerDataObject $customerData
  * @return $this
  */
 public function setCustomerData(CustomerDataObject $customerData)
 {
     /* @TODO: remove model usage in favor of Data Object in scope of MAGETWO-19930 */
     $customer = $this->_customerFactory->create();
     $customer->setData(\Magento\Framework\Service\ExtensibleDataObjectConverter::toFlatArray($customerData));
     $customer->setId($customerData->getId());
     $this->setCustomer($customer);
     return $this;
 }
Example #13
0
 /**
  * Update customer model with the data from the data object
  *
  * @param Customer $customerModel
  * @param CustomerDataObject $customerData
  * @return void
  */
 public function updateCustomerModel(\Magento\Customer\Model\Customer $customerModel, CustomerDataObject $customerData)
 {
     $attributes = ExtensibleDataObjectConverter::toFlatArray($customerData);
     foreach ($attributes as $attributeCode => $attributeValue) {
         $customerModel->setDataUsingMethod($attributeCode, $attributeValue);
     }
     $customerId = $customerData->getId();
     if ($customerId) {
         $customerModel->setId($customerId);
     }
     // Need to use attribute set or future calls to customerModel::save can cause data loss
     if (!$customerModel->getAttributeSetId()) {
         $customerModel->setAttributeSetId(CustomerMetadataServiceInterface::ATTRIBUTE_SET_ID_CUSTOMER);
     }
 }
Example #14
0
 /**
  * {@inheritdoc}
  */
 public function validateCustomerData(Data\Customer $customer, array $attributes = [])
 {
     $customerErrors = $this->validator->validateData(\Magento\Framework\Service\ExtensibleDataObjectConverter::toFlatArray($customer), $attributes, 'customer');
     if ($customerErrors !== true) {
         return $this->customerValidationResultsBuilder->setIsValid(false)->setMessages($this->validator->getMessages())->create();
     }
     $customerModel = $this->converter->createCustomerModel($customer);
     $result = $customerModel->validate();
     if (true !== $result && is_array($result)) {
         return $this->customerValidationResultsBuilder->setIsValid(false)->setMessages($result)->create();
     }
     return $this->customerValidationResultsBuilder->setIsValid(true)->setMessages([])->create();
 }
Example #15
0
 /**
  * Prepare customer data for order creation.
  *
  * Create customer if not created using data from customer form.
  * Create customer billing/shipping address if necessary using data from customer address forms.
  * Set customer data to quote.
  *
  * @return $this
  */
 public function _prepareCustomer()
 {
     if ($this->getQuote()->getCustomerIsGuest()) {
         return $this;
     }
     /** @var $store \Magento\Store\Model\Store */
     $store = $this->getSession()->getStore();
     $customerDataObject = $this->getQuote()->getCustomerData();
     if ($customerDataObject->getId() && !$this->_customerIsInStore($store)) {
         /** Create a new customer record if it is not available in the specified store */
         $customerDataObject = $this->_customerBuilder->populate($customerDataObject)->setId(null)->setStoreId($store->getId())->setWebsiteId($store->getWebsiteId())->setCreatedAt(null)->create();
         $customerDataObject = $this->_validateCustomerData($customerDataObject);
     } else {
         if (!$customerDataObject->getId()) {
             /** Create new customer */
             $customerBillingAddressDataObject = $this->getBillingAddress()->exportCustomerAddressData();
             $customerDataObject = $this->_customerBuilder->populate($customerDataObject)->setSuffix($customerBillingAddressDataObject->getSuffix())->setFirstname($customerBillingAddressDataObject->getFirstname())->setLastname($customerBillingAddressDataObject->getLastname())->setMiddlename($customerBillingAddressDataObject->getMiddlename())->setPrefix($customerBillingAddressDataObject->getPrefix())->setStoreId($store->getId())->setEmail($this->_getNewCustomerEmail())->create();
             $customerDataObject = $this->_validateCustomerData($customerDataObject);
         }
     }
     if ($this->getBillingAddress()->getSaveInAddressBook()) {
         $this->_prepareCustomerAddress($customerDataObject, $this->getBillingAddress());
     }
     if (!$this->getQuote()->isVirtual() && $this->getShippingAddress()->getSaveInAddressBook()) {
         $this->_prepareCustomerAddress($customerDataObject, $this->getShippingAddress());
     }
     $this->getQuote()->updateCustomerData($customerDataObject);
     $customerData = \Magento\Framework\Service\ExtensibleDataObjectConverter::toFlatArray($customerDataObject);
     foreach ($this->_createCustomerForm($customerDataObject)->getUserAttributes() as $attribute) {
         if (isset($customerData[$attribute->getAttributeCode()])) {
             $quoteCode = sprintf('customer_%s', $attribute->getAttributeCode());
             $this->getQuote()->setData($quoteCode, $customerData[$attribute->getAttributeCode()]);
         }
     }
     return $this;
 }
Example #16
0
 public function testToFlatArray()
 {
     $customerData = array('email' => '*****@*****.**', 'firstname' => 'John', 'lastname' => 'Doe', 'unknown_key' => 'Golden Necklace', 'warehouse_zip' => '78777', 'warehouse_alternate' => '90051');
     $expectedCustomerData = array('email' => '*****@*****.**', 'firstname' => 'John', 'lastname' => 'Doe', 'warehouse_zip' => '78777', 'warehouse_alternate' => '90051');
     $customer = $this->_customerBuilder->populateWithArray($customerData)->create();
     $this->assertEquals($expectedCustomerData, \Magento\Framework\Service\ExtensibleDataObjectConverter::toFlatArray($customer));
 }
 /**
  * @magentoAppArea frontend
  * @magentoDataFixture Magento/Customer/_files/customer.php
  * @magentoDbIsolation enabled
  */
 public function testCreateNonexistingCustomer()
 {
     $existingCustId = 1;
     $existingCustomer = $this->_customerAccountService->getCustomer($existingCustId);
     $email = '*****@*****.**';
     $firstName = 'Firstsave';
     $lastName = 'Lastsave';
     $customerData = array_merge($existingCustomer->__toArray(), ['email' => $email, 'firstname' => $firstName, 'lastname' => $lastName, 'created_in' => 'Admin', 'id' => null]);
     $this->_customerBuilder->populateWithArray($customerData);
     $customerEntity = $this->_customerBuilder->create();
     $customerDetails = $this->_customerDetailsBuilder->setCustomer($customerEntity)->create();
     $customerAfter = $this->_customerAccountService->createCustomer($customerDetails, 'aPassword');
     $this->assertGreaterThan(0, $customerAfter->getId());
     $this->assertEquals($email, $customerAfter->getEmail());
     $this->assertEquals($firstName, $customerAfter->getFirstname());
     $this->assertEquals($lastName, $customerAfter->getLastname());
     $this->assertEquals('Admin', $customerAfter->getCreatedIn());
     $this->_customerAccountService->authenticate($customerAfter->getEmail(), 'aPassword', true);
     $attributesBefore = \Magento\Framework\Service\ExtensibleDataObjectConverter::toFlatArray($existingCustomer);
     $attributesAfter = \Magento\Framework\Service\ExtensibleDataObjectConverter::toFlatArray($customerAfter);
     // ignore 'updated_at'
     unset($attributesBefore['updated_at']);
     unset($attributesAfter['updated_at']);
     $inBeforeOnly = array_diff_assoc($attributesBefore, $attributesAfter);
     $inAfterOnly = array_diff_assoc($attributesAfter, $attributesBefore);
     $expectedInBefore = ['email', 'firstname', 'id', 'lastname'];
     sort($expectedInBefore);
     $actualInBeforeOnly = array_keys($inBeforeOnly);
     sort($actualInBeforeOnly);
     $this->assertEquals($expectedInBefore, $actualInBeforeOnly);
     $expectedInAfter = ['created_in', 'email', 'firstname', 'id', 'lastname'];
     sort($expectedInAfter);
     $actualInAfterOnly = array_keys($inAfterOnly);
     sort($actualInAfterOnly);
     $this->assertEquals($expectedInAfter, $actualInAfterOnly);
 }
Example #18
0
 /**
  * Return Form Elements values
  *
  * @return array
  */
 public function getFormValues()
 {
     try {
         $customer = $this->_customerAccountService->getCustomer($this->getCustomerId());
     } catch (\Exception $e) {
         /** If customer does not exist do nothing. */
     }
     $data = isset($customer) ? ExtensibleDataObjectConverter::toFlatArray($customer) : array();
     foreach ($this->getQuote()->getData() as $key => $value) {
         if (strpos($key, 'customer_') === 0) {
             $data[substr($key, 9)] = $value;
         }
     }
     if ($this->getQuote()->getCustomerEmail()) {
         $data['email'] = $this->getQuote()->getCustomerEmail();
     }
     return $data;
 }
 public function testGetCustomer()
 {
     $attributeModelMock = $this->getMockBuilder('\\Magento\\Customer\\Model\\Attribute')->disableOriginalConstructor()->getMock();
     $this->_customerModelMock->expects($this->any())->method('load')->will($this->returnValue($this->_customerModelMock));
     $this->_mockReturnValue($this->_customerModelMock, array('getId' => self::ID, 'getFirstname' => self::FIRSTNAME, 'getLastname' => self::LASTNAME, 'getName' => self::NAME, 'getEmail' => self::EMAIL, 'getAttributes' => array($attributeModelMock)));
     $attributeModelMock->expects($this->any())->method('getAttributeCode')->will($this->returnValue('attribute_code'));
     $this->_customerModelMock->expects($this->any())->method('getData')->with($this->equalTo('attribute_code'))->will($this->returnValue('ATTRIBUTE_VALUE'));
     $this->_customerFactoryMock->expects($this->any())->method('create')->will($this->returnValue($this->_customerModelMock));
     $customerService = $this->_createService();
     $actualCustomer = $customerService->getCustomer(self::ID);
     $this->assertEquals(self::ID, $actualCustomer->getId(), 'customer id does not match');
     $this->assertEquals(self::FIRSTNAME, $actualCustomer->getFirstName());
     $this->assertEquals(self::LASTNAME, $actualCustomer->getLastName());
     $this->assertEquals(self::EMAIL, $actualCustomer->getEmail());
     $this->assertEquals(4, count(ExtensibleDataObjectConverter::toFlatArray($actualCustomer)));
 }
 /**
  * Convert data object to array and process available custom attributes
  *
  * @param array $dataObjectArray
  * @return array
  */
 protected function processDataObject($dataObjectArray)
 {
     if (isset($dataObjectArray[AbstractExtensibleObject::CUSTOM_ATTRIBUTES_KEY])) {
         $dataObjectArray = ExtensibleDataObjectConverter::convertCustomAttributesToSequentialArray($dataObjectArray);
     }
     //Check for nested custom_attributes
     foreach ($dataObjectArray as $key => $value) {
         if (is_array($value)) {
             $dataObjectArray[$key] = $this->processDataObject($value);
         }
     }
     return $dataObjectArray;
 }
Example #21
0
 /**
  * Validate customer data and set some its data for further usage in quote
  *
  * Will return either true or array with error messages
  *
  * @param array $data
  * @return bool|array
  */
 protected function _validateCustomerData(array $data)
 {
     $quote = $this->getQuote();
     $isCustomerNew = !$quote->getCustomerId();
     $customer = $quote->getCustomerData();
     $customerData = \Magento\Framework\Service\ExtensibleDataObjectConverter::toFlatArray($customer);
     /** @var Form $customerForm */
     $customerForm = $this->_formFactory->create(CustomerMetadata::ENTITY_TYPE_CUSTOMER, 'checkout_register', $customerData, $this->_request->isAjax(), Form::IGNORE_INVISIBLE, array());
     if ($isCustomerNew) {
         $customerRequest = $customerForm->prepareRequest($data);
         $customerData = $customerForm->extractData($customerRequest);
     }
     $customerErrors = $customerForm->validateData($customerData);
     if ($customerErrors !== true) {
         return array('error' => -1, 'message' => implode(', ', $customerErrors));
     }
     if (!$isCustomerNew) {
         return true;
     }
     $this->_customerBuilder->populateWithArray($customerData);
     $customer = $this->_customerBuilder->create();
     if ($quote->getCheckoutMethod() == self::METHOD_REGISTER) {
         // We always have $customerRequest here, otherwise we would have been kicked off the function several
         // lines above
         $password = $customerRequest->getParam('customer_password');
         if ($password != $customerRequest->getParam('confirm_password')) {
             return ['error' => -1, 'message' => __('Password and password confirmation are not equal.')];
         }
         $quote->setPasswordHash($this->_customerAccountService->getPasswordHash($password));
     } else {
         // set NOT LOGGED IN group id explicitly,
         // otherwise copyFieldsetToTarget('customer_account', 'to_quote') will fill it with default group id value
         $this->_customerBuilder->populate($customer);
         $this->_customerBuilder->setGroupId(CustomerGroupServiceInterface::NOT_LOGGED_IN_ID);
         $customer = $this->_customerBuilder->create();
     }
     //validate customer
     $attributes = $customerForm->getAllowedAttributes();
     $result = $this->_customerAccountService->validateCustomerData($customer, $attributes);
     if (!$result->isValid()) {
         return ['error' => -1, 'message' => implode(', ', $result->getMessages())];
     }
     // copy customer/guest email to address
     $quote->getBillingAddress()->setEmail($customer->getEmail());
     // copy customer data to quote
     $this->_objectCopyService->copyFieldsetToTarget('customer_account', 'to_quote', \Magento\Framework\Service\ExtensibleDataObjectConverter::toFlatArray($customer), $quote);
     return true;
 }