/** * @param string $entityType * @param object $entity * @return object * @throws CouldNotSaveException * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function execute($entityType, $entity) { /** * @var $entity \Magento\Catalog\Api\Data\ProductLinkInterface */ $linkedProduct = $this->productRepository->get($entity->getLinkedProductSku()); $product = $this->productRepository->get($entity->getSku()); $links = []; $extensions = $this->dataObjectProcessor->buildOutputDataArray($entity->getExtensionAttributes(), 'Magento\\Catalog\\Api\\Data\\ProductLinkExtensionInterface'); $extensions = is_array($extensions) ? $extensions : []; $data = $entity->__toArray(); foreach ($extensions as $attributeCode => $attribute) { $data[$attributeCode] = $attribute; } unset($data['extension_attributes']); $data['product_id'] = $linkedProduct->getId(); $links[$linkedProduct->getId()] = $data; try { $linkTypesToId = $this->linkTypeProvider->getLinkTypes(); $prodyctHydrator = $this->metadataPool->getHydrator(ProductInterface::class); $productData = $prodyctHydrator->extract($product); $this->linkResource->saveProductLinks($productData[$this->metadataPool->getMetadata(ProductInterface::class)->getLinkField()], $links, $linkTypesToId[$entity->getLinkType()]); } catch (\Exception $exception) { throw new CouldNotSaveException(__('Invalid data provided for linked products')); } return $entity; }
/** * Update Model with the data from Data Interface * * @param AddressInterface $address * @return $this * @deprecated Use Api/RepositoryInterface for the operations in the Data Interfaces. Don't rely on Address Model */ public function updateData(AddressInterface $address) { // Set all attributes $attributes = $this->dataProcessor->buildOutputDataArray($address, '\\Magento\\Customer\\Api\\Data\\AddressInterface'); foreach ($attributes as $attributeCode => $attributeData) { if (AddressInterface::REGION === $attributeCode) { $this->setRegion($address->getRegion()->getRegion()); $this->setRegionCode($address->getRegion()->getRegionCode()); $this->setRegionId($address->getRegion()->getRegionId()); } else { $this->setDataUsingMethod($attributeCode, $attributeData); } } // Need to explicitly set this due to discrepancy in the keys between model and data object $this->setIsDefaultBilling($address->isDefaultBilling()); $this->setIsDefaultShipping($address->isDefaultShipping()); if (!$this->getAttributeSetId()) { $this->setAttributeSetId(AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS); } $customAttributes = $address->getCustomAttributes(); if ($customAttributes !== null) { foreach ($customAttributes as $attribute) { $this->setData($attribute->getAttributeCode(), $attribute->getValue()); } } return $this; }
/** * 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'])); }
/** * Convert AbstractExtensibleObject into a nested array. * * @param ExtensibleDataInterface $dataObject * @param string[] $skipAttributes * @param string $dataObjectType * @return array */ public function toNestedArray(ExtensibleDataInterface $dataObject, $skipAttributes = [], $dataObjectType = null) { if ($dataObjectType == null) { $dataObjectType = get_class($dataObject); } $dataObjectArray = $this->dataObjectProcessor->buildOutputDataArray($dataObject, $dataObjectType); //process custom attributes if present if (!empty($dataObjectArray[AbstractExtensibleObject::CUSTOM_ATTRIBUTES_KEY])) { /** @var AttributeValue[] $customAttributes */ $customAttributes = $dataObjectArray[AbstractExtensibleObject::CUSTOM_ATTRIBUTES_KEY]; unset($dataObjectArray[AbstractExtensibleObject::CUSTOM_ATTRIBUTES_KEY]); foreach ($customAttributes as $attributeValue) { if (!in_array($attributeValue[AttributeValue::ATTRIBUTE_CODE], $skipAttributes)) { $dataObjectArray[$attributeValue[AttributeValue::ATTRIBUTE_CODE]] = $attributeValue[AttributeValue::VALUE]; } } } if (!empty($dataObjectArray[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY])) { /** @var array $extensionAttributes */ $extensionAttributes = $dataObjectArray[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]; unset($dataObjectArray[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]); foreach ($extensionAttributes as $attributeKey => $attributeValue) { if (!in_array($attributeKey, $skipAttributes)) { $dataObjectArray[$attributeKey] = $attributeValue; } } } return $dataObjectArray; }
/** * Create or save customer group. * * @return \Magento\Backend\Model\View\Result\Redirect|\Magento\Backend\Model\View\Result\Forward */ public function executeInternal() { $taxClass = (int) $this->getRequest()->getParam('tax_class'); /** @var \Magento\Customer\Api\Data\GroupInterface $customerGroup */ $customerGroup = null; if ($taxClass) { $id = $this->getRequest()->getParam('id'); $resultRedirect = $this->resultRedirectFactory->create(); try { if ($id !== null) { $customerGroup = $this->groupRepository->getById((int) $id); } else { $customerGroup = $this->groupDataFactory->create(); } $customerGroupCode = (string) $this->getRequest()->getParam('code'); if (empty($customerGroupCode)) { $customerGroupCode = null; } $customerGroup->setCode($customerGroupCode); $customerGroup->setTaxClassId($taxClass); $this->groupRepository->save($customerGroup); $this->messageManager->addSuccess(__('You saved the customer group.')); $resultRedirect->setPath('customer/group'); } catch (\Exception $e) { $this->messageManager->addError($e->getMessage()); if ($customerGroup != null) { $this->storeCustomerGroupDataToSession($this->dataObjectProcessor->buildOutputDataArray($customerGroup, '\\Magento\\Customer\\Api\\Data\\GroupInterface')); } $resultRedirect->setPath('customer/group/edit', ['id' => $id]); } return $resultRedirect; } else { return $this->resultForwardFactory->create()->forward('new'); } }
/** * {@inheritdoc} */ public function save(\Magento\Customer\Api\Data\GroupInterface $group) { $this->_validate($group); /** @var \Magento\Customer\Model\Group $groupModel */ $groupModel = null; if ($group->getId()) { $this->_verifyTaxClassModel($group->getTaxClassId(), $group); $groupModel = $this->groupRegistry->retrieve($group->getId()); $groupDataAttributes = $this->dataObjectProcessor->buildOutputDataArray($group, '\\Magento\\Customer\\Api\\Data\\GroupInterface'); foreach ($groupDataAttributes as $attributeCode => $attributeData) { $groupModel->setDataUsingMethod($attributeCode, $attributeData); } } else { $groupModel = $this->groupFactory->create(); $groupModel->setCode($group->getCode()); $taxClassId = $group->getTaxClassId() ?: self::DEFAULT_TAX_CLASS_ID; $this->_verifyTaxClassModel($taxClassId, $group); $groupModel->setTaxClassId($taxClassId); } try { $this->groupResourceModel->save($groupModel); } catch (\Magento\Framework\Exception\LocalizedException $e) { /** * Would like a better way to determine this error condition but * difficult to do without imposing more database calls */ if ($e->getMessage() == (string) __('Customer Group already exists.')) { throw new InvalidTransitionException(__('Customer Group already exists.')); } throw $e; } $this->groupRegistry->remove($groupModel->getId()); $groupDataObject = $this->groupDataFactory->create()->setId($groupModel->getId())->setCode($groupModel->getCode())->setTaxClassId($groupModel->getTaxClassId())->setTaxClassName($groupModel->getTaxClassName()); return $groupDataObject; }
/** * {@inheritdoc} */ public function extract($entity) { $entityType = $this->typeResolver->resolve($entity); $data = $this->dataObjectProcessor->buildOutputDataArray($entity, $entityType); $mapper = $this->mapperPool->getMapper($entityType); return $mapper->entityToDatabase($entityType, $data); }
/** * Convert nested array into flat array. * * @param ExtensibleDataInterface $dataObject * @param string $dataObjectType * @return array */ public function toFlatArray(ExtensibleDataInterface $dataObject, $dataObjectType = null) { if ($dataObjectType === null) { $dataObjectType = get_class($dataObject); } $data = $this->dataObjectProcessor->buildOutputDataArray($dataObject, $dataObjectType); return ConvertArray::toFlatArray($data); }
/** * {@inheritdoc} */ public function save(\Stepzerosolutions\Tbslider\Api\Data\SlideritemsInterface $slider) { $this->_validate($slider); /** @var \Stepzerosolutions\Tbslider\Model\Bookings\Slideritems $sliderModel */ $sliderModel = null; if ($slider->getId()) { $sliderModel = $this->slideritemsRegistry->retrieve($slider->getId()); $sliderDataAttributes = $this->dataObjectProcessor->buildOutputDataArray($slider, '\\Stepzerosolutions\\Tbslider\\Api\\Data\\SlideritemsInterface'); foreach ($sliderDataAttributes as $attributeCode => $attributeData) { $sliderModel->setDataUsingMethod($attributeCode, $attributeData); } } else { $sliderModel = $this->slideritemsFactory->create(); $sliderModel->setSlideritemTitle($slider->getSlideritemTitle()); $sliderModel->setSlideritem_description($slider->getSlideritemDescription()); $sliderModel->setSlideritemSlider($slider->getSlideritemSlider()); $sliderModel->setSliderImagePath($slider->getSliderImagePath()); $sliderModel->setSliderImageMdPath($slider->getSliderImageMdPath()); $sliderModel->setSliderImageSmPath($slider->getSliderImageSmPath()); $sliderModel->setSliderImageXsPath($slider->getSliderImageXsPath()); $sliderModel->setSliderUrl($slider->getSliderUrl()); $sliderModel->setDate($slider->getDate()); $sliderModel->setTimestamp($slider->getTimestamp()); $sliderModel->setSliderSort($slider->getSliderSort()); $sliderModel->setCaptionmeta($slider->getCaptionmeta()); $sliderModel->setIsActive($slider->getIsActive()); } try { $this->slideritemsResourceModel->save($sliderModel); } catch (\Magento\Framework\Exception\LocalizedException $e) { /** * Would like a better way to determine this error condition but * difficult to do without imposing more database calls */ die($e->getMessage()); if ($e->getMessage() == (string) __('Slideritems already exists.')) { throw new InvalidTransitionException(__('Slideritems already exists.')); } throw $e; } $this->slideritemsRegistry->remove($sliderModel->getId()); $sliderDataObject = $this->slideritemsDataFactory->create(); $sliderDataObject->setSlideritemTitle($sliderModel->getSlideritemTitle()); $sliderDataObject->setSlideritemDescription($sliderModel->getSlideritemDescription()); $sliderDataObject->setSlideritemSlider($sliderModel->getSlideritemSlider()); $sliderDataObject->setSliderImagePath($sliderModel->getSliderImagePath()); $sliderDataObject->setSliderImageMdPath($sliderModel->getSliderImageMdPath()); $sliderDataObject->setSliderImageSmPath($sliderModel->getSliderImageSmPath()); $sliderDataObject->setSliderImageXsPath($sliderModel->getSliderImageXsPath()); $sliderDataObject->setSliderUrl($sliderModel->getSliderUrl()); $sliderDataObject->setDate($sliderModel->getDate()); $sliderDataObject->setTimestamp($sliderModel->getTimestamp()); $sliderDataObject->setSliderSort($sliderModel->getSliderSort()); $sliderDataObject->setCaptionmeta($sliderModel->getCaptionmeta()); $sliderDataObject->setIsActive($sliderModel->getIsActive()); return $sliderDataObject; }
/** * Retrieve slides matching the specified criteria. * * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria * @return \Magento\Framework\Api\SearchResultsInterface * @throws \Magento\Framework\Exception\LocalizedException */ public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria) { $this->searchResultsFactory->setSearchCriteria($searchCriteria); $collection = $this->slideCollectionFactory->create(); foreach ($searchCriteria->getFilterGroups() as $filterGroup) { foreach ($filterGroup->getFilters() as $filter) { $condition = $filter->getConditionType() ?: 'eq'; $collection->addFieldToFilter($filter->getField(), [$condition => $filter->getValue()]); } } $this->searchResultsFactory->setTotalCount($collection->getSize()); $sortOrders = $searchCriteria->getSortOrders(); if ($sortOrders) { foreach ($sortOrders as $sortOrder) { $collection->addOrder($sortOrder->getField(), strtoupper($sortOrder->getDirection()) === 'ASC' ? 'ASC' : 'DESC'); } } $collection->setCurPage($searchCriteria->getCurrentPage()); $collection->setPageSize($searchCriteria->getPageSize()); $slides = []; /** @var \Foggyline\Slider\Model\Slide $slideModel */ foreach ($collection as $slideModel) { $slideData = $this->dataSlideFactory->create(); $this->dataObjectHelper->populateWithArray($slideData, $slideModel->getData(), '\\Foggyline\\Slider\\Api\\Data\\SlideInterface'); $slides[] = $this->dataObjectProcessor->buildOutputDataArray($slideData, '\\Foggyline\\Slider\\Api\\Data\\SlideInterface'); } $this->searchResultsFactory->setItems($slides); return $this->searchResultsFactory; }
/** * Retrieve log entities matching the specified criteria. * * @param \Magento\Framework\Api\SearchCriteriaInterface $criteria * @return \Foggyline\Sentinel\Api\Data\LoginLogSearchResultsInterface * @throws \Magento\Framework\Exception\LocalizedException */ public function getList(\Magento\Framework\Api\SearchCriteriaInterface $criteria) { $searchResults = $this->searchResultsFactory->create(); $searchResults->setSearchCriteria($criteria); /* @var $collection \Foggyline\Sentinel\Model\ResourceModel\LoginLog\Collection */ $collection = $this->logCollectionFactory->create(); foreach ($criteria->getFilterGroups() as $filterGroup) { foreach ($filterGroup->getFilters() as $filter) { if ($filter->getField() === 'store_id') { $collection->addFieldToFilter('store', ['in' => $filter->getValue()]); continue; } $condition = $filter->getConditionType() ?: 'eq'; $collection->addFieldToFilter($filter->getField(), [$condition => $filter->getValue()]); } } $searchResults->setTotalCount($collection->getSize()); $sortOrders = $criteria->getSortOrders(); if ($sortOrders) { foreach ($sortOrders as $sortOrder) { $collection->addOrder($sortOrder->getField(), $sortOrder->getDirection() == SortOrder::SORT_ASC ? 'ASC' : 'DESC'); } } $collection->setCurPage($criteria->getCurrentPage()); $collection->setPageSize($criteria->getPageSize()); $logs = []; /** @var \Foggyline\Sentinel\Model\LoginLog $logModel */ foreach ($collection as $logModel) { $logData = $this->dataLoginLogFactory->create(); $this->dataObjectHelper->populateWithArray($logData, $logModel->getData(), '\\Foggyline\\Sentinel\\Api\\Data\\LoginLogInterface'); $logs[] = $this->dataObjectProcessor->buildOutputDataArray($logData, '\\Foggyline\\Sentinel\\Api\\Data\\LoginLogInterface'); } $searchResults->setItems($logs); return $searchResults; }
/** * Create customer using setters. * * @return CustomerInterface */ public function createSampleCustomerDataObject() { $customerAddress1 = $this->customerAddressFactory->create(); $customerAddress1->setCountryId('US'); $customerAddress1->setIsDefaultBilling(true); $customerAddress1->setIsDefaultShipping(true); $customerAddress1->setPostcode('75477'); $customerAddress1->setRegion(Bootstrap::getObjectManager()->create('Magento\\Customer\\Api\\Data\\RegionInterfaceFactory')->create()->setRegionCode(self::ADDRESS_REGION_CODE1)->setRegion('Alabama')->setRegionId(1)); $customerAddress1->setStreet(['Green str, 67']); $customerAddress1->setTelephone('3468676'); $customerAddress1->setCity(self::ADDRESS_CITY1); $customerAddress1->setFirstname('John'); $customerAddress1->setLastname('Smith'); $address1 = $this->dataObjectProcessor->buildOutputDataArray($customerAddress1, 'Magento\\Customer\\Api\\Data\\AddressInterface'); $customerAddress2 = $this->customerAddressFactory->create(); $customerAddress2->setCountryId('US'); $customerAddress2->setIsDefaultBilling(false); $customerAddress2->setIsDefaultShipping(false); $customerAddress2->setPostcode('47676'); $customerAddress2->setRegion(Bootstrap::getObjectManager()->create('Magento\\Customer\\Api\\Data\\RegionInterfaceFactory')->create()->setRegionCode(self::ADDRESS_REGION_CODE2)->setRegion('Alabama')->setRegionId(1)); $customerAddress2->setStreet(['Black str, 48', 'Building D']); $customerAddress2->setTelephone('3234676'); $customerAddress2->setCity(self::ADDRESS_CITY2); $customerAddress2->setFirstname('John'); $customerAddress2->setLastname('Smith'); $address2 = $this->dataObjectProcessor->buildOutputDataArray($customerAddress2, 'Magento\\Customer\\Api\\Data\\AddressInterface'); $customerData = [CustomerData::FIRSTNAME => self::FIRSTNAME, CustomerData::LASTNAME => self::LASTNAME, CustomerData::EMAIL => 'janedoe' . uniqid() . '@example.com', CustomerData::CONFIRMATION => self::CONFIRMATION, CustomerData::CREATED_AT => self::CREATED_AT, CustomerData::CREATED_IN => self::STORE_NAME, CustomerData::DOB => self::DOB, CustomerData::GENDER => self::GENDER, CustomerData::GROUP_ID => self::GROUP_ID, CustomerData::MIDDLENAME => self::MIDDLENAME, CustomerData::PREFIX => self::PREFIX, CustomerData::STORE_ID => self::STORE_ID, CustomerData::SUFFIX => self::SUFFIX, CustomerData::TAXVAT => self::TAXVAT, CustomerData::WEBSITE_ID => self::WEBSITE_ID, CustomerData::KEY_ADDRESSES => [$address1, $address2], 'custom_attributes' => [['attribute_code' => 'disable_auto_group_change', 'value' => '0']]]; $customer = $this->customerDataFactory->create(); $this->dataObjectHelper->populateWithArray($customer, $customerData, '\\Magento\\Customer\\Api\\Data\\CustomerInterface'); return $customer; }
/** * Load Page data collection by given search criteria * * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @param \Magento\Framework\Api\SearchCriteriaInterface $criteria * @return \Magento\Cms\Model\ResourceModel\Page\Collection */ public function getList(\Magento\Framework\Api\SearchCriteriaInterface $criteria) { $searchResults = $this->searchResultsFactory->create(); $searchResults->setSearchCriteria($criteria); $collection = $this->pageCollectionFactory->create(); foreach ($criteria->getFilterGroups() as $filterGroup) { foreach ($filterGroup->getFilters() as $filter) { if ($filter->getField() === 'store_id') { $collection->addStoreFilter($filter->getValue(), false); continue; } $condition = $filter->getConditionType() ?: 'eq'; $collection->addFieldToFilter($filter->getField(), [$condition => $filter->getValue()]); } } $searchResults->setTotalCount($collection->getSize()); $sortOrders = $criteria->getSortOrders(); if ($sortOrders) { /** @var SortOrder $sortOrder */ foreach ($sortOrders as $sortOrder) { $collection->addOrder($sortOrder->getField(), $sortOrder->getDirection() == SortOrder::SORT_ASC ? 'ASC' : 'DESC'); } } $collection->setCurPage($criteria->getCurrentPage()); $collection->setPageSize($criteria->getPageSize()); $pages = []; /** @var Page $pageModel */ foreach ($collection as $pageModel) { $pageData = $this->dataPageFactory->create(); $this->dataObjectHelper->populateWithArray($pageData, $pageModel->getData(), 'Magento\\Cms\\Api\\Data\\PageInterface'); $pages[] = $this->dataObjectProcessor->buildOutputDataArray($pageData, 'Magento\\Cms\\Api\\Data\\PageInterface'); } $searchResults->setItems($pages); return $searchResults; }
/** * Convert associative array into proper data object. * * @param array $data * @param string $dataType * @return array|object */ public function convertValue($data, $dataType) { if (is_array($data)) { $result = []; $arrayElementType = substr($dataType, 0, -2); foreach ($data as $datum) { if (is_object($datum)) { $datum = $this->processDataObject( $this->dataObjectProcessor->buildOutputDataArray($datum, $arrayElementType) ); } $result[] = $datum; } return $result; } elseif (is_object($data)) { return $this->processDataObject( $this->dataObjectProcessor->buildOutputDataArray($data, $dataType) ); } elseif ($data === null) { return []; } else { /** No processing is required for scalar types */ return $data; } }
/** * Retrieve teaserItems matching the specified criteria. * * @param SearchCriteriaInterface $searchCriteria * * @return Data\TeaserItemSearchResultInterface * * @throws \Magento\Framework\Exception\LocalizedException */ public function getList(SearchCriteriaInterface $searchCriteria) { /** @var Data\TeaserItemSearchResultInterface $searchResults */ $searchResults = $this->searchResultsFactory->create(); $searchResults->setSearchCriteria($searchCriteria); /** @var TeaserItemResource\Collection $collection */ $collection = $this->teaserItemCollectionFactory->create(); foreach ($searchCriteria->getFilterGroups() as $filterGroup) { foreach ($filterGroup->getFilters() as $filter) { $condition = $filter->getConditionType() ?: 'eq'; $collection->addFieldToFilter($filter->getField(), [$condition => $filter->getValue()]); } } $searchResults->setTotalCount($collection->getSize()); $sortOrders = $searchCriteria->getSortOrders(); if ($sortOrders) { foreach ($sortOrders as $sortOrder) { $collection->addOrder($sortOrder->getField(), $sortOrder->getDirection() == SortOrder::SORT_ASC ? 'ASC' : 'DESC'); } } $collection->setCurPage($searchCriteria->getCurrentPage()); $collection->setPageSize($searchCriteria->getPageSize()); $teaserItems = []; /** @var TeaserItem $teaserItemModel */ foreach ($collection as $teaserItemModel) { $teaserItemData = $this->teaserItemFactory->create(); $this->dataObjectHelper->populateWithArray($teaserItemData, $teaserItemModel->getData(), Data\TeaserItemInterface::class); $teaserItems[] = $this->dataObjectProcessor->buildOutputDataArray($teaserItemData, Data\TeaserItemInterface::class); } $searchResults->setItems($teaserItems); return $searchResults; }
/** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function testNewAccount() { $customerId = 1; $customerStoreId = 2; $customerEmail = '*****@*****.**'; $customerData = ['key' => 'value']; $customerName = 'Customer Name'; $templateIdentifier = 'Template Identifier'; $sender = 'Sender'; $customer = $this->getMock(\Magento\Customer\Api\Data\CustomerInterface::class, [], [], '', false); $customer->expects($this->any())->method('getStoreId')->willReturn($customerStoreId); $customer->expects($this->any())->method('getId')->willReturn($customerId); $customer->expects($this->any())->method('getEmail')->willReturn($customerEmail); $this->storeMock->expects($this->any())->method('getId')->willReturn($customerStoreId); $this->storeManagerMock->expects($this->once())->method('getStore')->with($customerStoreId)->willReturn($this->storeMock); $this->customerRegistryMock->expects($this->once())->method('retrieveSecureData')->with($customerId)->willReturn($this->customerSecureMock); $this->dataProcessorMock->expects($this->once())->method('buildOutputDataArray')->with($customer, \Magento\Customer\Api\Data\CustomerInterface::class)->willReturn($customerData); $this->customerViewHelperMock->expects($this->any())->method('getCustomerName')->with($customer)->willReturn($customerName); $this->customerSecureMock->expects($this->once())->method('addData')->with($customerData)->willReturnSelf(); $this->customerSecureMock->expects($this->once())->method('setData')->with('name', $customerName)->willReturnSelf(); $this->scopeConfigMock->expects($this->at(0))->method('getValue')->with(EmailNotification::XML_PATH_REGISTER_EMAIL_TEMPLATE, ScopeInterface::SCOPE_STORE, $customerStoreId)->willReturn($templateIdentifier); $this->scopeConfigMock->expects($this->at(1))->method('getValue')->with(EmailNotification::XML_PATH_REGISTER_EMAIL_IDENTITY, ScopeInterface::SCOPE_STORE, $customerStoreId)->willReturn($sender); $transport = $this->getMock(\Magento\Framework\Mail\TransportInterface::class, [], [], '', false); $this->transportBuilderMock->expects($this->once())->method('setTemplateIdentifier')->with($templateIdentifier)->willReturnSelf(); $this->transportBuilderMock->expects($this->once())->method('setTemplateOptions')->with(['area' => Area::AREA_FRONTEND, 'store' => $customerStoreId])->willReturnSelf(); $this->transportBuilderMock->expects($this->once())->method('setTemplateVars')->with(['customer' => $this->customerSecureMock, 'back_url' => '', 'store' => $this->storeMock])->willReturnSelf(); $this->transportBuilderMock->expects($this->once())->method('setFrom')->with($sender)->willReturnSelf(); $this->transportBuilderMock->expects($this->once())->method('addTo')->with($customerEmail, $customerName)->willReturnSelf(); $this->transportBuilderMock->expects($this->once())->method('getTransport')->willReturn($transport); $transport->expects($this->once())->method('sendMessage'); $this->model->newAccount($customer, EmailNotification::NEW_ACCOUNT_EMAIL_REGISTERED, '', $customerStoreId); }
/** * Create customer using setters. * * @param array $additional * @return CustomerInterface */ public function createSampleCustomerDataObject(array $additional = []) { $customerAddress1 = $this->customerAddressFactory->create(); $customerAddress1->setCountryId('US'); $customerAddress1->setIsDefaultBilling(true); $customerAddress1->setIsDefaultShipping(true); $customerAddress1->setPostcode('75477'); $customerAddress1->setRegion(Bootstrap::getObjectManager()->create('Magento\\Customer\\Api\\Data\\RegionInterfaceFactory')->create()->setRegionCode(self::ADDRESS_REGION_CODE1)->setRegion('Alabama')->setRegionId(1)); $customerAddress1->setStreet(['Green str, 67']); $customerAddress1->setTelephone('3468676'); $customerAddress1->setCity(self::ADDRESS_CITY1); $customerAddress1->setFirstname('John'); $customerAddress1->setLastname('Smith'); $address1 = $this->dataObjectProcessor->buildOutputDataArray($customerAddress1, 'Magento\\Customer\\Api\\Data\\AddressInterface'); $customerAddress2 = $this->customerAddressFactory->create(); $customerAddress2->setCountryId('US'); $customerAddress2->setIsDefaultBilling(false); $customerAddress2->setIsDefaultShipping(false); $customerAddress2->setPostcode('47676'); $customerAddress2->setRegion(Bootstrap::getObjectManager()->create('Magento\\Customer\\Api\\Data\\RegionInterfaceFactory')->create()->setRegionCode(self::ADDRESS_REGION_CODE2)->setRegion('Alabama')->setRegionId(1)); $customerAddress2->setStreet(['Black str, 48', 'Building D']); $customerAddress2->setTelephone('3234676'); $customerAddress2->setCity(self::ADDRESS_CITY2); $customerAddress2->setFirstname('John'); $customerAddress2->setLastname('Smith'); $address2 = $this->dataObjectProcessor->buildOutputDataArray($customerAddress2, 'Magento\\Customer\\Api\\Data\\AddressInterface'); $customerData = $this->getCustomerSampleData(array_merge([CustomerData::KEY_ADDRESSES => [$address1, $address2]], $additional)); $customer = $this->customerDataFactory->create(); $this->dataObjectHelper->populateWithArray($customer, $customerData, '\\Magento\\Customer\\Api\\Data\\CustomerInterface'); return $customer; }
/** * @magentoDataFixture Magento/Customer/_files/customer.php */ public function testSaveNewAddressDefaults() { $customerId = 1; /** @var $addressShipping \Magento\Customer\Api\Data\AddressInterface */ $addressShipping = $this->_expectedAddresses[0]->setId(null); $addressShipping->setIsDefaultShipping(true)->setIsDefaultBilling(false)->setCustomerId($customerId); //TODO : Will be fixed as part of fixing populate. For now Region is set as Data Object instead of array $addressShipping->setRegion($this->_expectedAddresses[0]->getRegion()); /** @var $addressBilling \Magento\Customer\Api\Data\AddressInterface */ $addressBilling = $this->_expectedAddresses[1]->setId(null); $addressBilling->setIsDefaultBilling(true)->setIsDefaultShipping(false)->setCustomerId($customerId); //TODO : Will be fixed as part of fixing populate $addressBilling->setRegion($this->_expectedAddresses[1]->getRegion()); $addressShippingExpected = $this->addressRepository->save($addressShipping); $addressBillingExpected = $this->addressRepository->save($addressBilling); // Call api under test $shippingResponse = $this->accountManagement->getDefaultShippingAddress($customerId); $billingResponse = $this->accountManagement->getDefaultBillingAddress($customerId); // Verify if the new Shipping address created is same as returned by the api under test : // \Magento\Customer\Api\AccountManagementInterface::getDefaultShippingAddress $addressShippingExpected = $this->dataProcessor->buildOutputDataArray($addressShippingExpected, 'Magento\\Customer\\Api\\Data\\AddressInterface'); $shippingResponse = $this->dataProcessor->buildOutputDataArray($shippingResponse, 'Magento\\Customer\\Api\\Data\\AddressInterface'); // Response should have this set since we save as default shipping $addressShippingExpected[AddressInterface::DEFAULT_SHIPPING] = true; $this->assertEquals($addressShippingExpected, $shippingResponse); // Verify if the new Billing address created is same as returned by the api under test : // \Magento\Customer\Api\AccountManagementInterface::getDefaultShippingAddress $addressBillingExpected = $this->dataProcessor->buildOutputDataArray($addressBillingExpected, 'Magento\\Customer\\Api\\Data\\AddressInterface'); $billingResponse = $this->dataProcessor->buildOutputDataArray($billingResponse, 'Magento\\Customer\\Api\\Data\\AddressInterface'); // Response should have this set since we save as default billing $addressBillingExpected[AddressInterface::DEFAULT_BILLING] = true; $this->assertEquals($addressBillingExpected, $billingResponse); }
/** * @param RuleDataModel $dataModel * @return $this|Rule * @throws \Magento\Framework\Exception\NoSuchEntityException * @throws \Magento\Framework\Exception\InputException */ public function toModel(RuleDataModel $dataModel) { $ruleId = $dataModel->getRuleId(); if ($ruleId) { $ruleModel = $this->ruleFactory->create()->load($ruleId); if (!$ruleModel->getId()) { throw new \Magento\Framework\Exception\NoSuchEntityException(); } } else { $ruleModel = $this->ruleFactory->create(); } $modelData = $ruleModel->getData(); $data = $this->dataObjectProcessor->buildOutputDataArray($dataModel, '\\Magento\\SalesRule\\Api\\Data\\RuleInterface'); $mergedData = array_merge($modelData, $data); $validateResult = $ruleModel->validateData(new \Magento\Framework\DataObject($mergedData)); if ($validateResult !== true) { $text = ''; /** @var \Magento\Framework\Phrase $errorMessage */ foreach ($validateResult as $errorMessage) { $text .= $errorMessage->getText(); $text .= '; '; } throw new \Magento\Framework\Exception\InputException(new \Magento\Framework\Phrase($text)); } $ruleModel->setData($mergedData); $this->mapFields($ruleModel, $dataModel); return $ruleModel; }
public function testSave() { $groupId = 0; $taxClass = $this->getMockForAbstractClass('Magento\\Tax\\Api\\Data\\TaxClassInterface', [], '', false); $this->group->expects($this->once())->method('getCode')->willReturn('Code'); $this->group->expects($this->atLeastOnce())->method('getId')->willReturn($groupId); $this->group->expects($this->once())->method('getTaxClassId')->willReturn(17); $this->groupModel->expects($this->atLeastOnce())->method('getId')->willReturn($groupId); $this->groupModel->expects($this->atLeastOnce())->method('getCode')->willReturn('Code'); $this->groupModel->expects($this->atLeastOnce())->method('getTaxClassId')->willReturn(234); $this->groupModel->expects($this->atLeastOnce())->method('getTaxClassName')->willReturn('Tax class name'); $this->group->expects($this->once())->method('setId')->with($groupId)->willReturnSelf(); $this->group->expects($this->once())->method('setCode')->with('Code')->willReturnSelf(); $this->group->expects($this->once())->method('setTaxClassId')->with(234)->willReturnSelf(); $this->group->expects($this->once())->method('setTaxClassName')->with('Tax class name')->willReturnSelf(); $this->taxClassRepository->expects($this->once())->method('get')->with(17)->willReturn($taxClass); $taxClass->expects($this->once())->method('getClassType')->willReturn('CUSTOMER'); $this->groupRegistry->expects($this->once())->method('retrieve')->with($groupId)->willReturn($this->groupModel); $this->dataObjectProcessor->expects($this->once())->method('buildOutputDataArray')->with($this->group, '\\Magento\\Customer\\Api\\Data\\GroupInterface')->willReturn(['attributeCode' => 'attributeData']); $this->groupModel->expects($this->once())->method('setDataUsingMethod')->with('attributeCode', 'attributeData'); $this->groupResourceModel->expects($this->once())->method('save')->with($this->groupModel); $this->groupRegistry->expects($this->once())->method('remove')->with($groupId); $this->groupDataFactory->expects($this->once())->method('create')->willReturn($this->group); $this->assertSame($this->group, $this->model->save($this->group)); }
/** * @magentoApiDataFixture Magento/Customer/_files/attribute_user_defined_address.php * @magentoApiDataFixture Magento/Customer/_files/attribute_user_defined_customer.php */ public function testCustomAttributes() { //Sample customer data comes with the disable_auto_group_change custom attribute $customerData = $this->customerHelper->createSampleCustomerDataObject(); //address attribute code from fixture $fixtureAddressAttributeCode = 'address_user_attribute'; //customer attribute code from fixture $fixtureCustomerAttributeCode = 'user_attribute'; //Custom Attribute Values $address1CustomAttributeValue = 'value1'; $address2CustomAttributeValue = 'value2'; $customerCustomAttributeValue = 'value3'; $addresses = $customerData->getAddresses(); $addresses[0]->setCustomAttribute($fixtureAddressAttributeCode, $address1CustomAttributeValue); $addresses[1]->setCustomAttribute($fixtureAddressAttributeCode, $address2CustomAttributeValue); $customerData->setAddresses($addresses); $customerData->setCustomAttribute($fixtureCustomerAttributeCode, $customerCustomAttributeValue); $serviceInfo = ['rest' => ['resourcePath' => self::RESOURCE_PATH, 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST], 'soap' => ['service' => self::SERVICE_NAME, 'serviceVersion' => self::SERVICE_VERSION, 'operation' => self::SERVICE_NAME . 'CreateAccount']]; $customerDataArray = $this->dataObjectProcessor->buildOutputDataArray($customerData, '\\Magento\\Customer\\Api\\Data\\CustomerInterface'); $requestData = ['customer' => $customerDataArray, 'password' => CustomerHelper::PASSWORD]; $customerData = $this->_webApiCall($serviceInfo, $requestData); $customerId = $customerData['id']; //TODO: Fix assertions to verify custom attributes $this->assertNotNull($customerData); $serviceInfo = ['rest' => ['resourcePath' => self::RESOURCE_PATH . '/' . $customerId, 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE], 'soap' => ['service' => CustomerRepositoryTest::SERVICE_NAME, 'serviceVersion' => self::SERVICE_VERSION, 'operation' => CustomerRepositoryTest::SERVICE_NAME . 'DeleteById']]; $response = $this->_webApiCall($serviceInfo, ['customerId' => $customerId]); $this->assertTrue($response); }
/** * Add rendering EAV attributes to Form element * * @param \Magento\Customer\Api\Data\AttributeMetadataInterface[] $attributes * @param \Magento\Framework\Data\Form\AbstractForm $form * @return $this * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ protected function _addAttributesToForm($attributes, \Magento\Framework\Data\Form\AbstractForm $form) { // add additional form types $types = $this->_getAdditionalFormElementTypes(); foreach ($types as $type => $className) { $form->addType($type, $className); } $renderers = $this->_getAdditionalFormElementRenderers(); foreach ($attributes as $attribute) { $inputType = $attribute->getFrontendInput(); if ($inputType) { $element = $form->addField($attribute->getAttributeCode(), $inputType, ['name' => $attribute->getAttributeCode(), 'label' => __($attribute->getStoreLabel()), 'class' => $attribute->getFrontendClass(), 'required' => $attribute->isRequired()]); if ($inputType == 'multiline') { $element->setLineCount($attribute->getMultilineCount()); } $element->setEntityAttribute($attribute); $this->_addAdditionalFormElementData($element); if (!empty($renderers[$attribute->getAttributeCode()])) { $element->setRenderer($renderers[$attribute->getAttributeCode()]); } if ($inputType == 'select' || $inputType == 'multiselect') { $options = []; foreach ($attribute->getOptions() as $optionData) { $options[] = ConvertArray::toFlatArray($this->dataObjectProcessor->buildOutputDataArray($optionData, '\\Magento\\Customer\\Api\\Data\\OptionInterface')); } $element->setValues($options); } elseif ($inputType == 'date') { $format = $this->_localeDate->getDateFormat(\IntlDateFormatter::SHORT); $element->setDateFormat($format); } } } return $this; }
/** * @param string $email * @param string $templateIdentifier * @param string $sender * @param int $storeId * @param int $customerId * @param string $hash */ protected function prepareInitiatePasswordReset($email, $templateIdentifier, $sender, $storeId, $customerId, $hash) { $websiteId = 1; $dateTime = date(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT); $customerData = ['key' => 'value']; $customerName = 'Customer Name'; $this->store->expects($this->once())->method('getWebsiteId')->willReturn($websiteId); $this->store->expects($this->any())->method('getId')->willReturn($storeId); $this->storeManager->expects($this->any())->method('getStore')->willReturn($this->store); $customer = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\CustomerInterface')->getMock(); $customer->expects($this->any())->method('getEmail')->willReturn($email); $customer->expects($this->any())->method('getId')->willReturn($customerId); $customer->expects($this->any())->method('getStoreId')->willReturn($storeId); $this->customerRepository->expects($this->once())->method('get')->with($email, $websiteId)->willReturn($customer); $this->customerRepository->expects($this->once())->method('save')->with($customer)->willReturnSelf(); $this->random->expects($this->once())->method('getUniqueHash')->willReturn($hash); $this->customerViewHelper->expects($this->any())->method('getCustomerName')->with($customer)->willReturn($customerName); $this->customerSecure->expects($this->any())->method('setRpToken')->with($hash)->willReturnSelf(); $this->customerSecure->expects($this->any())->method('setRpTokenCreatedAt')->with($dateTime)->willReturnSelf(); $this->customerSecure->expects($this->any())->method('addData')->with($customerData)->willReturnSelf(); $this->customerSecure->expects($this->any())->method('setData')->with('name', $customerName)->willReturnSelf(); $this->customerRegistry->expects($this->any())->method('retrieveSecureData')->with($customerId)->willReturn($this->customerSecure); $this->dataObjectProcessor->expects($this->any())->method('buildOutputDataArray')->with($customer, '\\Magento\\Customer\\Api\\Data\\CustomerInterface')->willReturn($customerData); $this->prepareEmailSend($email, $templateIdentifier, $sender, $storeId, $customerName); }
/** * @return \Magento\Customer\Api\Data\CustomerInterface */ private function _loadCustomer() { $customer = $this->_customerRepository->getById(1); $data = ['account' => $this->_dataObjectProcessor->buildOutputDataArray($customer, 'Magento\\Customer\\Api\\Data\\CustomerInterface')]; $this->_context->getBackendSession()->setCustomerData($data); $this->_coreRegistry->register(RegistryConstants::CURRENT_CUSTOMER_ID, $customer->getId()); return $customer; }
/** * Merges second object onto the first * * @param string $interfaceName * @param mixed $firstDataObject * @param mixed $secondDataObject * @return $this * @throws \LogicException */ public function mergeDataObjects($interfaceName, $firstDataObject, $secondDataObject) { if (!$firstDataObject instanceof $interfaceName || !$secondDataObject instanceof $interfaceName) { throw new \LogicException('Wrong prototype object given. It can only be of "' . $interfaceName . '" type.'); } $secondObjectArray = $this->objectProcessor->buildOutputDataArray($secondDataObject, $interfaceName); $this->_setDataValues($firstDataObject, $secondObjectArray, $interfaceName); return $this; }
/** * @param AttributeMetadataInterface $attribute * @return array */ protected function _getAttributeOptionsArray(AttributeMetadataInterface $attribute) { $options = $attribute->getOptions(); $result = []; foreach ($options as $option) { $result[] = $this->dataObjectProcessor->buildOutputDataArray($option, 'Magento\\Customer\\Api\\Data\\OptionInterface'); } return $result; }
public function testToModel() { /** * @var \Magento\SalesRule\Model\Data\Rule $dataModel */ $dataModel = $this->getMockBuilder('\\Magento\\SalesRule\\Model\\Data\\Rule')->disableOriginalConstructor()->setMethods(['create', 'load', 'getData', 'getRuleId', 'getCondition', 'getActionCondition', 'getStoreLabels'])->getMock(); $dataModel->expects($this->atLeastOnce())->method('getRuleId')->willReturn(1); $dataModel->expects($this->atLeastOnce())->method('getCondition')->willReturn(false); $dataModel->expects($this->atLeastOnce())->method('getActionCondition')->willReturn(false); $dataModel->expects($this->atLeastOnce())->method('getStoreLabels')->willReturn([]); $ruleModel = $this->getMockBuilder('\\Magento\\SalesRule\\Model\\Rule')->disableOriginalConstructor()->setMethods(['create', 'load', 'getId', 'getData'])->getMock(); $ruleModel->expects($this->atLeastOnce())->method('load')->willReturn($ruleModel); $ruleModel->expects($this->atLeastOnce())->method('getId')->willReturn(1); $ruleModel->expects($this->atLeastOnce())->method('getData')->willReturn(['data_1' => 1]); $this->dataObjectProcessor->expects($this->any())->method('buildOutputDataArray')->willReturn(['data_2' => 2]); $this->ruleFactory->expects($this->any())->method('create')->willReturn($ruleModel); $result = $this->model->toModel($dataModel); $this->assertEquals($ruleModel, $result); }
/** * Create an object with data merged from Customer and CustomerSecure * * @param CustomerInterface $customer * @return \Magento\Customer\Model\Data\CustomerSecure */ private function getFullCustomerObject($customer) { // No need to flatten the custom attributes or nested objects since the only usage is for email templates and // object passed for events $mergedCustomerData = $this->customerRegistry->retrieveSecureData($customer->getId()); $customerData = $this->dataProcessor->buildOutputDataArray($customer, \Magento\Customer\Api\Data\CustomerInterface::class); $mergedCustomerData->addData($customerData); $mergedCustomerData->setData('name', $this->customerViewHelper->getCustomerName($customer)); return $mergedCustomerData; }
/** * @dataProvider expectedDatesProvider */ public function testFormattingDate($data) { /** * @var \Magento\SalesRule\Model\Data\Rule|\PHPUnit_Framework_MockObject_MockObject $dataModel */ $dataModel = $this->getMockBuilder(\Magento\SalesRule\Model\Data\Rule::class)->disableOriginalConstructor()->setMethods(['create', 'load', 'getData', 'getRuleId', 'getCondition', 'getActionCondition', 'getStoreLabels', 'getFromDate', 'setFromDate', 'getToDate', 'setToDate'])->getMock(); $dataModel->expects($this->atLeastOnce())->method('getRuleId')->willReturn(null); $dataModel->expects($this->atLeastOnce())->method('getCondition')->willReturn(false); $dataModel->expects($this->atLeastOnce())->method('getActionCondition')->willReturn(false); $dataModel->expects($this->atLeastOnce())->method('getStoreLabels')->willReturn([]); $ruleModel = $this->getMockBuilder('\\Magento\\SalesRule\\Model\\Rule')->disableOriginalConstructor()->setMethods(['create', 'load', 'getId', 'getData'])->getMock(); $ruleModel->expects($this->atLeastOnce())->method('getData')->willReturn(['data_1' => 1]); $this->dataObjectProcessor->expects($this->any())->method('buildOutputDataArray')->willReturn(['data_2' => 2]); $this->ruleFactory->expects($this->any())->method('create')->willReturn($ruleModel); $dataModel->expects($this->atLeastOnce())->method('getFromDate')->willReturn($data['from_date']); $dataModel->expects($this->atLeastOnce())->method('getToDate')->willReturn($data['to_date']); $dataModel->expects($this->atLeastOnce())->method('setFromDate')->with($data['expected_from_date']); $dataModel->expects($this->atLeastOnce())->method('setToDate')->with($data['expected_to_date']); $this->model->toModel($dataModel); }
/** * @magentoDataFixture Magento/Customer/_files/customer.php */ public function testNewCustomer() { /** @var \Magento\Customer\Api\Data\CustomerInterfaceFactory $customerFactory */ $customerFactory = $this->objectManager->get('Magento\\Customer\\Api\\Data\\CustomerInterfaceFactory'); $customerData = $this->dataObjectProcessor->buildOutputDataArray($customerFactory->create(), '\\Magento\\Customer\\Api\\Data\\CustomerInterface'); $this->backendSession->setCustomerData(['customer_id' => 0, 'account' => $customerData]); $result = $this->accountBlock->initForm()->toHtml(); // Contains send email controls $this->assertContains('<input id="_accountsendemail"', $result); $this->assertContains('<select id="_accountsendemail_store_id"', $result); }