/** * exec post user question * @return void * @throws \Exception */ public function execute() { $post = $this->getRequest()->getPostValue(); if (!$post) { $this->_redirect('*/*/'); return; } $this->inlineTranslation->suspend(); try { $postObject = new \Magento\Framework\DataObject(); $postObject->setData($post); $error = false; /* validate-checking */ if (!\Zend_Validate::is(trim($post['name']), 'NotEmpty')) { $error = true; } if (!\Zend_Validate::is(trim($post['comment']), 'NotEmpty')) { $error = true; } if (!\Zend_Validate::is(trim($post['email']), 'EmailAddress')) { $error = true; } /** * setting custome param * add new elements : product_name & product_sku information */ if (array_key_exists('product_name', $post) && array_key_exists('product_sku', $post)) { if (!\Zend_Validate::is(trim($post['product_name']), 'NotEmpty')) { $error = true; } if (!\Zend_Validate::is(trim($post['product_sku']), 'NotEmpty')) { $error = true; } } /* this column, hideit, is not so sure for using during this process, so I close it temporarily.... if (!\Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) { $error = true; }*/ if ($error) { throw new \Exception(); //todo } /* Transport email to user */ $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; $transport = $this->_transportBuilder->setTemplateIdentifier($this->scopeConfig->getValue(self::XML_PATH_EMAIL_TEMPLATE, $storeScope))->setTemplateOptions(['area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE, 'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID])->setTemplateVars(['data' => $postObject])->setFrom($this->scopeConfig->getValue(self::XML_PATH_EMAIL_SENDER, $storeScope))->addTo($this->scopeConfig->getValue(self::XML_PATH_EMAIL_RECIPIENT, $storeScope))->setReplyTo($post['email'])->getTransport(); $transport->sendMessage(); $this->inlineTranslation->resume(); $this->messageManager->addSuccess(__('Hi there, this is Optoma, and thanks for your contacting with us about your questions by nice information, and we will notify you very soon, see you next time~')); /* redirect to new page :: pending */ $this->_redirect('contact/index'); return; } catch (\Exception $e) { /* Error Log should be noted here */ $this->inlineTranslation->resume(); $this->messageManager->addError(__('Hi there, this is Optoma, so sorry for that we just cant\'t process your request right now, please wait a minutes and we will contact y ou very soon~')); $this->_redirect('contact/index'); //todo return; } }
/** * Check that grid does not contain unnecessary totals row * * @param $from string * @param $to string * @param $expectedResult bool * * @dataProvider getCountTotalsDataProvider * @magentoDataFixture Magento/Reports/_files/orders.php */ public function testGetCountTotals($from, $to, $expectedResult) { $block = $this->_createBlock(); $filterData = new \Magento\Framework\DataObject(); $filterData->setReportType('updated_at_order'); $filterData->setPeriodType('day'); $filterData->setData('from', $from); $filterData->setData('to', $to); $block->setFilterData($filterData); $block->toHtml(); $this->assertEquals($expectedResult, $block->getCountTotals()); }
/** * Post user question * * @return void * @throws \Exception */ public function execute() { $post = $this->getRequest()->getPostValue(); if (!$post) { $this->_redirect('*/*/'); return; } $this->inlineTranslation->suspend(); try { $postObject = new \Magento\Framework\DataObject(); $postObject->setData($post); $error = false; if (!\Zend_Validate::is(trim($post['contact_email']), 'EmailAddress')) { $error = true; } if (!\Zend_Validate::is(trim($post['contact_question']), 'NotEmpty')) { $error = true; } if ($error) { throw new \Exception(); } $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; $transport = $this->_transportBuilder->setTemplateIdentifier($this->scopeConfig->getValue(self::XML_PATH_EMAIL_TEMPLATE, $storeScope))->setTemplateOptions(['area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE, 'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID])->setTemplateVars(['data' => $postObject])->setFrom($this->scopeConfig->getValue(self::XML_PATH_EMAIL_SENDER, $storeScope))->addTo($this->scopeConfig->getValue(self::XML_PATH_EMAIL_RECIPIENT, $storeScope))->setReplyTo($post['contact_email'])->getTransport(); $transport->sendMessage(); $this->inlineTranslation->resume(); $this->messageManager->addSuccess(__('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.')); $this->_redirect('delivery-charges'); return; } catch (\Exception $e) { $this->inlineTranslation->resume(); $this->messageManager->addError(__('We can\'t process your request right now. Sorry, that\'s all we know.')); $this->_redirect('delivery-charges'); return; } }
/** * @param array $data * @param bool $result * @param array $messages * * @covers \Magento\Framework\View\Design\Theme\Validator::validate * @dataProvider dataProviderValidate */ public function testValidate(array $data, $result, array $messages) { /** @var $themeMock \Magento\Framework\DataObject */ $themeMock = new \Magento\Framework\DataObject(); $themeMock->setData($data); $validator = new \Magento\Framework\View\Design\Theme\Validator(); $this->assertEquals($result, $validator->validate($themeMock)); $this->assertEquals($messages, $validator->getErrorMessages()); }
public function execute() { $redirectUrl = $this->getUrl('wirecardcheckoutpage/fundtransfer/transfer'); if (!($data = $this->getRequest()->getPostValue())) { $this->_redirect($redirectUrl); return; } $postObject = new \Magento\Framework\DataObject(); $postObject->setData($data); $this->_session->setWirecardCheckoutPageFundTrandsferFormData($postObject); try { $return = $this->_fundTransferModel->sendrequest($postObject); if ($return->hasFailed()) { $this->messageManager->addErrorMessage($return->getError()->getMessage()); } else { $this->_logger->debug(__METHOD__ . ':' . print_r($postObject->getData(), true)); $this->_session->unsWirecardCheckoutPageFundTrandsferFormData(); $this->messageManager->addNoticeMessage($this->_dataHelper->__('Fund transfer submitted successfully!')); $this->messageManager->addNoticeMessage($this->_dataHelper->__('Credit number' . ':' . $return->getCreditNumber())); } } catch (\Exception $e) { $this->messageManager->addErrorMessage($e->getMessage()); } $this->_redirect($redirectUrl); }
public function sendNotification($data) { if (!$data) { return false; } $this->inlineTranslation->suspend(); try { $postObject = new \Magento\Framework\DataObject(); $postObject->setData($data); $error = false; $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; /* $from = [ 'name' => '', 'email' => '' ];*/ $email_template = $this->scopeConfig->getValue('cadou/email/template'); if (empty($email_template)) { $email_template = (string) 'cadou_email_template'; // this code we have mentioned in the email_templates.xml } $transport = $this->_transportBuilder->setTemplateIdentifier($email_template)->setTemplateOptions(['area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE, 'store' => $this->storeManager->getDefaultStoreView()->getId()])->setTemplateVars(['data' => $postObject, 'subject' => $data['productname']])->setFrom($this->scopeConfig->getValue('contact/email/sender_email_identity', $storeScope))->addTo($data['email'], isset($data['fullname']) ? $data['fullname'] : $data['name'])->getTransport(); $transport->sendMessage(); $this->inlineTranslation->resume(); /*$this->messageManager->addSuccess( __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.') );*/ return TRUE; } catch (\Exception $e) { $this->inlineTranslation->resume(); $this->messageManager->addError(__('We can\'t process your request right now. Sorry, that\'s all we know.' . $e->getMessage())); return FALSE; } }
/** * Convert actions to html * * @param array $actions * @return string */ protected function _actionsToHtml(array $actions) { $html = []; $attributesObject = new \Magento\Framework\DataObject(); foreach ($actions as $action) { $attributesObject->setData($action['@']); $html[] = '<a ' . $attributesObject->serialize() . '>' . $action['#'] . '</a>'; } return implode(' <span class="separator"> | </span> ', $html); }
/** * Test getMediaGalleryDataJson() */ public function testGetMediaGalleryDataJson() { $mediaGalleryData = new \Magento\Framework\DataObject(); $data = [['media_type' => 'external-video', 'video_url' => 'http://magento.ce/pub/media/catalog/product/9/b/9br6ujuthnc.jpg', 'is_base' => true], ['media_type' => 'external-video', 'video_url' => 'https://www.youtube.com/watch?v=QRYX7GIvdLE', 'is_base' => false], ['media_type' => '', 'video_url' => '', 'is_base' => null]]; $mediaGalleryData->setData($data); $this->coreRegistry->expects($this->any())->method('registry')->willReturn($this->productModelMock); $typeInstance = $this->getMock('\\Magento\\Catalog\\Model\\Product\\Type\\AbstractType', [], [], '', false); $typeInstance->expects($this->any())->method('getStoreFilter')->willReturn('_cache_instance_store_filter'); $this->productModelMock->expects($this->any())->method('getTypeInstance')->willReturn($typeInstance); $this->productModelMock->expects($this->any())->method('getMediaGalleryImages')->willReturn([$mediaGalleryData]); $this->gallery->getMediaGalleryDataJson(); }
/** * Load data * * @param bool $printQuery * @param bool $logQuery * @return $this * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function loadData($printQuery = false, $logQuery = false) { if (!count($this->_items)) { $data = [['id' => 'sales', 'report' => __('Orders'), 'comment' => __('Total Ordered Report'), 'updated_at' => $this->_getUpdatedAt(\Magento\Reports\Model\Flag::REPORT_ORDER_FLAG_CODE)], ['id' => 'tax', 'report' => __('Tax'), 'comment' => __('Order Taxes Report Grouped by Tax Rates'), 'updated_at' => $this->_getUpdatedAt(\Magento\Reports\Model\Flag::REPORT_TAX_FLAG_CODE)], ['id' => 'shipping', 'report' => __('Shipping'), 'comment' => __('Total Shipped Report'), 'updated_at' => $this->_getUpdatedAt(\Magento\Reports\Model\Flag::REPORT_SHIPPING_FLAG_CODE)], ['id' => 'invoiced', 'report' => __('Total Invoiced'), 'comment' => __('Total Invoiced VS Paid Report'), 'updated_at' => $this->_getUpdatedAt(\Magento\Reports\Model\Flag::REPORT_INVOICE_FLAG_CODE)], ['id' => 'refunded', 'report' => __('Total Refunded'), 'comment' => __('Total Refunded Report'), 'updated_at' => $this->_getUpdatedAt(\Magento\Reports\Model\Flag::REPORT_REFUNDED_FLAG_CODE)], ['id' => 'coupons', 'report' => __('Coupons'), 'comment' => __('Promotion Coupons Usage Report'), 'updated_at' => $this->_getUpdatedAt(\Magento\Reports\Model\Flag::REPORT_COUPONS_FLAG_CODE)], ['id' => 'bestsellers', 'report' => __('Bestsellers'), 'comment' => __('Products Bestsellers Report'), 'updated_at' => $this->_getUpdatedAt(\Magento\Reports\Model\Flag::REPORT_BESTSELLERS_FLAG_CODE)], ['id' => 'viewed', 'report' => __('Most Viewed'), 'comment' => __('Most Viewed Products Report'), 'updated_at' => $this->_getUpdatedAt(\Magento\Reports\Model\Flag::REPORT_PRODUCT_VIEWED_FLAG_CODE)]]; foreach ($data as $value) { $item = new \Magento\Framework\DataObject(); $item->setData($value); $this->addItem($item); } } return $this; }
/** * Test that Tax Rate applied only once * * @magentoAppIsolation enabled * @magentoDataFixture Magento/Tax/_files/tax_classes.php */ public function testGetRate() { /** @var $objectManager \Magento\TestFramework\ObjectManager */ $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $taxRule = $objectManager->get('Magento\\Framework\\Registry')->registry('_fixture/Magento_Tax_Model_Calculation_Rule'); $customerTaxClasses = $taxRule->getCustomerTaxClassIds(); $productTaxClasses = $taxRule->getProductTaxClassIds(); $taxRate = $objectManager->get('Magento\\Framework\\Registry')->registry('_fixture/Magento_Tax_Model_Calculation_Rate'); $data = new \Magento\Framework\DataObject(); $data->setData(['tax_country_id' => 'US', 'taxregion_id' => '12', 'tax_postcode' => '5555', 'customer_class_id' => $customerTaxClasses[0], 'product_class_id' => $productTaxClasses[0]]); $taxCalculation = $objectManager->get('Magento\\Tax\\Model\\ResourceModel\\Calculation'); $this->assertEquals($taxRate->getRateIds(), $taxCalculation->getRate($data)); }
/** * Render options array as a HTML string * * @param array $actions * @return string */ protected function _actionsToHtml(array $actions = []) { $html = []; $attributesObject = new \Magento\Framework\DataObject(); if (empty($actions)) { $actions = $this->_actions; } foreach ($actions as $action) { $attributesObject->setData($action['@']); $html[] = '<a ' . $attributesObject->serialize() . '>' . $action['#'] . '</a>'; } return implode('', $html); }
/** * @param array $indexValues * @param string $expectedResult * @dataProvider renderDataProvider */ public function testRender($indexValues, $expectedResult) { $context = $this->getMockBuilder('\\Magento\\Backend\\Block\\Context')->disableOriginalConstructor()->getMock(); $model = new \Magento\Indexer\Block\Backend\Grid\Column\Renderer\Status($context); $obj = new \Magento\Framework\DataObject(); $obj->setGetter(null); $obj->setDefault(''); $obj->setValue(''); $obj->setIndex($indexValues[0]); $obj->setData($indexValues[0], $indexValues[0]); $model->setColumn($obj); $model->setIndex($indexValues[0]); $result = $model->render($obj); $this->assertEquals($result, '<span class="' . $expectedResult['class'] . '"><span>' . $expectedResult['text'] . '</span></span>'); }
public function execute() { $redirectUrl = $this->getUrl('wirecardcheckoutpage/support/contact'); if (!($data = $this->getRequest()->getPostValue())) { $this->_redirect($redirectUrl); return; } $postObject = new \Magento\Framework\DataObject(); $postObject->setData($data); try { $this->_supportModel->sendrequest($postObject); $this->messageManager->addNoticeMessage($this->_dataHelper->__('Support request sent successfully!')); } catch (\Exception $e) { $this->messageManager->addErrorMessage($e->getMessage()); } $this->_redirect($redirectUrl); }
public function testUpgradeCustomerPassword() { $customerId = '1'; $password = '******'; $passwordHash = 'hash:salt:999'; $model = $this->getMockBuilder('Magento\\Customer\\Model\\Customer')->disableOriginalConstructor()->setMethods(['getId'])->getMock(); $customer = $this->getMockBuilder('Magento\\Customer\\Api\\Data\\CustomerInterface')->getMockForAbstractClass(); $customerSecure = $this->getMockBuilder('Magento\\Customer\\Model\\Data\\CustomerSecure')->disableOriginalConstructor()->setMethods(['getPasswordHash', 'setPasswordHash'])->getMock(); $model->expects($this->exactly(2))->method('getId')->willReturn($customerId); $this->customerRepository->expects($this->once())->method('getById')->with($customerId)->willReturn($customer); $this->customerRegistry->expects($this->once())->method('retrieveSecureData')->with($customerId)->willReturn($customerSecure); $customerSecure->expects($this->once())->method('getPasswordHash')->willReturn($passwordHash); $this->encryptorMock->expects($this->once())->method('validateHashVersion')->with($passwordHash)->willReturn(false); $this->encryptorMock->expects($this->once())->method('getHash')->with($password, true)->willReturn($passwordHash); $customerSecure->expects($this->once())->method('setPasswordHash')->with($passwordHash); $this->customerRepository->expects($this->once())->method('save')->with($customer); $event = new \Magento\Framework\DataObject(); $event->setData(['password' => 'password', 'model' => $model]); $observerMock = new \Magento\Framework\Event\Observer(); $observerMock->setEvent($event); $this->model->execute($observerMock); }
/** * After Save Attribute manipulation * * @param \Magento\Catalog\Model\Product $object * @return $this * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function afterSave($object) { $websiteId = $this->_storeManager->getStore($object->getStoreId())->getWebsiteId(); $isGlobal = $this->getAttribute()->isScopeGlobal() || $websiteId == 0; $priceRows = $object->getData($this->getAttribute()->getName()); if ($priceRows === null) { return $this; } $old = []; $new = []; // prepare original data for compare $origPrices = $object->getOrigData($this->getAttribute()->getName()); if (!is_array($origPrices)) { $origPrices = []; } foreach ($origPrices as $data) { if ($data['website_id'] > 0 || $data['website_id'] == '0' && $isGlobal) { $key = join('-', array_merge([$data['website_id'], $data['cust_group']], $this->_getAdditionalUniqueFields($data))); $old[$key] = $data; } } // prepare data for save foreach ($priceRows as $data) { $hasEmptyData = false; foreach ($this->_getAdditionalUniqueFields($data) as $field) { if (empty($field)) { $hasEmptyData = true; break; } } if ($hasEmptyData || !isset($data['cust_group']) || !empty($data['delete'])) { continue; } if ($this->getAttribute()->isScopeGlobal() && $data['website_id'] > 0) { continue; } if (!$isGlobal && (int) $data['website_id'] == 0) { continue; } $key = join('-', array_merge([$data['website_id'], $data['cust_group']], $this->_getAdditionalUniqueFields($data))); $useForAllGroups = $data['cust_group'] == $this->_groupManagement->getAllCustomersGroup()->getId(); $customerGroupId = !$useForAllGroups ? $data['cust_group'] : 0; $new[$key] = array_merge(['website_id' => $data['website_id'], 'all_groups' => $useForAllGroups ? 1 : 0, 'customer_group_id' => $customerGroupId, 'value' => $data['price']], $this->_getAdditionalUniqueFields($data)); } $delete = array_diff_key($old, $new); $insert = array_diff_key($new, $old); $update = array_intersect_key($new, $old); $isChanged = false; $productId = $object->getData($this->metadataPool->getMetadata(ProductInterface::class)->getLinkField()); if (!empty($delete)) { foreach ($delete as $data) { $this->_getResource()->deletePriceData($productId, null, $data['price_id']); $isChanged = true; } } if (!empty($insert)) { foreach ($insert as $data) { $price = new \Magento\Framework\DataObject($data); $price->setData($this->metadataPool->getMetadata(ProductInterface::class)->getLinkField(), $productId); $this->_getResource()->savePriceData($price); $isChanged = true; } } if (!empty($update)) { foreach ($update as $k => $v) { if ($old[$k]['price'] != $v['value']) { $price = new \Magento\Framework\DataObject(['value_id' => $old[$k]['price_id'], 'value' => $v['value']]); $this->_getResource()->savePriceData($price); $isChanged = true; } } } if ($isChanged) { $valueChangedKey = $this->getAttribute()->getName() . '_changed'; $object->setData($valueChangedKey, 1); } return $this; }
/** * @return array */ public function textExecuteFailedPlaceOrderDataProvider() { $objectFailed = new \Magento\Framework\DataObject(); $objectFailed->setData('error', true); $objectFailed->setData('error_messages', __('Cannot place order.')); return [[['method' => 'authorizenet_directpost'], IframeConfigProvider::CHECKOUT_IDENTIFIER, 1, $objectFailed]]; }
/** * Prepare fixture for exported address * * @param array $addressData * @return \Magento\Framework\DataObject */ protected function _getExportedAddressFixture(array $addressData) { $addressDataKeys = ['firstname', 'lastname', 'street', 'city', 'telephone']; $result = []; foreach ($addressDataKeys as $key) { if (isset($addressData[$key])) { $result[$key] = 'exported' . $addressData[$key]; } } $fixture = new \Magento\Framework\DataObject($result); $fixture->setExportedKeys($addressDataKeys); $fixture->setData('note', 'note'); return $fixture; }
/** * Get entity summary * * @param Product $product * @param int $storeId * @return void */ public function getEntitySummary($product, $storeId = 0) { $summaryData = $this->_summaryModFactory->create()->setStoreId($storeId)->load($product->getId()); $summary = new \Magento\Framework\DataObject(); $summary->setData($summaryData->getData()); $product->setRatingSummary($summary); }
/** * Test decorateFilter() * * @param array $attributeData * @param string $backendType * @param array $columnValue * @dataProvider decorateFilterDataProvider */ public function testDecorateFilter($attributeData, $backendType, $columnValue) { $value = ''; $attribute = new \Magento\Eav\Model\Entity\Attribute($this->modelContext, $this->registry, $this->extensionFactory, $this->customAttributeFactory, $this->eavConfig, $this->eavTypeFactory, $this->storeManager, $this->resourceHelper, $this->universalFactory, $this->optionDataFactory, $this->dataObjectProcessor, $this->dataObjectHelper, $this->localeDate, $this->reservedAttributeList, $this->localeResolver, $this->dateTimeFormatter, $this->resource, $this->resourceCollection); $attribute->setAttributeCode($attributeData['code']); $attribute->setFrontendInput($attributeData['input']); $attribute->setOptions($attributeData['options']); $attribute->setFilterOptions($attributeData['filter_options']); $attribute->setBackendType($backendType); $column = new \Magento\Framework\DataObject(); $column->setData($columnValue, 'value'); $isExport = true; $this->filter->decorateFilter($value, $attribute, $column, $isExport); }
/** * Process $buyRequest and sets its options before saving configuration to some product item. * This method is used to attach additional parameters to processed buyRequest. * * $params holds parameters of what operation must be performed: * - 'current_config', \Magento\Framework\DataObject or array - current buyRequest * that configures product in this item, used to restore currently attached files * - 'files_prefix': string[a-z0-9_] - prefix that was added at frontend to names of file inputs, * so they won't intersect with other submitted options * * @param \Magento\Framework\DataObject|array $buyRequest * @param \Magento\Framework\DataObject|array $params * @return \Magento\Framework\DataObject */ public function addParamsToBuyRequest($buyRequest, $params) { if (is_array($buyRequest)) { $buyRequest = new \Magento\Framework\DataObject($buyRequest); } if (is_array($params)) { $params = new \Magento\Framework\DataObject($params); } // Ensure that currentConfig goes as \Magento\Framework\DataObject - for easier work with it later $currentConfig = $params->getCurrentConfig(); if ($currentConfig) { if (is_array($currentConfig)) { $params->setCurrentConfig(new \Magento\Framework\DataObject($currentConfig)); } elseif (!$currentConfig instanceof \Magento\Framework\DataObject) { $params->unsCurrentConfig(); } } /* * Notice that '_processing_params' must always be object to protect processing forged requests * where '_processing_params' comes in $buyRequest as array from user input */ $processingParams = $buyRequest->getData('_processing_params'); if (!$processingParams || !$processingParams instanceof \Magento\Framework\DataObject) { $processingParams = new \Magento\Framework\DataObject(); $buyRequest->setData('_processing_params', $processingParams); } $processingParams->addData($params->getData()); return $buyRequest; }
/** * Create item object from item data * * @param string $name * @param int $qty * @param float $amount * @param null|string $identifier * @return \Magento\Framework\DataObject */ protected function _createItemFromData($name, $qty, $amount, $identifier = null) { $item = new \Magento\Framework\DataObject(['name' => $name, 'qty' => $qty, 'amount' => (double) $amount]); if ($identifier) { $item->setData('id', $identifier); } return $item; }
/** * Return widget XML configuration as \Magento\Framework\DataObject and makes some data preparations * * @param string $type Widget type * @return \Magento\Framework\DataObject */ public function getConfigAsObject($type) { $widget = $this->getWidgetByClassType($type); $object = new \Magento\Framework\DataObject(); if ($widget === null) { return $object; } $widget = $this->getAsCanonicalArray($widget); // Save all nodes to object data $object->setType($type); $object->setData($widget); // Correct widget parameters and convert its data to objects $newParams = $this->prepareWidgetParameters($object); $object->setData('parameters', $newParams); return $object; }
/** * Javascript setup object for filebrowser instance * * @return string */ public function getFilebrowserSetupObject() { $setupObject = new \Magento\Framework\DataObject(); $setupObject->setData(['newFolderPrompt' => __('New Folder Name:'), 'deleteFolderConfirmationMessage' => __('Are you sure you want to delete this folder?'), 'deleteFileConfirmationMessage' => __('Are you sure you want to delete this file?'), 'targetElementId' => $this->getTargetElementId(), 'contentsUrl' => $this->getContentsUrl(), 'onInsertUrl' => $this->getOnInsertUrl(), 'newFolderUrl' => $this->getNewfolderUrl(), 'deleteFolderUrl' => $this->getDeletefolderUrl(), 'deleteFilesUrl' => $this->getDeleteFilesUrl(), 'headerText' => $this->getHeaderText(), 'showBreadcrumbs' => true]); return $this->_jsonEncoder->encode($setupObject); }
/** * Form XML for international shipment request * As integration guide it is important to follow appropriate sequence for tags e.g.: <FromLastName /> must be * after <FromFirstName /> * * @param \Magento\Framework\DataObject $request * @return string * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ protected function _formIntlShipmentRequest(\Magento\Framework\DataObject $request) { $packageParams = $request->getPackageParams(); $height = $packageParams->getHeight(); $width = $packageParams->getWidth(); $length = $packageParams->getLength(); $girth = $packageParams->getGirth(); $packageWeight = $request->getPackageWeight(); if ($packageParams->getWeightUnits() != \Zend_Measure_Weight::POUND) { $packageWeight = $this->_carrierHelper->convertMeasureWeight($request->getPackageWeight(), $packageParams->getWeightUnits(), \Zend_Measure_Weight::POUND); } if ($packageParams->getDimensionUnits() != \Zend_Measure_Length::INCH) { $length = round($this->_carrierHelper->convertMeasureDimension($packageParams->getLength(), $packageParams->getDimensionUnits(), \Zend_Measure_Length::INCH)); $width = round($this->_carrierHelper->convertMeasureDimension($packageParams->getWidth(), $packageParams->getDimensionUnits(), \Zend_Measure_Length::INCH)); $height = round($this->_carrierHelper->convertMeasureDimension($packageParams->getHeight(), $packageParams->getDimensionUnits(), \Zend_Measure_Length::INCH)); } if ($packageParams->getGirthDimensionUnits() != \Zend_Measure_Length::INCH) { $girth = round($this->_carrierHelper->convertMeasureDimension($packageParams->getGirth(), $packageParams->getGirthDimensionUnits(), \Zend_Measure_Length::INCH)); } $container = $request->getPackagingType(); switch ($container) { case 'VARIABLE': $container = 'VARIABLE'; break; case 'FLAT RATE ENVELOPE': $container = 'FLATRATEENV'; break; case 'FLAT RATE BOX': $container = 'FLATRATEBOX'; break; case 'RECTANGULAR': $container = 'RECTANGULAR'; break; case 'NONRECTANGULAR': $container = 'NONRECTANGULAR'; break; default: $container = 'VARIABLE'; } $shippingMethod = $request->getShippingMethod(); list($fromZip5, $fromZip4) = $this->_parseZip($request->getShipperAddressPostalCode()); // the wrap node needs for remove xml declaration above $xmlWrap = $this->_xmlElFactory->create(['data' => '<?xml version = "1.0" encoding = "UTF-8"?><wrap/>']); $method = ''; $service = $this->getCode('service_to_code', $shippingMethod); if ($service == 'Priority') { $method = 'Priority'; $rootNode = 'PriorityMailIntlRequest'; $xml = $xmlWrap->addChild($rootNode); } else { if ($service == 'First Class') { $method = 'FirstClass'; $rootNode = 'FirstClassMailIntlRequest'; $xml = $xmlWrap->addChild($rootNode); } else { $method = 'Express'; $rootNode = 'ExpressMailIntlRequest'; $xml = $xmlWrap->addChild($rootNode); } } $xml->addAttribute('USERID', $this->getConfigData('userid')); $xml->addAttribute('PASSWORD', $this->getConfigData('password')); $xml->addChild('Option'); $xml->addChild('Revision', self::DEFAULT_REVISION); $xml->addChild('ImageParameters'); $xml->addChild('FromFirstName', $request->getShipperContactPersonFirstName()); $xml->addChild('FromLastName', $request->getShipperContactPersonLastName()); $xml->addChild('FromFirm', $request->getShipperContactCompanyName()); $xml->addChild('FromAddress1', $request->getShipperAddressStreet2()); $xml->addChild('FromAddress2', $request->getShipperAddressStreet1()); $xml->addChild('FromCity', $request->getShipperAddressCity()); $xml->addChild('FromState', $request->getShipperAddressStateOrProvinceCode()); $xml->addChild('FromZip5', $fromZip5); $xml->addChild('FromZip4', $fromZip4); $xml->addChild('FromPhone', $request->getShipperContactPhoneNumber()); if ($method != 'FirstClass') { if ($request->getReferenceData()) { $referenceData = $request->getReferenceData() . ' P' . $request->getPackageId(); } else { $referenceData = $request->getOrderShipment()->getOrder()->getIncrementId() . ' P' . $request->getPackageId(); } $xml->addChild('FromCustomsReference', 'Order #' . $referenceData); } $xml->addChild('ToFirstName', $request->getRecipientContactPersonFirstName()); $xml->addChild('ToLastName', $request->getRecipientContactPersonLastName()); $xml->addChild('ToFirm', $request->getRecipientContactCompanyName()); $xml->addChild('ToAddress1', $request->getRecipientAddressStreet1()); $xml->addChild('ToAddress2', $request->getRecipientAddressStreet2()); $xml->addChild('ToCity', $request->getRecipientAddressCity()); $xml->addChild('ToProvince', $request->getRecipientAddressStateOrProvinceCode()); $xml->addChild('ToCountry', $this->_getCountryName($request->getRecipientAddressCountryCode())); $xml->addChild('ToPostalCode', $request->getRecipientAddressPostalCode()); $xml->addChild('ToPOBoxFlag', 'N'); $xml->addChild('ToPhone', $request->getRecipientContactPhoneNumber()); $xml->addChild('ToFax'); $xml->addChild('ToEmail'); if ($method != 'FirstClass') { $xml->addChild('NonDeliveryOption', 'Return'); } if ($method == 'FirstClass') { if (stripos($shippingMethod, 'Letter') !== false) { $xml->addChild('FirstClassMailType', 'LETTER'); } else { if (stripos($shippingMethod, 'Flat') !== false) { $xml->addChild('FirstClassMailType', 'FLAT'); } else { $xml->addChild('FirstClassMailType', 'PARCEL'); } } } if ($method != 'FirstClass') { $xml->addChild('Container', $container); } $shippingContents = $xml->addChild('ShippingContents'); $packageItems = $request->getPackageItems(); // get countries of manufacture $countriesOfManufacture = []; $productIds = []; foreach ($packageItems as $itemShipment) { $item = new \Magento\Framework\DataObject(); $item->setData($itemShipment); $productIds[] = $item->getProductId(); } $productCollection = $this->_productCollectionFactory->create()->addStoreFilter($request->getStoreId())->addFieldToFilter('entity_id', ['in' => $productIds])->addAttributeToSelect('country_of_manufacture'); foreach ($productCollection as $product) { $countriesOfManufacture[$product->getId()] = $product->getCountryOfManufacture(); } $packagePoundsWeight = $packageOuncesWeight = 0; // for ItemDetail foreach ($packageItems as $itemShipment) { $item = new \Magento\Framework\DataObject(); $item->setData($itemShipment); $itemWeight = $item->getWeight() * $item->getQty(); if ($packageParams->getWeightUnits() != \Zend_Measure_Weight::POUND) { $itemWeight = $this->_carrierHelper->convertMeasureWeight($itemWeight, $packageParams->getWeightUnits(), \Zend_Measure_Weight::POUND); } if (!empty($countriesOfManufacture[$item->getProductId()])) { $countryOfManufacture = $this->_getCountryName($countriesOfManufacture[$item->getProductId()]); } else { $countryOfManufacture = ''; } $itemDetail = $shippingContents->addChild('ItemDetail'); $itemDetail->addChild('Description', $item->getName()); $ceiledQty = ceil($item->getQty()); if ($ceiledQty < 1) { $ceiledQty = 1; } $individualItemWeight = $itemWeight / $ceiledQty; $itemDetail->addChild('Quantity', $ceiledQty); $itemDetail->addChild('Value', $item->getCustomsValue() * $item->getQty()); list($individualPoundsWeight, $individualOuncesWeight) = $this->_convertPoundOunces($individualItemWeight); $itemDetail->addChild('NetPounds', $individualPoundsWeight); $itemDetail->addChild('NetOunces', $individualOuncesWeight); $itemDetail->addChild('HSTariffNumber', 0); $itemDetail->addChild('CountryOfOrigin', $countryOfManufacture); list($itemPoundsWeight, $itemOuncesWeight) = $this->_convertPoundOunces($itemWeight); $packagePoundsWeight += $itemPoundsWeight; $packageOuncesWeight += $itemOuncesWeight; } $additionalPackagePoundsWeight = floor($packageOuncesWeight / self::OUNCES_POUND); $packagePoundsWeight += $additionalPackagePoundsWeight; $packageOuncesWeight -= $additionalPackagePoundsWeight * self::OUNCES_POUND; if ($packagePoundsWeight + $packageOuncesWeight / self::OUNCES_POUND < $packageWeight) { list($packagePoundsWeight, $packageOuncesWeight) = $this->_convertPoundOunces($packageWeight); } $xml->addChild('GrossPounds', $packagePoundsWeight); $xml->addChild('GrossOunces', $packageOuncesWeight); if ($packageParams->getContentType() == 'OTHER' && $packageParams->getContentTypeOther() != null) { $xml->addChild('ContentType', $packageParams->getContentType()); $xml->addChild('ContentTypeOther ', $packageParams->getContentTypeOther()); } else { $xml->addChild('ContentType', $packageParams->getContentType()); } $xml->addChild('Agreement', 'y'); $xml->addChild('ImageType', 'PDF'); $xml->addChild('ImageLayout', 'ALLINONEFILE'); if ($method == 'FirstClass') { $xml->addChild('Container', $container); } // set size if ($packageParams->getSize()) { $xml->addChild('Size', $packageParams->getSize()); } // set dimensions $xml->addChild('Length', $length); $xml->addChild('Width', $width); $xml->addChild('Height', $height); if ($girth) { $xml->addChild('Girth', $girth); } $xml = $xmlWrap->{$rootNode}->asXML(); return $xml; }
/** * Report action init operations * * @param array|\Magento\Framework\DataObject $blocks * @return $this */ public function _initReportAction($blocks) { if (!is_array($blocks)) { $blocks = [$blocks]; } $requestData = $this->_objectManager->get('Magento\\Backend\\Helper\\Data')->prepareFilterString($this->getRequest()->getParam('filter')); $inputFilter = new \Zend_Filter_Input(['from' => $this->_dateFilter, 'to' => $this->_dateFilter], [], $requestData); $requestData = $inputFilter->getUnescaped(); $requestData['store_ids'] = $this->getRequest()->getParam('store_ids'); $params = new \Magento\Framework\DataObject(); foreach ($requestData as $key => $value) { if (!empty($value)) { $params->setData($key, $value); } } foreach ($blocks as $block) { if ($block) { $block->setPeriodType($params->getData('period_type')); $block->setFilterData($params); } } return $this; }
public function testGetEntitySummary() { $productId = 6; $storeId = 4; $testSummaryData = ['test' => 'value']; $summary = new \Magento\Framework\DataObject(); $summary->setData($testSummaryData); $product = $this->getMock('Magento\\Catalog\\Model\\Product', ['getId', 'setRatingSummary', '__wakeup'], [], '', false); $product->expects($this->once())->method('getId')->will($this->returnValue($productId)); $product->expects($this->once())->method('setRatingSummary')->with($summary)->will($this->returnSelf()); $summaryData = $this->getMock('Magento\\Review\\Model\\Review\\Summary', ['load', 'getData', 'setStoreId', '__wakeup'], [], '', false); $summaryData->expects($this->once())->method('setStoreId')->with($this->equalTo($storeId))->will($this->returnSelf()); $summaryData->expects($this->once())->method('load')->with($this->equalTo($productId))->will($this->returnSelf()); $summaryData->expects($this->once())->method('getData')->will($this->returnValue($testSummaryData)); $this->summaryModMock->expects($this->once())->method('create')->will($this->returnValue($summaryData)); $this->assertNull($this->review->getEntitySummary($product, $storeId)); }
/** * Form array with appropriate structure for shipment request * * @param \Magento\Framework\DataObject $request * @return array * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ protected function _formShipmentRequest(\Magento\Framework\DataObject $request) { if ($request->getReferenceData()) { $referenceData = $request->getReferenceData() . $request->getPackageId(); } else { $referenceData = 'Order #' . $request->getOrderShipment()->getOrder()->getIncrementId() . ' P' . $request->getPackageId(); } $packageParams = $request->getPackageParams(); $customsValue = $packageParams->getCustomsValue(); $height = $packageParams->getHeight(); $width = $packageParams->getWidth(); $length = $packageParams->getLength(); $weightUnits = $packageParams->getWeightUnits() == \Zend_Measure_Weight::POUND ? 'LB' : 'KG'; $dimensionsUnits = $packageParams->getDimensionUnits() == \Zend_Measure_Length::INCH ? 'IN' : 'CM'; $unitPrice = 0; $itemsQty = 0; $itemsDesc = []; $countriesOfManufacture = []; $productIds = []; $packageItems = $request->getPackageItems(); foreach ($packageItems as $itemShipment) { $item = new \Magento\Framework\DataObject(); $item->setData($itemShipment); $unitPrice += $item->getPrice(); $itemsQty += $item->getQty(); $itemsDesc[] = $item->getName(); $productIds[] = $item->getProductId(); } // get countries of manufacture $productCollection = $this->_productCollectionFactory->create()->addStoreFilter($request->getStoreId())->addFieldToFilter('entity_id', ['in' => $productIds])->addAttributeToSelect('country_of_manufacture'); foreach ($productCollection as $product) { $countriesOfManufacture[] = $product->getCountryOfManufacture(); } $paymentType = $request->getIsReturn() ? 'RECIPIENT' : 'SENDER'; $optionType = $request->getShippingMethod() == self::RATE_REQUEST_SMARTPOST ? 'SERVICE_DEFAULT' : $packageParams->getDeliveryConfirmation(); $requestClient = ['RequestedShipment' => ['ShipTimestamp' => time(), 'DropoffType' => $this->getConfigData('dropoff'), 'PackagingType' => $request->getPackagingType(), 'ServiceType' => $request->getShippingMethod(), 'Shipper' => ['Contact' => ['PersonName' => $request->getShipperContactPersonName(), 'CompanyName' => $request->getShipperContactCompanyName(), 'PhoneNumber' => $request->getShipperContactPhoneNumber()], 'Address' => ['StreetLines' => [$request->getShipperAddressStreet()], 'City' => $request->getShipperAddressCity(), 'StateOrProvinceCode' => $request->getShipperAddressStateOrProvinceCode(), 'PostalCode' => $request->getShipperAddressPostalCode(), 'CountryCode' => $request->getShipperAddressCountryCode()]], 'Recipient' => ['Contact' => ['PersonName' => $request->getRecipientContactPersonName(), 'CompanyName' => $request->getRecipientContactCompanyName(), 'PhoneNumber' => $request->getRecipientContactPhoneNumber()], 'Address' => ['StreetLines' => [$request->getRecipientAddressStreet()], 'City' => $request->getRecipientAddressCity(), 'StateOrProvinceCode' => $request->getRecipientAddressStateOrProvinceCode(), 'PostalCode' => $request->getRecipientAddressPostalCode(), 'CountryCode' => $request->getRecipientAddressCountryCode(), 'Residential' => (bool) $this->getConfigData('residence_delivery')]], 'ShippingChargesPayment' => ['PaymentType' => $paymentType, 'Payor' => ['AccountNumber' => $this->getConfigData('account'), 'CountryCode' => $this->_scopeConfig->getValue(\Magento\Sales\Model\Order\Shipment::XML_PATH_STORE_COUNTRY_ID, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $request->getStoreId())]], 'LabelSpecification' => ['LabelFormatType' => 'COMMON2D', 'ImageType' => 'PNG', 'LabelStockType' => 'PAPER_8.5X11_TOP_HALF_LABEL'], 'RateRequestTypes' => ['ACCOUNT'], 'PackageCount' => 1, 'RequestedPackageLineItems' => ['SequenceNumber' => '1', 'Weight' => ['Units' => $weightUnits, 'Value' => $request->getPackageWeight()], 'CustomerReferences' => ['CustomerReferenceType' => 'CUSTOMER_REFERENCE', 'Value' => $referenceData], 'SpecialServicesRequested' => ['SpecialServiceTypes' => 'SIGNATURE_OPTION', 'SignatureOptionDetail' => ['OptionType' => $optionType]]]]]; // for international shipping if ($request->getShipperAddressCountryCode() != $request->getRecipientAddressCountryCode()) { $requestClient['RequestedShipment']['CustomsClearanceDetail'] = ['CustomsValue' => ['Currency' => $request->getBaseCurrencyCode(), 'Amount' => $customsValue], 'DutiesPayment' => ['PaymentType' => $paymentType, 'Payor' => ['AccountNumber' => $this->getConfigData('account'), 'CountryCode' => $this->_scopeConfig->getValue(\Magento\Sales\Model\Order\Shipment::XML_PATH_STORE_COUNTRY_ID, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $request->getStoreId())]], 'Commodities' => ['Weight' => ['Units' => $weightUnits, 'Value' => $request->getPackageWeight()], 'NumberOfPieces' => 1, 'CountryOfManufacture' => implode(',', array_unique($countriesOfManufacture)), 'Description' => implode(', ', $itemsDesc), 'Quantity' => ceil($itemsQty), 'QuantityUnits' => 'pcs', 'UnitPrice' => ['Currency' => $request->getBaseCurrencyCode(), 'Amount' => $unitPrice], 'CustomsValue' => ['Currency' => $request->getBaseCurrencyCode(), 'Amount' => $customsValue]]]; } if ($request->getMasterTrackingId()) { $requestClient['RequestedShipment']['MasterTrackingId'] = $request->getMasterTrackingId(); } if ($request->getShippingMethod() == self::RATE_REQUEST_SMARTPOST) { $requestClient['RequestedShipment']['SmartPostDetail'] = ['Indicia' => (double) $request->getPackageWeight() >= 1 ? 'PARCEL_SELECT' : 'PRESORTED_STANDARD', 'HubId' => $this->getConfigData('smartpost_hubid')]; } // set dimensions if ($length || $width || $height) { $requestClient['RequestedShipment']['RequestedPackageLineItems']['Dimensions'] = []; $dimenssions =& $requestClient['RequestedShipment']['RequestedPackageLineItems']['Dimensions']; $dimenssions['Length'] = $length; $dimenssions['Width'] = $width; $dimenssions['Height'] = $height; $dimenssions['Units'] = $dimensionsUnits; } return $this->_getAuthDetails() + $requestClient; }
/** * Return Wysiwyg config as \Magento\Framework\DataObject * * Config options description: * * enabled: Enabled Visual Editor or not * hidden: Show Visual Editor on page load or not * use_container: Wrap Editor contents into div or not * no_display: Hide Editor container or not (related to use_container) * translator: Helper to translate phrases in lib * files_browser_*: Files Browser (media, images) settings * encode_directives: Encode template directives with JS or not * * @param array|\Magento\Framework\DataObject $data Object constructor params to override default config values * @return \Magento\Framework\DataObject */ public function getConfig($data = []) { $config = new \Magento\Framework\DataObject(); $config->setData(['enabled' => $this->isEnabled(), 'hidden' => $this->isHidden(), 'use_container' => false, 'add_variables' => true, 'add_widgets' => true, 'no_display' => false, 'encode_directives' => true, 'baseStaticUrl' => $this->_assetRepo->getStaticViewFileContext()->getBaseUrl(), 'baseStaticDefaultUrl' => str_replace('index.php/', '', $this->_backendUrl->getBaseUrl()) . $this->filesystem->getUri(DirectoryList::STATIC_VIEW) . '/', 'directives_url' => $this->_backendUrl->getUrl('cms/wysiwyg/directive'), 'popup_css' => $this->_assetRepo->getUrl('mage/adminhtml/wysiwyg/tiny_mce/themes/advanced/skins/default/dialog.css'), 'content_css' => $this->_assetRepo->getUrl('mage/adminhtml/wysiwyg/tiny_mce/themes/advanced/skins/default/content.css'), 'width' => '100%', 'height' => '500px', 'plugins' => []]); $config->setData('directives_url_quoted', preg_quote($config->getData('directives_url'))); if ($this->_authorization->isAllowed('Magento_Cms::media_gallery')) { $config->addData(['add_images' => true, 'files_browser_window_url' => $this->_backendUrl->getUrl('cms/wysiwyg_images/index'), 'files_browser_window_width' => $this->_windowSize['width'], 'files_browser_window_height' => $this->_windowSize['height']]); } if (is_array($data)) { $config->addData($data); } if ($config->getData('add_variables')) { $settings = $this->_variableConfig->getWysiwygPluginSettings($config); $config->addData($settings); } if ($config->getData('add_widgets')) { $settings = $this->_widgetConfig->getPluginSettings($config); $config->addData($settings); } return $config; }
/** * Render single action as link html * * @param array $action * @param \Magento\Framework\DataObject $row * @return string */ protected function _toLinkHtml($action, \Magento\Framework\DataObject $row) { $actionAttributes = new \Magento\Framework\DataObject(); $actionCaption = ''; $this->_transformActionData($action, $actionCaption, $row); if (isset($action['confirm'])) { $action['onclick'] = 'return window.confirm(\'' . addslashes($this->escapeHtml($action['confirm'])) . '\')'; unset($action['confirm']); } $actionAttributes->setData($action); return '<a ' . $actionAttributes->serialize() . '>' . $actionCaption . '</a>'; }
/** * Form XML for shipment request * * @param \Magento\Framework\DataObject $request * @return string * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ protected function _formShipmentRequest(\Magento\Framework\DataObject $request) { $packageParams = $request->getPackageParams(); $height = $packageParams->getHeight(); $width = $packageParams->getWidth(); $length = $packageParams->getLength(); $weightUnits = $packageParams->getWeightUnits() == \Zend_Measure_Weight::POUND ? 'LBS' : 'KGS'; $dimensionsUnits = $packageParams->getDimensionUnits() == \Zend_Measure_Length::INCH ? 'IN' : 'CM'; $itemsDesc = []; $itemsShipment = $request->getPackageItems(); foreach ($itemsShipment as $itemShipment) { $item = new \Magento\Framework\DataObject(); $item->setData($itemShipment); $itemsDesc[] = $item->getName(); } $xmlRequest = $this->_xmlElFactory->create(['data' => '<?xml version = "1.0" ?><ShipmentConfirmRequest xml:lang="en-US"/>']); $requestPart = $xmlRequest->addChild('Request'); $requestPart->addChild('RequestAction', 'ShipConfirm'); $requestPart->addChild('RequestOption', 'nonvalidate'); $shipmentPart = $xmlRequest->addChild('Shipment'); if ($request->getIsReturn()) { $returnPart = $shipmentPart->addChild('ReturnService'); // UPS Print Return Label $returnPart->addChild('Code', '9'); } $shipmentPart->addChild('Description', substr(implode(' ', $itemsDesc), 0, 35)); //empirical $shipperPart = $shipmentPart->addChild('Shipper'); if ($request->getIsReturn()) { $shipperPart->addChild('Name', $request->getRecipientContactCompanyName()); $shipperPart->addChild('AttentionName', $request->getRecipientContactPersonName()); $shipperPart->addChild('ShipperNumber', $this->getConfigData('shipper_number')); $shipperPart->addChild('PhoneNumber', $request->getRecipientContactPhoneNumber()); $addressPart = $shipperPart->addChild('Address'); $addressPart->addChild('AddressLine1', $request->getRecipientAddressStreet()); $addressPart->addChild('AddressLine2', $request->getRecipientAddressStreet2()); $addressPart->addChild('City', $request->getRecipientAddressCity()); $addressPart->addChild('CountryCode', $request->getRecipientAddressCountryCode()); $addressPart->addChild('PostalCode', $request->getRecipientAddressPostalCode()); if ($request->getRecipientAddressStateOrProvinceCode()) { $addressPart->addChild('StateProvinceCode', $request->getRecipientAddressStateOrProvinceCode()); } } else { $shipperPart->addChild('Name', $request->getShipperContactCompanyName()); $shipperPart->addChild('AttentionName', $request->getShipperContactPersonName()); $shipperPart->addChild('ShipperNumber', $this->getConfigData('shipper_number')); $shipperPart->addChild('PhoneNumber', $request->getShipperContactPhoneNumber()); $addressPart = $shipperPart->addChild('Address'); $addressPart->addChild('AddressLine1', $request->getShipperAddressStreet()); $addressPart->addChild('AddressLine2', $request->getShipperAddressStreet2()); $addressPart->addChild('City', $request->getShipperAddressCity()); $addressPart->addChild('CountryCode', $request->getShipperAddressCountryCode()); $addressPart->addChild('PostalCode', $request->getShipperAddressPostalCode()); if ($request->getShipperAddressStateOrProvinceCode()) { $addressPart->addChild('StateProvinceCode', $request->getShipperAddressStateOrProvinceCode()); } } $shipToPart = $shipmentPart->addChild('ShipTo'); $shipToPart->addChild('AttentionName', $request->getRecipientContactPersonName()); $shipToPart->addChild('CompanyName', $request->getRecipientContactCompanyName() ? $request->getRecipientContactCompanyName() : 'N/A'); $shipToPart->addChild('PhoneNumber', $request->getRecipientContactPhoneNumber()); $addressPart = $shipToPart->addChild('Address'); $addressPart->addChild('AddressLine1', $request->getRecipientAddressStreet1()); $addressPart->addChild('AddressLine2', $request->getRecipientAddressStreet2()); $addressPart->addChild('City', $request->getRecipientAddressCity()); $addressPart->addChild('CountryCode', $request->getRecipientAddressCountryCode()); $addressPart->addChild('PostalCode', $request->getRecipientAddressPostalCode()); if ($request->getRecipientAddressStateOrProvinceCode()) { $addressPart->addChild('StateProvinceCode', $request->getRecipientAddressRegionCode()); } if ($this->getConfigData('dest_type') == 'RES') { $addressPart->addChild('ResidentialAddress'); } if ($request->getIsReturn()) { $shipFromPart = $shipmentPart->addChild('ShipFrom'); $shipFromPart->addChild('AttentionName', $request->getShipperContactPersonName()); $shipFromPart->addChild('CompanyName', $request->getShipperContactCompanyName() ? $request->getShipperContactCompanyName() : $request->getShipperContactPersonName()); $shipFromAddress = $shipFromPart->addChild('Address'); $shipFromAddress->addChild('AddressLine1', $request->getShipperAddressStreet1()); $shipFromAddress->addChild('AddressLine2', $request->getShipperAddressStreet2()); $shipFromAddress->addChild('City', $request->getShipperAddressCity()); $shipFromAddress->addChild('CountryCode', $request->getShipperAddressCountryCode()); $shipFromAddress->addChild('PostalCode', $request->getShipperAddressPostalCode()); if ($request->getShipperAddressStateOrProvinceCode()) { $shipFromAddress->addChild('StateProvinceCode', $request->getShipperAddressStateOrProvinceCode()); } $addressPart = $shipToPart->addChild('Address'); $addressPart->addChild('AddressLine1', $request->getShipperAddressStreet1()); $addressPart->addChild('AddressLine2', $request->getShipperAddressStreet2()); $addressPart->addChild('City', $request->getShipperAddressCity()); $addressPart->addChild('CountryCode', $request->getShipperAddressCountryCode()); $addressPart->addChild('PostalCode', $request->getShipperAddressPostalCode()); if ($request->getShipperAddressStateOrProvinceCode()) { $addressPart->addChild('StateProvinceCode', $request->getShipperAddressStateOrProvinceCode()); } if ($this->getConfigData('dest_type') == 'RES') { $addressPart->addChild('ResidentialAddress'); } } $servicePart = $shipmentPart->addChild('Service'); $servicePart->addChild('Code', $request->getShippingMethod()); $packagePart = $shipmentPart->addChild('Package'); $packagePart->addChild('Description', substr(implode(' ', $itemsDesc), 0, 35)); //empirical $packagePart->addChild('PackagingType')->addChild('Code', $request->getPackagingType()); $packageWeight = $packagePart->addChild('PackageWeight'); $packageWeight->addChild('Weight', $request->getPackageWeight()); $packageWeight->addChild('UnitOfMeasurement')->addChild('Code', $weightUnits); // set dimensions if ($length || $width || $height) { $packageDimensions = $packagePart->addChild('Dimensions'); $packageDimensions->addChild('UnitOfMeasurement')->addChild('Code', $dimensionsUnits); $packageDimensions->addChild('Length', $length); $packageDimensions->addChild('Width', $width); $packageDimensions->addChild('Height', $height); } // ups support reference number only for domestic service if ($this->_isUSCountry($request->getRecipientAddressCountryCode()) && $this->_isUSCountry($request->getShipperAddressCountryCode())) { if ($request->getReferenceData()) { $referenceData = $request->getReferenceData() . $request->getPackageId(); } else { $referenceData = 'Order #' . $request->getOrderShipment()->getOrder()->getIncrementId() . ' P' . $request->getPackageId(); } $referencePart = $packagePart->addChild('ReferenceNumber'); $referencePart->addChild('Code', '02'); $referencePart->addChild('Value', $referenceData); } $deliveryConfirmation = $packageParams->getDeliveryConfirmation(); if ($deliveryConfirmation) { /** @var $serviceOptionsNode Element */ $serviceOptionsNode = null; switch ($this->_getDeliveryConfirmationLevel($request->getRecipientAddressCountryCode())) { case self::DELIVERY_CONFIRMATION_PACKAGE: $serviceOptionsNode = $packagePart->addChild('PackageServiceOptions'); break; case self::DELIVERY_CONFIRMATION_SHIPMENT: $serviceOptionsNode = $shipmentPart->addChild('ShipmentServiceOptions'); break; default: break; } if (!is_null($serviceOptionsNode)) { $serviceOptionsNode->addChild('DeliveryConfirmation')->addChild('DCISType', $packageParams->getDeliveryConfirmation()); } } $shipmentPart->addChild('PaymentInformation')->addChild('Prepaid')->addChild('BillShipper')->addChild('AccountNumber', $this->getConfigData('shipper_number')); if ($request->getPackagingType() != $this->configHelper->getCode('container', 'ULE') && $request->getShipperAddressCountryCode() == self::USA_COUNTRY_ID && ($request->getRecipientAddressCountryCode() == 'CA' || $request->getRecipientAddressCountryCode() == 'PR')) { $invoiceLineTotalPart = $shipmentPart->addChild('InvoiceLineTotal'); $invoiceLineTotalPart->addChild('CurrencyCode', $request->getBaseCurrencyCode()); $invoiceLineTotalPart->addChild('MonetaryValue', ceil($packageParams->getCustomsValue())); } $labelPart = $xmlRequest->addChild('LabelSpecification'); $labelPart->addChild('LabelPrintMethod')->addChild('Code', 'GIF'); $labelPart->addChild('LabelImageFormat')->addChild('Code', 'GIF'); $this->setXMLAccessRequest(); $xmlRequest = $this->_xmlAccessRequest . $xmlRequest->asXml(); return $xmlRequest; }