/** * Converts a specified rate model to a shipping method data object. * * @param \Magento\Quote\Model\Quote\Item $item * @return array * @throws \Exception */ public function modelToDataObject($item) { $this->eventManager->dispatch('items_additional_data', ['item' => $item]); $items = $item->toArray(); $items['options'] = $this->getFormattedOptionValue($item); $itemsData = $this->totalsItemFactory->create(); $this->dataObjectHelper->populateWithArray($itemsData, $items, '\\Magento\\Quote\\Api\\Data\\TotalsItemInterface'); return $itemsData; }
/** * @param \Magento\Quote\Model\Quote $quote * @return \Magento\Quote\Model\Quote */ public function prepareQuoteForNewCustomer(\Magento\Quote\Model\Quote $quote) { $billing = $quote->getBillingAddress(); $shipping = $quote->isVirtual() ? null : $quote->getShippingAddress(); $billing->setDefaultBilling(true); if ($shipping && !$shipping->getSameAsBilling()) { $shipping->setDefaultShipping(true); $address = $shipping->exportCustomerAddress(); $shipping->setCustomerAddressData($address); } elseif ($shipping) { $billing->setDefaultShipping(true); } $address = $shipping->exportCustomerAddress(); $billing->setCustomerAddressData($address); foreach (['customer_dob', 'customer_taxvat', 'customer_gender'] as $attribute) { if ($quote->getData($attribute) && !$billing->getData($attribute)) { $billing->setData($attribute, $quote->getData($attribute)); } } $customer = $this->customerFactory->create(); $this->dataObjectHelper->populateWithArray($customer, $this->copyObject->getDataFromFieldset('checkout_onepage_billing', 'to_customer', $billing), '\\Magento\\Customer\\Api\\Data\\CustomerInterface'); $customer->setEmail($quote->getCustomerEmail()); $customer->setPrefix($quote->getCustomerPrefix()); $customer->setFirstname($quote->getCustomerFirstname()); $customer->setMiddlename($quote->getCustomerMiddlename()); $customer->setLastname($quote->getCustomerLastname()); $customer->setSuffix($quote->getCustomerSuffix()); $quote->setCustomer($customer); $quote->addCustomerAddress($billing->exportCustomerAddress()); if ($shipping->hasCustomerAddress()) { $quote->addCustomerAddress($shipping->exportCustomerAddress()); } return $quote; }
/** * @param Address $object * @param array $data * @return OrderAddressInterface */ public function convert(Address $object, $data = []) { $orderAddress = $this->orderAddressRepository->create(); $orderAddressData = $this->objectCopyService->getDataFromFieldset('quote_convert_address', 'to_order_address', $object); $this->dataObjectHelper->populateWithArray($orderAddress, array_merge($orderAddressData, $data), '\\Magento\\Sales\\Api\\Data\\OrderAddressInterface'); return $orderAddress; }
/** * Create AttributeMetadata Data object from the Attribute Model * * @param \Magento\Customer\Model\Attribute $attribute * @return \Magento\Customer\Api\Data\AttributeMetadataInterface */ public function createMetadataAttribute($attribute) { $options = []; if ($attribute->usesSource()) { foreach ($attribute->getSource()->getAllOptions() as $option) { $optionDataObject = $this->optionFactory->create(); if (!is_array($option['value'])) { $optionDataObject->setValue($option['value']); } else { $optionArray = []; foreach ($option['value'] as $optionArrayValues) { $optionObject = $this->optionFactory->create(); $this->dataObjectHelper->populateWithArray($optionObject, $optionArrayValues, '\\Magento\\Customer\\Api\\Data\\OptionInterface'); $optionArray[] = $optionObject; } $optionDataObject->setOptions($optionArray); } $optionDataObject->setLabel($option['label']); $options[] = $optionDataObject; } } $validationRules = []; foreach ($attribute->getValidateRules() as $name => $value) { $validationRule = $this->validationRuleFactory->create()->setName($name)->setValue($value); $validationRules[] = $validationRule; } return $this->attributeMetadataFactory->create()->setAttributeCode($attribute->getAttributeCode())->setFrontendInput($attribute->getFrontendInput())->setInputFilter((string) $attribute->getInputFilter())->setStoreLabel($attribute->getStoreLabel())->setValidationRules($validationRules)->setIsVisible((bool) $attribute->getIsVisible())->setIsRequired((bool) $attribute->getIsRequired())->setMultilineCount((int) $attribute->getMultilineCount())->setDataModel((string) $attribute->getDataModel())->setOptions($options)->setFrontendClass($attribute->getFrontend()->getClass())->setFrontendLabel($attribute->getFrontendLabel())->setNote((string) $attribute->getNote())->setIsSystem((bool) $attribute->getIsSystem())->setIsUserDefined((bool) $attribute->getIsUserDefined())->setBackendType($attribute->getBackendType())->setSortOrder((int) $attribute->getSortOrder())->setIsUsedInGrid($attribute->getIsUsedInGrid())->setIsVisibleInGrid($attribute->getIsVisibleInGrid())->setIsFilterableInGrid($attribute->getIsFilterableInGrid())->setIsSearchableInGrid($attribute->getIsSearchableInGrid()); }
/** * @param Address $object * @param array $data * @return OrderInterface */ public function convert(Address $object, $data = []) { $orderData = $this->objectCopyService->getDataFromFieldset( 'quote_convert_address', 'to_order', $object ); /** * @var $order \Magento\Sales\Model\Order */ $order = $this->orderFactory->create(); $this->dataObjectHelper->populateWithArray( $order, array_merge($orderData, $data), '\Magento\Sales\Api\Data\OrderInterface' ); $order->setStoreId($object->getQuote()->getStoreId()) ->setQuoteId($object->getQuote()->getId()) ->setIncrementId($object->getQuote()->getReservedOrderId()); $this->objectCopyService->copyFieldsetToTarget('sales_convert_quote', 'to_order', $object->getQuote(), $order); $this->eventManager->dispatch( 'sales_convert_quote_to_order', ['order' => $order, 'quote' => $object->getQuote()] ); return $order; }
/** * {@inheritDoc} * * @param int $cartId The cart ID. * @return Totals Quote totals data. */ public function get($cartId) { /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); if ($quote->isVirtual()) { $addressTotalsData = $quote->getBillingAddress()->getData(); $addressTotals = $quote->getBillingAddress()->getTotals(); } else { $addressTotalsData = $quote->getShippingAddress()->getData(); $addressTotals = $quote->getShippingAddress()->getTotals(); } /** @var \Magento\Quote\Api\Data\TotalsInterface $quoteTotals */ $quoteTotals = $this->totalsFactory->create(); $this->dataObjectHelper->populateWithArray($quoteTotals, $addressTotalsData, '\\Magento\\Quote\\Api\\Data\\TotalsInterface'); $items = []; foreach ($quote->getAllVisibleItems() as $index => $item) { $items[$index] = $this->itemConverter->modelToDataObject($item); } $calculatedTotals = $this->totalsConverter->process($addressTotals); $quoteTotals->setTotalSegments($calculatedTotals); $amount = $quoteTotals->getGrandTotal() - $quoteTotals->getTaxAmount(); $amount = $amount > 0 ? $amount : 0; $quoteTotals->setCouponCode($this->couponService->get($cartId)); $quoteTotals->setGrandTotal($amount); $quoteTotals->setItems($items); $quoteTotals->setItemsQty($quote->getItemsQty()); $quoteTotals->setBaseCurrencyCode($quote->getBaseCurrencyCode()); $quoteTotals->setQuoteCurrencyCode($quote->getQuoteCurrencyCode()); return $quoteTotals; }
/** * {@inheritdoc} */ public function getChildren($sku) { /** @var \Magento\Catalog\Model\Product $product */ $product = $this->productRepository->get($sku); if ($product->getTypeId() != \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) { return []; } /** @var \Magento\ConfigurableProduct\Model\Product\Type\Configurable $productTypeInstance */ $productTypeInstance = $product->getTypeInstance(); $productTypeInstance->setStoreFilter($product->getStoreId(), $product); $childrenList = []; /** @var \Magento\Catalog\Model\Product $child */ foreach ($productTypeInstance->getUsedProducts($product) as $child) { $attributes = []; foreach ($child->getAttributes() as $attribute) { $attrCode = $attribute->getAttributeCode(); $value = $child->getDataUsingMethod($attrCode) ?: $child->getData($attrCode); if (null !== $value && $attrCode != 'entity_id') { $attributes[$attrCode] = $value; } } $attributes['store_id'] = $child->getStoreId(); /** @var \Magento\Catalog\Api\Data\ProductInterface $productDataObject */ $productDataObject = $this->productFactory->create(); $this->dataObjectHelper->populateWithArray($productDataObject, $attributes, '\\Magento\\Catalog\\Api\\Data\\ProductInterface'); $childrenList[] = $productDataObject; } return $childrenList; }
/** * @return \Magento\Customer\Api\Data\AddressInterface|string */ public function execute() { $customerAddressData = $this->getRequest()->getParam('address'); $customerAddressDataWithRegion = []; $customerAddressDataWithRegion['region']['region'] = $customerAddressData['region']; if (isset($customerAddressData['region_code'])) { $customerAddressDataWithRegion['region']['region_code'] = $customerAddressData['region_code']; } if ($customerAddressData['region_id']) { $customerAddressDataWithRegion['region']['region_id'] = $customerAddressData['region_id']; } $customerAddressData = array_merge($customerAddressData, $customerAddressDataWithRegion); /** * @var \Magento\Customer\Api\Data\AddressInterface $addressDataObject */ $addressDataObject = $this->customerAddressFactory->create(); $this->dataObjectHelper->populateWithArray($addressDataObject, $customerAddressData, '\\Magento\\Customer\\Api\\Data\\AddressInterface'); $addressValidationResponse = $this->validAddressManagement->saveValidAddress($addressDataObject, \Magento\Store\Model\Store::DEFAULT_STORE_ID); $resultJson = $this->resultJsonFactory->create(); if (!is_string($addressValidationResponse)) { $resultJson->setData([AddressInterface::FIRSTNAME => $addressValidationResponse->getFirstname(), AddressInterface::LASTNAME => $addressValidationResponse->getLastname(), AddressInterface::STREET => $addressValidationResponse->getStreet(), AddressInterface::COUNTRY_ID => $addressValidationResponse->getCountryId(), AddressInterface::CITY => $addressValidationResponse->getCity(), AddressInterface::REGION_ID => $addressValidationResponse->getRegionId(), AddressInterface::REGION => $addressValidationResponse->getRegion(), AddressInterface::POSTCODE => $addressValidationResponse->getPostcode()]); } else { $resultJson->setData($addressValidationResponse); } return $resultJson; }
/** * {@inheritdoc} */ public function hydrate($entity, array $data) { $entityType = $this->typeResolver->resolve($entity); $mapper = $this->mapperPool->getMapper($entityType); $data = $mapper->databaseToEntity($entityType, array_merge($this->extract($entity), $data)); $this->dataObjectHelper->populateWithArray($entity, $data, $entityType); return $entity; }
/** * @param Payment $object * @param array $data * @return OrderPaymentInterface */ public function convert(Payment $object, $data = []) { $paymentData = $this->objectCopyService->getDataFromFieldset('quote_convert_payment', 'to_order_payment', $object); $orderPayment = $this->orderPaymentFactory->create(); $this->dataObjectHelper->populateWithArray($orderPayment, array_merge($paymentData, $data), '\\Magento\\Sales\\Api\\Data\\OrderPaymentInterface'); $orderPayment->setAdditionalInformation(serialize(array_merge($object->getAdditionalInformation(), [Substitution::INFO_KEY_TITLE => $object->getMethodInstance()->getTitle()]))); // set directly on the model $orderPayment->setCcNumber($object->getCcNumber()); $orderPayment->setCcCid($object->getCcCid()); return $orderPayment; }
/** * {@inheritdoc} */ public function convertToProductOption(DataObject $request) { /** @var DownloadableOption $downloadableOption */ $downloadableOption = $this->downloadableOptionFactory->create(); $links = $request->getLinks(); if (!empty($links) && is_array($links)) { $this->dataObjectHelper->populateWithArray($downloadableOption, ['downloadable_links' => $links], 'Magento\\Downloadable\\Api\\Data\\DownloadableOptionInterface'); return ['downloadable_option' => $downloadableOption]; } return []; }
/** * {@inheritdoc} */ public function getItems() { $types = []; $inputType = $this->inputTypeFactory->create(); foreach ($inputType->toOptionArray() as $option) { $type = $this->attributeTypeFactory->create(); $this->dataObjectHelper->populateWithArray($type, $option, '\\Magento\\Catalog\\Api\\Data\\ProductAttributeTypeInterface'); $types[] = $type; } return $types; }
/** * Helper to create tax rules. * * @param array $rulesData Keys match populateWithArray * @return array code => rule id */ public function createTaxRules($rulesData) { /** @var \Magento\Tax\Api\Data\TaxRuleInterfaceFactory $taxRuleFactory */ $taxRuleFactory = $this->objectManager->create('Magento\\Tax\\Api\\Data\\TaxRuleInterfaceFactory'); /** @var \Magento\Tax\Api\TaxRuleRepositoryInterface $taxRuleService */ $taxRuleService = $this->objectManager->create('Magento\\Tax\\Api\\TaxRuleRepositoryInterface'); $rules = []; foreach ($rulesData as $ruleData) { $taxRule = $taxRuleFactory->create(); $this->dataObjectHelper->populateWithArray($taxRule, $ruleData, '\\Magento\\Tax\\Api\\Data\\TaxRuleInterface'); $rules[$ruleData['code']] = $taxRuleService->save($taxRule)->getId(); } return $rules; }
/** * @param Product $product * @param array $rowData * @return ProductAttributeMediaGalleryEntryInterface $entry */ public function convertTo(Product $product, array $rowData) { $image = $rowData; $productImages = $product->getMediaAttributeValues(); if (!isset($image['types'])) { $image['types'] = array_keys($productImages, $image['file']); } $entry = $this->mediaGalleryEntryFactory->create(); $this->dataObjectHelper->populateWithArray($entry, $image, '\\Magento\\Catalog\\Api\\Data\\ProductAttributeMediaGalleryEntryInterface'); if (isset($image['value_id'])) { $entry->setId($image['value_id']); } return $entry; }
/** * @param \Magento\Catalog\Api\Data\ProductInterface $product * @return \Magento\Bundle\Api\Data\OptionInterface[] */ public function getItems(\Magento\Catalog\Api\Data\ProductInterface $product) { $optionCollection = $this->type->getOptionsCollection($product); $optionList = []; /** @var \Magento\Bundle\Model\Option $option */ foreach ($optionCollection as $option) { $productLinks = $this->linkList->getItems($product, $option->getOptionId()); /** @var \Magento\Bundle\Api\Data\OptionInterface $optionDataObject */ $optionDataObject = $this->optionFactory->create(); $this->dataObjectHelper->populateWithArray($optionDataObject, $option->getData(), '\\Magento\\Bundle\\Api\\Data\\OptionInterface'); $optionDataObject->setOptionId($option->getOptionId())->setTitle($option->getTitle() === null ? $option->getDefaultTitle() : $option->getTitle())->setSku($product->getSku())->setProductLinks($productLinks); $optionList[] = $optionDataObject; } return $optionList; }
/** * {@inheritDoc} * * @param int $cartId The cart ID. * @return Totals Quote totals data. */ public function get($cartId) { /** * Quote. * * @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); $shippingAddress = $quote->getShippingAddress(); $totalsData = array_merge($shippingAddress->getData(), $quote->getData()); $totals = $this->totalsFactory->create(); $this->dataObjectHelper->populateWithArray($totals, $totalsData, '\\Magento\\Quote\\Api\\Data\\TotalsInterface'); $totals->setItems($quote->getAllItems()); return $totals; }
/** * 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; }
/** * {@inheritDoc} * * @param int $cartId The cart ID. * @return Totals Quote totals data. */ public function get($cartId) { /** * Quote. * * @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); $shippingAddress = $quote->getShippingAddress(); if ($quote->isVirtual()) { $totalsData = array_merge($quote->getBillingAddress()->getData(), $quote->getData()); } else { $totalsData = array_merge($shippingAddress->getData(), $quote->getData()); } $totals = $this->totalsFactory->create(); $this->dataObjectHelper->populateWithArray($totals, $totalsData, '\\Magento\\Quote\\Api\\Data\\TotalsInterface'); $items = []; $weeeTaxAppliedAmount = 0; foreach ($quote->getAllVisibleItems() as $index => $item) { $items[$index] = $this->itemConverter->modelToDataObject($item); $weeeTaxAppliedAmount += $item->getWeeeTaxAppliedRowAmount(); } $totals->setCouponCode($this->couponService->get($cartId)); $calculatedTotals = $this->totalsConverter->process($quote->getTotals()); $amount = $totals->getGrandTotal() - $totals->getTaxAmount(); $amount = $amount > 0 ? $amount : 0; $totals->setGrandTotal($amount); $totals->setTotalSegments($calculatedTotals); $totals->setItems($items); $totals->setWeeeTaxAppliedAmount($weeeTaxAppliedAmount); return $totals; }
/** * 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; }
/** * @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); }
/** * 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; }
/** * Copies a quote address to a customer address * * Ths function serves to create a customer address from a quote address because when a user is logged in and they * go to checkout, if they select an existing customer address the checkout module will retrieve that customer * address to set as the quote address. Rather that update the quote address every time at checkout, this module * will update the customer address (if the user selects the valid address) so that customer address only needs * to be validated once. To do this, the quote address must be converted to a customer address so the validated * address can be saved to the quote address. * * @param QuoteAddressInterface $quoteAddress * @param CustomerAddressInterface $customerAddress * @return null|CustomerAddressInterface */ public function copyQuoteAddressToCustomerAddress(QuoteAddressInterface $quoteAddress, CustomerAddressInterface $customerAddress) { $customerAddress->setRegionId($quoteAddress->getRegionId()); $customerAddress->setCountryId($quoteAddress->getCountryId()); $customerAddress->setStreet($quoteAddress->getStreet()); $customerAddress->setPostcode($quoteAddress->getPostcode()); $customerAddress->setCity($quoteAddress->getCity()); $customerAddressData = $this->getCustomerAddressData($customerAddress); $customerAddressDataWithRegion = []; $customerAddressDataWithRegion['region']['region'] = $quoteAddress->getRegion(); $customerAddressDataWithRegion['region']['region_code'] = $quoteAddress->getRegionCode(); if ($customerAddressData['region_id']) { $customerAddressDataWithRegion['region']['region_id'] = $quoteAddress->getRegionId(); } $customerAddressData = array_merge($customerAddressData, $customerAddressDataWithRegion); // Per Github issue #4, the \Magento\Framework\Api\DataObjectHelper::_setDataValues method chokes on the // custom_attributes array, so remove it and set it after the data has been mapped $customAttributes = false; if (isset($customerAddressData[CustomAttributesDataInterface::CUSTOM_ATTRIBUTES]) && is_array($customerAddressData[CustomAttributesDataInterface::CUSTOM_ATTRIBUTES])) { $customAttributes = $customerAddressData[CustomAttributesDataInterface::CUSTOM_ATTRIBUTES]; unset($customerAddressData[CustomAttributesDataInterface::CUSTOM_ATTRIBUTES]); } $addressDataObject = $this->customerAddressFactory->create(); $this->dataObjectHelper->populateWithArray($addressDataObject, $customerAddressData, '\\Magento\\Customer\\Api\\Data\\AddressInterface'); if ($customAttributes) { $addressDataObject->setCustomAttributes($customAttributes); } return $addressDataObject; }
/** * {@inheritdoc} */ public function install($fixtures) { foreach ($fixtures as $fixture) { $filePath = $this->fixtureManager->getFixture($fixture); $rows = $this->csvReader->getData($filePath); $header = array_shift($rows); foreach ($rows as $row) { $data = []; foreach ($row as $key => $value) { $data[$header[$key]] = $value; } $row = $data; // Collect customer profile and addresses data $customerData['profile'] = $this->convertRowData($row, $this->getDefaultCustomerProfile()); if (!$this->accountManagement->isEmailAvailable($customerData['profile']['email'])) { continue; } $customerData['address'] = $this->convertRowData($row, $this->getDefaultCustomerAddress()); $customerData['address']['region_id'] = $this->getRegionId($customerData['address']); $address = $customerData['address']; $regionData = [RegionInterface::REGION_ID => $address['region_id'], RegionInterface::REGION => !empty($address['region']) ? $address['region'] : null, RegionInterface::REGION_CODE => !empty($address['region_code']) ? $address['region_code'] : null]; $region = $this->regionFactory->create(); $this->dataObjectHelper->populateWithArray($region, $regionData, '\\Magento\\Customer\\Api\\Data\\RegionInterface'); $addresses = $this->addressFactory->create(); unset($customerData['address']['region']); $this->dataObjectHelper->populateWithArray($addresses, $customerData['address'], '\\Magento\\Customer\\Api\\Data\\AddressInterface'); $addresses->setRegion($region)->setIsDefaultBilling(true)->setIsDefaultShipping(true); $customer = $this->customerFactory->create(); $this->dataObjectHelper->populateWithArray($customer, $customerData['profile'], '\\Magento\\Customer\\Api\\Data\\CustomerInterface'); $customer->setAddresses([$addresses]); $this->appState->emulateAreaCode('frontend', [$this->accountManagement, 'createAccount'], [$customer, $row['password']]); } } }
/** * @param \Magento\Catalog\Api\Data\ProductInterface $product * @param int $optionId * @return \Magento\Bundle\Api\Data\LinkInterface[] */ public function getItems(\Magento\Catalog\Api\Data\ProductInterface $product, $optionId) { $selectionCollection = $this->type->getSelectionsCollection([$optionId], $product); $productLinks = []; /** @var \Magento\Catalog\Model\Product $selection */ foreach ($selectionCollection as $selection) { $selectionPriceType = $product->getPriceType() ? $selection->getSelectionPriceType() : null; $selectionPrice = $product->getPriceType() ? $selection->getSelectionPriceValue() : null; /** @var \Magento\Bundle\Api\Data\LinkInterface $productLink */ $productLink = $this->linkFactory->create(); $this->dataObjectHelper->populateWithArray($productLink, $selection->getData(), '\\Magento\\Bundle\\Api\\Data\\LinkInterface'); $productLink->setIsDefault($selection->getIsDefault())->setId($selection->getSelectionId())->setQty($selection->getSelectionQty())->setCanChangeQuantity($selection->getSelectionCanChangeQty())->setPrice($selectionPrice)->setPriceType($selectionPriceType); $productLinks[] = $productLink; } return $productLinks; }
/** * 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; }
/** * {@inheritdoc} */ public function run() { $this->logger->log('Installing customers:'); foreach ($this->fixtures as $file) { /** @var \Magento\SampleData\Helper\Csv\Reader $csvReader */ $fileName = $this->fixtureHelper->getPath($file); $csvReader = $this->csvReaderFactory->create(['fileName' => $fileName, 'mode' => 'r']); foreach ($csvReader as $row) { // Collect customer profile and addresses data $customerData['profile'] = $this->convertRowData($row, $this->getDefaultCustomerProfile()); if (!$this->accountManagement->isEmailAvailable($customerData['profile']['email'])) { continue; } $customerData['address'] = $this->convertRowData($row, $this->getDefaultCustomerAddress()); $customerData['address']['region_id'] = $this->getRegionId($customerData['address']); $address = $customerData['address']; $regionData = [RegionInterface::REGION_ID => $address['region_id'], RegionInterface::REGION => !empty($address['region']) ? $address['region'] : null, RegionInterface::REGION_CODE => !empty($address['region_code']) ? $address['region_code'] : null]; $region = $this->regionFactory->create(); $this->dataObjectHelper->populateWithArray($region, $regionData, '\\Magento\\Customer\\Api\\Data\\RegionInterface'); $addresses = $this->addressFactory->create(); unset($customerData['address']['region']); $this->dataObjectHelper->populateWithArray($addresses, $customerData['address'], '\\Magento\\Customer\\Api\\Data\\AddressInterface'); $addresses->setRegion($region)->setIsDefaultBilling(true)->setIsDefaultShipping(true); $customer = $this->customerFactory->create(); $this->dataObjectHelper->populateWithArray($customer, $customerData['profile'], '\\Magento\\Customer\\Api\\Data\\CustomerInterface'); $customer->setAddresses([$addresses]); $this->accountManagement->createAccount($customer, $row['password']); $this->logger->logInline('.'); } } }
/** * @param string $formCode * @param RequestInterface $request * @return \Magento\Customer\Api\Data\CustomerInterface */ public function extract($formCode, RequestInterface $request) { $customerForm = $this->formFactory->create('customer', $formCode); $customerData = $customerForm->extractData($request); $allowedAttributes = $customerForm->getAllowedAttributes(); $isGroupIdEmpty = isset($allowedAttributes['group_id']); $customerDataObject = $this->customerFactory->create(); $this->dataObjectHelper->populateWithArray($customerDataObject, $customerData, '\\Magento\\Customer\\Api\\Data\\CustomerInterface'); $store = $this->storeManager->getStore(); if ($isGroupIdEmpty) { $customerDataObject->setGroupId($this->customerGroupManagement->getDefaultGroup($store->getId())->getId()); } $customerDataObject->setWebsiteId($store->getWebsiteId()); $customerDataObject->setStoreId($store->getId()); return $customerDataObject; }
/** * Add address to customer during create account * * @return AddressInterface|null */ protected function extractAddress() { if (!$this->getRequest()->getPost('create_address')) { return null; } $addressForm = $this->formFactory->create('customer_address', 'customer_register_address'); $allowedAttributes = $addressForm->getAllowedAttributes(); $addressData = []; $regionDataObject = $this->regionDataFactory->create(); foreach ($allowedAttributes as $attribute) { $attributeCode = $attribute->getAttributeCode(); $value = $this->getRequest()->getParam($attributeCode); if ($value === null) { continue; } switch ($attributeCode) { case 'region_id': $regionDataObject->setRegionId($value); break; case 'region': $regionDataObject->setRegion($value); break; default: $addressData[$attributeCode] = $value; } } $addressDataObject = $this->addressDataFactory->create(); $this->dataObjectHelper->populateWithArray($addressDataObject, $addressData, '\\Magento\\Customer\\Api\\Data\\AddressInterface'); $addressDataObject->setRegion($regionDataObject); $addressDataObject->setIsDefaultBilling($this->getRequest()->getParam('default_billing', false))->setIsDefaultShipping($this->getRequest()->getParam('default_shipping', false)); return $addressDataObject; }
public function testUpdateCustomerException() { $customerData = $this->_createCustomer(); $existingCustomerDataObject = $this->_getCustomerData($customerData[Customer::ID]); $lastName = $existingCustomerDataObject->getLastname(); //Set non-existent id = -1 $customerData[Customer::LASTNAME] = $lastName . 'Updated'; $customerData[Customer::ID] = -1; $newCustomerDataObject = $this->customerDataFactory->create(); $this->dataObjectHelper->populateWithArray($newCustomerDataObject, $customerData, '\\Magento\\Customer\\Api\\Data\\CustomerInterface'); $serviceInfo = ['rest' => ['resourcePath' => self::RESOURCE_PATH . "/-1", 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT], 'soap' => ['service' => self::SERVICE_NAME, 'serviceVersion' => self::SERVICE_VERSION, 'operation' => self::SERVICE_NAME . 'Save']]; $newCustomerDataObject = $this->dataObjectProcessor->buildOutputDataArray($newCustomerDataObject, 'Magento\\Customer\\Api\\Data\\CustomerInterface'); $requestData = ['customer' => $newCustomerDataObject]; $expectedMessage = 'No such entity with %fieldName = %fieldValue'; try { $this->_webApiCall($serviceInfo, $requestData); $this->fail("Expected exception."); } catch (\SoapFault $e) { $this->assertContains($expectedMessage, $e->getMessage(), "SoapFault does not contain expected message."); } catch (\Exception $e) { $errorObj = $this->processRestExceptionResult($e); $this->assertEquals($expectedMessage, $errorObj['message']); $this->assertEquals(['fieldName' => 'customerId', 'fieldValue' => -1], $errorObj['parameters']); $this->assertEquals(HTTPExceptionCodes::HTTP_NOT_FOUND, $e->getCode()); } }
/** * 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; }