/**
  * @magentoDataFixture Magento/Customer/_files/customer.php
  */
 public function testGetCustomerAttributeMetadata()
 {
     // Expect these attributes to exist but do not check the value
     $expectAttrsWOutVals = ['created_at', 'updated_at'];
     // Expect these attributes to exist and check the value - values come from _files/customer.php
     $expectAttrsWithVals = ['id' => 1, 'website_id' => 1, 'store_id' => 1, 'group_id' => 1, 'prefix' => 'Mr.', 'firstname' => 'John', 'middlename' => 'A', 'lastname' => 'Smith', 'suffix' => 'Esq.', 'email' => '*****@*****.**', 'default_billing' => '1', 'default_shipping' => '1', 'disable_auto_group_change' => 0, 'taxvat' => '12', 'gender' => 0];
     $customer = $this->customerRepository->getById(1);
     $this->assertNotNull($customer);
     $attributes = $this->_extensibleDataObjectConverter->toFlatArray($customer, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     $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);
 }
Beispiel #2
0
 public function testGetProductWeeeAttributes()
 {
     /** @var \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository */
     $customerRepository = Bootstrap::getObjectManager()->create('Magento\\Customer\\Api\\CustomerRepositoryInterface');
     $customerMetadataService = Bootstrap::getObjectManager()->create('Magento\\Customer\\Api\\CustomerMetadataInterface');
     $customerFactory = Bootstrap::getObjectManager()->create('Magento\\Customer\\Api\\Data\\CustomerInterfaceFactory', ['metadataService' => $customerMetadataService]);
     $dataObjectHelper = Bootstrap::getObjectManager()->create('Magento\\Framework\\Api\\DataObjectHelper');
     $expected = $this->_extensibleDataObjectConverter->toFlatArray($customerRepository->getById(1), [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     $customerDataSet = $customerFactory->create();
     $dataObjectHelper->populateWithArray($customerDataSet, $expected, '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     $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\Quote\Model\Quote $quote */
     $quote = Bootstrap::getObjectManager()->create('Magento\\Quote\\Model\\Quote');
     $quote->setCustomerGroupId($fixtureGroupId);
     $quote->setCustomerTaxClassId($fixtureTaxClassId);
     $quote->setCustomer($customerDataSet);
     $shipping = new \Magento\Framework\DataObject(['quote' => $quote]);
     $productRepository = Bootstrap::getObjectManager()->create('Magento\\Catalog\\Api\\ProductRepositoryInterface');
     $product = $productRepository->get('simple-with-ftp');
     $amount = $this->_model->getProductWeeeAttributes($product, $shipping, null, null, true);
     $this->assertTrue(is_array($amount));
     $this->assertArrayHasKey(0, $amount);
     $this->assertEquals(12.7, $amount[0]->getAmount());
 }
Beispiel #3
0
 public function testGetProductWeeeAttributes()
 {
     /** @var \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository */
     $customerRepository = Bootstrap::getObjectManager()->create('Magento\\Customer\\Api\\CustomerRepositoryInterface');
     $customerMetadataService = Bootstrap::getObjectManager()->create('Magento\\Customer\\Api\\CustomerMetadataInterface');
     $customerFactory = Bootstrap::getObjectManager()->create('Magento\\Customer\\Api\\Data\\CustomerInterfaceFactory', ['metadataService' => $customerMetadataService]);
     $dataObjectHelper = Bootstrap::getObjectManager()->create('Magento\\Framework\\Api\\DataObjectHelper');
     $expected = $this->_extensibleDataObjectConverter->toFlatArray($customerRepository->getById(1), [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     $customerDataSet = $customerFactory->create();
     $dataObjectHelper->populateWithArray($customerDataSet, $expected, '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     $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\Quote\Model\Quote $quote */
     $quote = Bootstrap::getObjectManager()->create('Magento\\Quote\\Model\\Quote');
     $quote->setCustomerGroupId($fixtureGroupId);
     $quote->setCustomerTaxClassId($fixtureTaxClassId);
     $quote->setCustomer($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 = ['website_id' => '1', 'entity_id' => '1', 'country' => 'US', 'value' => '12.4', 'state' => '0', 'attribute_id' => '73', 'entity_type_id' => '0'];
     $weeeTax->setData($weeeTaxData);
     $weeeTax->save();
     $amount = $this->_model->getProductWeeeAttributes($product, $shipping);
     $this->assertEquals('12.4000', $amount[0]->getAmount());
 }
 /**
  * Test toNestedArray() method with custom attributes and with skipped custom attribute.
  */
 public function testToNestedArrayCustom()
 {
     $dataArray = ['attribute_key' => 'attribute_value', AbstractExtensibleObject::CUSTOM_ATTRIBUTES_KEY => [[AttributeValue::ATTRIBUTE_CODE => 'custom_attribute_code', AttributeValue::VALUE => 'custom_attribute_value'], [AttributeValue::ATTRIBUTE_CODE => 'custom_attribute_code_multi', AttributeValue::VALUE => ['custom_attribute_value_multi_1', 'custom_attribute_value_multi_2']], [AttributeValue::ATTRIBUTE_CODE => 'custom_attribute_code_skip', AttributeValue::VALUE => 'custom_attribute_value_skip']]];
     $resultArray = ['attribute_key' => 'attribute_value', 'custom_attribute_code' => 'custom_attribute_value', 'custom_attribute_code_multi' => ['custom_attribute_value_multi_1', 'custom_attribute_value_multi_2']];
     $this->processor->expects($this->any())->method('buildOutputDataArray')->with($this->dataObject)->willReturn($dataArray);
     $this->assertEquals($resultArray, $this->converter->toNestedArray($this->dataObject, ['custom_attribute_code_skip']));
 }
 public function testToFlatArray()
 {
     $expectedResultWithoutStreet = ['id' => 1, 'default_shipping' => false, 'default_billing' => true, 'firstname' => 'John', 'lastname' => 'Doe', 'city' => 'Austin', 'country_id' => 'US', 'region_id' => 1, 'region' => 'Texas', 'region_code' => 'TX'];
     $expectedResultWithStreet = array_merge($expectedResultWithoutStreet, ['street' => ['7700 W Parmer Ln', 'Austin, TX']]);
     $this->extensibleObjectConverter->expects($this->once())->method('toFlatArray')->willReturn($expectedResultWithoutStreet);
     $addressData = $this->createAddressMock();
     $result = $this->addressMapper->toFlatArray($addressData);
     $this->assertEquals($expectedResultWithStreet, $result);
 }
Beispiel #6
0
 /**
  * Prepare the form.
  *
  * @return $this
  */
 protected function _prepareForm()
 {
     /** @var \Magento\Framework\Data\Form $form */
     $form = $this->_formFactory->create(['data' => ['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', ['name' => 'customer_id']);
         $customer = $this->_customerRepository->getById($customerId);
         $form->setValues($this->_extensibleDataObjectConverter->toFlatArray($customer, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface'))->addValues(['customer_id' => $customerId]);
     }
     $form->setUseContainer(true);
     $this->setForm($form);
     return parent::_prepareForm();
 }
 /**
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 protected function setUp()
 {
     $this->addressRepositoryMock = $this->getMockForAbstractClass('Magento\\Customer\\Api\\AddressRepositoryInterface', ['get'], '', false);
     $this->accountManagementMock = $this->getMockForAbstractClass('Magento\\Customer\\Api\\AccountManagementInterface', [], '', false);
     $this->eventManagerMock = $this->getMock('Magento\\Framework\\Event\\ManagerInterface');
     $this->checkoutHelperMock = $this->getMock('Magento\\Checkout\\Helper\\Data', [], [], '', false);
     $this->customerUrlMock = $this->getMock('Magento\\Customer\\Model\\Url', [], [], '', false);
     $this->loggerMock = $this->getMock('Psr\\Log\\LoggerInterface');
     $this->checkoutSessionMock = $this->getMock('Magento\\Checkout\\Model\\Session', ['getLastOrderId', 'getQuote', 'setStepData', 'getStepData'], [], '', false);
     $this->customerSessionMock = $this->getMock('Magento\\Customer\\Model\\Session', ['getCustomerDataObject', 'isLoggedIn'], [], '', false);
     $this->storeManagerMock = $this->getMock('Magento\\Store\\Model\\StoreManagerInterface');
     $this->requestMock = $this->getMockBuilder('Magento\\Framework\\App\\Request\\Http')->disableOriginalConstructor()->getMock();
     $this->addressFactoryMock = $this->getMock('Magento\\Customer\\Model\\AddressFactory', [], [], '', false);
     $this->formFactoryMock = $this->getMock('Magento\\Customer\\Model\\Metadata\\FormFactory', [], [], '', false);
     $this->customerFactoryMock = $this->getMock('Magento\\Customer\\Model\\CustomerFactory', [], [], '', false);
     $this->quoteManagementMock = $this->getMock('Magento\\Quote\\Model\\QuoteManagement', [], [], '', false);
     $this->orderFactoryMock = $this->getMock('Magento\\Sales\\Model\\OrderFactory', ['create'], [], '', false);
     $this->copyMock = $this->getMock('Magento\\Framework\\Object\\Copy', [], [], '', false);
     $this->messageManagerMock = $this->getMock('Magento\\Framework\\Message\\ManagerInterface');
     $this->customerFormFactoryMock = $this->getMock('Magento\\Customer\\Model\\FormFactory', ['create'], [], '', false);
     $this->customerDataFactoryMock = $this->getMock('Magento\\Customer\\Api\\Data\\CustomerInterfaceFactory', [], [], '', false);
     $this->randomMock = $this->getMock('Magento\\Framework\\Math\\Random');
     $this->encryptorMock = $this->getMock('Magento\\Framework\\Encryption\\EncryptorInterface');
     $this->customerRepositoryMock = $this->getMockForAbstractClass('\\Magento\\Customer\\Api\\CustomerRepositoryInterface', [], '', false);
     $orderSenderMock = $this->getMock('\\Magento\\Sales\\Model\\Order\\Email\\Sender\\OrderSender', [], [], '', false);
     $this->quoteRepositoryMock = $this->getMock('Magento\\Quote\\Model\\QuoteRepository', [], [], '', false);
     $this->extensibleDataObjectConverterMock = $this->getMockBuilder('Magento\\Framework\\Api\\ExtensibleDataObjectConverter')->setMethods(['toFlatArray'])->disableOriginalConstructor()->getMock();
     $this->extensibleDataObjectConverterMock->expects($this->any())->method('toFlatArray')->will($this->returnValue([]));
     $this->objectManagerHelper = new ObjectManagerHelper($this);
     $this->onepage = $this->objectManagerHelper->getObject('Magento\\Checkout\\Model\\Type\\Onepage', ['eventManager' => $this->eventManagerMock, 'helper' => $this->checkoutHelperMock, 'customerUrl' => $this->customerUrlMock, 'logger' => $this->loggerMock, 'checkoutSession' => $this->checkoutSessionMock, 'customerSession' => $this->customerSessionMock, 'storeManager' => $this->storeManagerMock, 'request' => $this->requestMock, 'customrAddrFactory' => $this->addressFactoryMock, 'customerFormFactory' => $this->customerFormFactoryMock, 'customerFactory' => $this->customerFactoryMock, 'orderFactory' => $this->orderFactoryMock, 'objectCopyService' => $this->copyMock, 'messageManager' => $this->messageManagerMock, 'formFactory' => $this->formFactoryMock, 'customerDataFactory' => $this->customerDataFactoryMock, 'mathRandom' => $this->randomMock, 'encryptor' => $this->encryptorMock, 'addressRepository' => $this->addressRepositoryMock, 'accountManagement' => $this->accountManagementMock, 'orderSenderMock' => $orderSenderMock, 'customerRepository' => $this->customerRepositoryMock, 'extensibleDataObjectConverter' => $this->extensibleDataObjectConverterMock, 'quoteRepository' => $this->quoteRepositoryMock, 'quoteManagement' => $this->quoteManagementMock]);
 }
Beispiel #8
0
 /**
  * Convert address data object to a flat array
  *
  * @param AddressInterface $addressDataObject
  * @return array
  * TODO:: Add concrete type of AddressInterface for $addressDataObject parameter once
  * all references have been refactored.
  */
 public function toFlatArray($addressDataObject)
 {
     $flatAddressArray = $this->extensibleDataObjectConverter->toFlatArray($addressDataObject, [], '\\Magento\\Customer\\Api\\Data\\AddressInterface');
     //preserve street
     $street = $addressDataObject->getStreet();
     if (!empty($street) && is_array($street)) {
         // Unset flat street data
         $streetKeys = array_keys($street);
         foreach ($streetKeys as $key) {
             unset($flatAddressArray[$key]);
         }
         //Restore street as an array
         $flatAddressArray[AddressInterface::STREET] = $street;
     }
     return $flatAddressArray;
 }
 /**
  * {@inheritdoc}
  */
 public function save(\Magento\Catalog\Api\Data\ProductInterface $product, $saveOptions = false)
 {
     if ($saveOptions) {
         $productOptions = $product->getProductOptions();
     }
     $groupPrices = $product->getData('group_price');
     $tierPrices = $product->getData('tier_price');
     $productId = $this->resourceModel->getIdBySku($product->getSku());
     $productDataArray = $this->extensibleDataObjectConverter->toNestedArray($product, [], 'Magento\\Catalog\\Api\\Data\\ProductInterface');
     $product = $this->initializeProductData($productDataArray, empty($productId));
     $validationResult = $this->resourceModel->validate($product);
     if (true !== $validationResult) {
         throw new \Magento\Framework\Exception\CouldNotSaveException(__('Invalid product data: %1', implode(',', $validationResult)));
     }
     try {
         if ($saveOptions) {
             $product->setProductOptions($productOptions);
             $product->setCanSaveCustomOptions(true);
         }
         $product->setData('group_price', $groupPrices);
         $product->setData('tier_price', $tierPrices);
         $this->resourceModel->save($product);
     } catch (\Magento\Eav\Model\Entity\Attribute\Exception $exception) {
         throw \Magento\Framework\Exception\InputException::invalidFieldValue($exception->getAttributeCode(), $product->getData($exception->getAttributeCode()), $exception);
     } catch (\Exception $e) {
         throw new \Magento\Framework\Exception\CouldNotSaveException(__('Unable to save product'));
     }
     unset($this->instances[$product->getSku()]);
     unset($this->instancesById[$product->getId()]);
     return $product;
 }
 /**
  * @magentoAppArea frontend
  * @magentoDataFixture Magento/Customer/_files/customer.php
  * @magentoDbIsolation enabled
  */
 public function testCreateNonexistingCustomer()
 {
     $existingCustId = 1;
     $existingCustomer = $this->customerRepository->getById($existingCustId);
     $email = '*****@*****.**';
     $firstName = 'Firstsave';
     $lastName = 'Lastsave';
     $customerData = array_merge($existingCustomer->__toArray(), ['email' => $email, 'firstname' => $firstName, 'lastname' => $lastName, 'id' => null]);
     $customerEntity = $this->customerFactory->create();
     $this->dataObjectHelper->populateWithArray($customerEntity, $customerData, '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     $customerAfter = $this->accountManagement->createAccount($customerEntity, 'aPassword');
     $this->assertGreaterThan(0, $customerAfter->getId());
     $this->assertEquals($email, $customerAfter->getEmail());
     $this->assertEquals($firstName, $customerAfter->getFirstname());
     $this->assertEquals($lastName, $customerAfter->getLastname());
     $this->accountManagement->authenticate($customerAfter->getEmail(), 'aPassword');
     $attributesBefore = $this->extensibleDataObjectConverter->toFlatArray($existingCustomer, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     $attributesAfter = $this->extensibleDataObjectConverter->toFlatArray($customerAfter, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     // 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);
 }
Beispiel #11
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;
 }
 /**
  * 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;
 }
 /**
  * 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;
 }
 /**
  * {@inheritdoc}
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function save(\Magento\Catalog\Api\Data\ProductInterface $product, $saveOptions = false)
 {
     if ($saveOptions) {
         $productOptions = $product->getProductOptions();
     }
     $isDeleteOptions = $product->getIsDeleteOptions();
     $tierPrices = $product->getData('tier_price');
     $productId = $this->resourceModel->getIdBySku($product->getSku());
     $ignoreLinksFlag = $product->getData('ignore_links_flag');
     $productDataArray = $this->extensibleDataObjectConverter->toNestedArray($product, [], 'Magento\\Catalog\\Api\\Data\\ProductInterface');
     $productLinks = null;
     if (!$ignoreLinksFlag && $ignoreLinksFlag !== null) {
         $productLinks = $product->getProductLinks();
     }
     $productDataArray['store_id'] = (int) $this->storeManager->getStore()->getId();
     $product = $this->initializeProductData($productDataArray, empty($productId));
     if (isset($productDataArray['options'])) {
         if (!empty($productDataArray['options']) || $isDeleteOptions) {
             $this->processOptions($product, $productDataArray['options']);
             $product->setCanSaveCustomOptions(true);
         }
     }
     $this->processLinks($product, $productLinks);
     if (isset($productDataArray['media_gallery_entries'])) {
         $this->processMediaGallery($product, $productDataArray['media_gallery_entries']);
     }
     $validationResult = $this->resourceModel->validate($product);
     if (true !== $validationResult) {
         throw new \Magento\Framework\Exception\CouldNotSaveException(__('Invalid product data: %1', implode(',', $validationResult)));
     }
     try {
         if ($saveOptions) {
             $product->setProductOptions($productOptions);
             $product->setCanSaveCustomOptions(true);
         }
         if ($tierPrices !== null) {
             $product->setData('tier_price', $tierPrices);
         }
         $this->resourceModel->save($product);
     } catch (\Magento\Eav\Model\Entity\Attribute\Exception $exception) {
         throw \Magento\Framework\Exception\InputException::invalidFieldValue($exception->getAttributeCode(), $product->getData($exception->getAttributeCode()), $exception);
     } catch (\Exception $e) {
         throw new \Magento\Framework\Exception\CouldNotSaveException(__('Unable to save product'));
     }
     unset($this->instances[$product->getSku()]);
     unset($this->instancesById[$product->getId()]);
     return $this->get($product->getSku());
 }
 public function testExecuteWithException()
 {
     $this->request->expects($this->once())->method('getPost')->willReturn(null);
     $this->form->expects($this->once())->method('setInvisibleIgnored');
     $this->form->expects($this->atLeastOnce())->method('extractData')->willReturn([]);
     $this->form->expects($this->never())->method('validateData');
     $this->extensibleDataObjectConverter->expects($this->once())->method('toFlatArray')->willReturn([]);
     $validationResult = $this->getMockForAbstractClass('Magento\\Customer\\Api\\Data\\ValidationResultsInterface', [], '', false, true, true);
     $error = $this->getMock('Magento\\Framework\\Message\\Error', [], [], '', false);
     $error->expects($this->once())->method('getText')->willReturn('Error text');
     $exception = $this->getMock('Magento\\Framework\\Validator\\Exception', [], [], '', false);
     $exception->expects($this->once())->method('getMessages')->willReturn([$error]);
     $validationResult->expects($this->once())->method('getMessages')->willThrowException($exception);
     $this->customerAccountManagement->expects($this->once())->method('validate')->willReturn($validationResult);
     $this->controller->execute();
 }
 /**
  * @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
 /**
  * Return Form Elements values
  *
  * @return array
  */
 public function getFormValues()
 {
     try {
         $customer = $this->customerRepository->getById($this->getCustomerId());
     } catch (\Exception $e) {
         /** If customer does not exist do nothing. */
     }
     $data = isset($customer) ? $this->_extensibleDataObjectConverter->toFlatArray($customer, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface') : [];
     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;
 }
 /**
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function testSaveWithPasswordHash()
 {
     $customerId = 1;
     $storeId = 2;
     $passwordHash = 'ukfa4sdfa56s5df02asdf4rt';
     $this->prepareMocksForValidation(true);
     $region = $this->getMockForAbstractClass('Magento\\Customer\\Api\\Data\\RegionInterface', [], '', false);
     $address = $this->getMockForAbstractClass('Magento\\Customer\\Api\\Data\\AddressInterface', [], '', false, false, true, ['setCustomerId', 'setRegion', 'getRegion', 'getId']);
     $address2 = $this->getMockForAbstractClass('Magento\\Customer\\Api\\Data\\AddressInterface', [], '', false, false, true, ['setCustomerId', 'setRegion', 'getRegion', 'getId']);
     $customerModel = $this->getMock('Magento\\Customer\\Model\\Customer', ['getId', 'setId', 'setStoreId', 'getStoreId', 'getAttributeSetId', 'setAttributeSetId', 'setRpToken', 'setRpTokenCreatedAt', 'getDataModel', 'setPasswordHash'], [], '', false);
     $customerAttributesMetaData = $this->getMockForAbstractClass('Magento\\Framework\\Api\\CustomAttributesDataInterface', [], '', false, false, true, ['getId', 'getEmail', 'getWebsiteId', 'getAddresses', 'setAddresses']);
     $this->customer->expects($this->atLeastOnce())->method('getId')->willReturn($customerId);
     $this->customerRegistry->expects($this->atLeastOnce())->method('retrieve')->with($customerId)->willReturn($customerModel);
     $customerModel->expects($this->atLeastOnce())->method('getDataModel')->willReturn($this->customer);
     $this->imageProcessor->expects($this->once())->method('save')->with($this->customer, CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER, $this->customer)->willReturn($customerAttributesMetaData);
     $address->expects($this->once())->method('setCustomerId')->with($customerId)->willReturnSelf();
     $address->expects($this->once())->method('getRegion')->willReturn($region);
     $address->expects($this->atLeastOnce())->method('getId')->willReturn(7);
     $address->expects($this->once())->method('setRegion')->with($region);
     $customerAttributesMetaData->expects($this->any())->method('getAddresses')->willReturn([$address]);
     $customerAttributesMetaData->expects($this->at(1))->method('setAddresses')->with([]);
     $customerAttributesMetaData->expects($this->at(2))->method('setAddresses')->with([$address]);
     $this->extensibleDataObjectConverter->expects($this->once())->method('toNestedArray')->with($customerAttributesMetaData, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface')->willReturn(['customerData']);
     $this->customerFactory->expects($this->once())->method('create')->with(['data' => ['customerData']])->willReturn($customerModel);
     $customerModel->expects($this->once())->method('getStoreId')->willReturn(null);
     $store = $this->getMock('Magento\\Store\\Model\\Store', [], [], '', false);
     $store->expects($this->once())->method('getId')->willReturn($storeId);
     $this->storeManager->expects($this->once())->method('getStore')->willReturn($store);
     $customerModel->expects($this->once())->method('setStoreId')->with($storeId);
     $customerModel->expects($this->once())->method('setId')->with(null);
     $customerModel->expects($this->once())->method('getAttributeSetId')->willReturn(null);
     $customerModel->expects($this->once())->method('setAttributeSetId')->with(\Magento\Customer\Api\CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER);
     $customerModel->expects($this->once())->method('setPasswordHash')->with($passwordHash);
     $customerModel->expects($this->atLeastOnce())->method('getId')->willReturn($customerId);
     $this->customerResourceModel->expects($this->once())->method('save')->with($customerModel);
     $this->customerRegistry->expects($this->once())->method('push')->with($customerModel);
     $this->customer->expects($this->any())->method('getAddresses')->willReturn([$address, $address2]);
     $this->addressRepository->expects($this->once())->method('save')->with($address);
     $customerAttributesMetaData->expects($this->once())->method('getEmail')->willReturn('*****@*****.**');
     $customerAttributesMetaData->expects($this->once())->method('getWebsiteId')->willReturn(2);
     $this->customerRegistry->expects($this->once())->method('retrieveByEmail')->with('*****@*****.**', 2)->willReturn($customerModel);
     $this->eventManager->expects($this->once())->method('dispatch')->with('customer_save_after_data_object', ['customer_data_object' => $this->customer, 'orig_customer_data_object' => $customerAttributesMetaData]);
     $this->model->save($this->customer, $passwordHash);
 }
 /**
  * @dataProvider updateCustomerDataProvider
  * @magentoAppArea frontend
  * @magentoDataFixture Magento/Customer/_files/customer.php
  * @param int|null $defaultBilling
  * @param int|null $defaultShipping
  */
 public function testUpdateCustomer($defaultBilling, $defaultShipping)
 {
     $existingCustomerId = 1;
     $email = '*****@*****.**';
     $firstName = 'Firstsave';
     $lastName = 'Lastsave';
     $customerBefore = $this->customerRepository->getById($existingCustomerId);
     $customerData = array_merge($customerBefore->__toArray(), ['id' => 1, 'email' => $email, 'firstname' => $firstName, 'lastname' => $lastName, 'created_in' => 'Admin', 'password' => 'notsaved', 'default_billing' => $defaultBilling, 'default_shipping' => $defaultShipping]);
     $customerDetails = $this->customerFactory->create();
     $this->dataObjectHelper->populateWithArray($customerDetails, $customerData, '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     $this->customerRepository->save($customerDetails);
     $customerAfter = $this->customerRepository->getById($existingCustomerId);
     $this->assertEquals($email, $customerAfter->getEmail());
     $this->assertEquals($firstName, $customerAfter->getFirstname());
     $this->assertEquals($lastName, $customerAfter->getLastname());
     $this->assertEquals($defaultBilling, $customerAfter->getDefaultBilling());
     $this->assertEquals($defaultShipping, $customerAfter->getDefaultShipping());
     $this->expectedDefaultShippingsInCustomerModelAttributes($existingCustomerId, $defaultBilling, $defaultShipping);
     $this->assertEquals('Admin', $customerAfter->getCreatedIn());
     $passwordFromFixture = 'password';
     $this->accountManagement->authenticate($customerAfter->getEmail(), $passwordFromFixture);
     $attributesBefore = $this->converter->toFlatArray($customerBefore, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     $attributesAfter = $this->converter->toFlatArray($customerAfter, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     // ignore 'updated_at'
     unset($attributesBefore['updated_at']);
     unset($attributesAfter['updated_at']);
     $inBeforeOnly = array_diff_assoc($attributesBefore, $attributesAfter);
     $inAfterOnly = array_diff_assoc($attributesAfter, $attributesBefore);
     $expectedInBefore = ['firstname', 'lastname', 'email'];
     foreach ($expectedInBefore as $key) {
         $this->assertContains($key, array_keys($inBeforeOnly));
     }
     $this->assertContains('created_in', array_keys($inAfterOnly));
     $this->assertContains('firstname', array_keys($inAfterOnly));
     $this->assertContains('lastname', array_keys($inAfterOnly));
     $this->assertContains('email', array_keys($inAfterOnly));
     $this->assertNotContains('password_hash', array_keys($inAfterOnly));
 }
 /**
  * {@inheritdoc}
  */
 public function validate(CustomerInterface $customer)
 {
     $customerData = $this->extensibleDataObjectConverter->toFlatArray($customer, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     $customerErrors = $this->validator->validateData($customerData, [], 'customer');
     $validationResults = $this->validationResultsDataFactory->create();
     if ($customerErrors !== true) {
         return $validationResults->setIsValid(false)->setMessages($this->validator->getMessages());
     }
     $oldAddresses = $customer->getAddresses();
     $customerModel = $this->customerFactory->create()->updateData($customer->setAddresses([]));
     $customer->setAddresses($oldAddresses);
     $result = $customerModel->validate();
     if (true !== $result && is_array($result)) {
         return $validationResults->setIsValid(false)->setMessages($result);
     }
     return $validationResults->setIsValid(true)->setMessages([]);
 }
Beispiel #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->getCustomer();
     $customerData = $this->extensibleDataObjectConverter->toFlatArray($customer, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     /** @var Form $customerForm */
     $customerForm = $this->_formFactory->create(\Magento\Customer\Api\CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER, 'checkout_register', $customerData, $this->_request->isAjax(), Form::IGNORE_INVISIBLE, []);
     if ($isCustomerNew) {
         $customerRequest = $customerForm->prepareRequest($data);
         $customerData = $customerForm->extractData($customerRequest);
     }
     $customerErrors = $customerForm->validateData($customerData);
     if ($customerErrors !== true) {
         return ['error' => -1, 'message' => implode(', ', $customerErrors)];
     }
     if (!$isCustomerNew) {
         return true;
     }
     $customer = $this->customerDataFactory->create();
     $this->dataObjectHelper->populateWithArray($customer, $customerData, '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     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->accountManagement->getPasswordHash($password));
     } else {
         // set NOT LOGGED IN group id explicitly,
         // otherwise copyFieldsetToTarget('customer_account', 'to_quote') will fill it with default group id value
         $customer->setGroupId(GroupInterface::NOT_LOGGED_IN_ID);
     }
     //validate customer
     $result = $this->accountManagement->validate($customer);
     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', $this->extensibleDataObjectConverter->toFlatArray($customer, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface'), $quote);
     return true;
 }
Beispiel #22
0
 /**
  * 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;
 }
 /**
  * {@inheritdoc}
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function save(\Magento\Customer\Api\Data\CustomerInterface $customer, $passwordHash = null)
 {
     $this->validate($customer);
     $prevCustomerData = null;
     if ($customer->getId()) {
         $prevCustomerData = $this->getById($customer->getId());
     }
     $customer = $this->imageProcessor->save($customer, CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER, $prevCustomerData);
     $origAddresses = $customer->getAddresses();
     $customer->setAddresses([]);
     $customerData = $this->extensibleDataObjectConverter->toNestedArray($customer, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     $customer->setAddresses($origAddresses);
     $customerModel = $this->customerFactory->create(['data' => $customerData]);
     $storeId = $customerModel->getStoreId();
     if ($storeId === null) {
         $customerModel->setStoreId($this->storeManager->getStore()->getId());
     }
     $customerModel->setId($customer->getId());
     // Need to use attribute set or future updates can cause data loss
     if (!$customerModel->getAttributeSetId()) {
         $customerModel->setAttributeSetId(\Magento\Customer\Api\CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER);
     }
     // Populate model with secure data
     if ($customer->getId()) {
         $customerSecure = $this->customerRegistry->retrieveSecureData($customer->getId());
         $customerModel->setRpToken($customerSecure->getRpToken());
         $customerModel->setRpTokenCreatedAt($customerSecure->getRpTokenCreatedAt());
         $customerModel->setPasswordHash($customerSecure->getPasswordHash());
     } else {
         if ($passwordHash) {
             $customerModel->setPasswordHash($passwordHash);
         }
     }
     // If customer email was changed, reset RpToken info
     if ($prevCustomerData && $prevCustomerData->getEmail() !== $customerModel->getEmail()) {
         $customerModel->setRpToken(null);
         $customerModel->setRpTokenCreatedAt(null);
     }
     $this->customerResourceModel->save($customerModel);
     $this->customerRegistry->push($customerModel);
     $customerId = $customerModel->getId();
     if ($customer->getAddresses() !== null) {
         if ($customer->getId()) {
             $existingAddresses = $this->getById($customer->getId())->getAddresses();
             $getIdFunc = function ($address) {
                 return $address->getId();
             };
             $existingAddressIds = array_map($getIdFunc, $existingAddresses);
         } else {
             $existingAddressIds = [];
         }
         $savedAddressIds = [];
         foreach ($customer->getAddresses() as $address) {
             $address->setCustomerId($customerId)->setRegion($address->getRegion());
             $this->addressRepository->save($address);
             if ($address->getId()) {
                 $savedAddressIds[] = $address->getId();
             }
         }
         $addressIdsToDelete = array_diff($existingAddressIds, $savedAddressIds);
         foreach ($addressIdsToDelete as $addressId) {
             $this->addressRepository->deleteById($addressId);
         }
     }
     $savedCustomer = $this->get($customer->getEmail(), $customer->getWebsiteId());
     $this->eventManager->dispatch('customer_save_after_data_object', ['customer_data_object' => $savedCustomer, 'orig_customer_data_object' => $customer]);
     return $savedCustomer;
 }
Beispiel #24
0
 /**
  * Convert address data object to a flat array
  *
  * @param CustomerInterface $customer
  * @return array
  */
 public function toFlatArray(CustomerInterface $customer)
 {
     $flatArray = $this->extensibleDataObjectConverter->toNestedArray($customer, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
     unset($flatArray["addresses"]);
     return ConvertArray::toFlatArray($flatArray);
 }