/** * @param AbstractElement $element * @return string * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function render(AbstractElement $element) { $countryId = false; $isRegionRequired = false; if ($country = $element->getForm()->getElement('country_id')) { $countryId = $country->getValue(); $isRegionRequired = $this->_directoryHelper->isRegionRequired($countryId); } $html = '<div class="field field-region ' . ($isRegionRequired ? 'required' : '') . '">' . "\n"; $regionCollection = false; if ($countryId) { if (!isset(self::$_regionCollections[$countryId])) { self::$_regionCollections[$countryId] = $this->_countryFactory->create()->setId($countryId)->getLoadedRegionCollection()->toOptionArray(); } $regionCollection = self::$_regionCollections[$countryId]; } $regionId = intval($element->getForm()->getElement('region_id')->getValue()); $htmlAttributes = $element->getHtmlAttributes(); foreach ($htmlAttributes as $key => $attribute) { if ('type' === $attribute) { unset($htmlAttributes[$key]); break; } } // Output two elements - for 'region' and for 'region_id'. // Two elements are needed later upon form post - to properly set data to address model, // otherwise old value can be left in region_id attribute and saved to DB. // Depending on country selected either 'region' (input text) or 'region_id' (selectbox) is visible to user $regionHtmlName = $element->getName(); $regionIdHtmlName = str_replace('region', 'region_id', $regionHtmlName); $regionHtmlId = $element->getHtmlId(); $regionIdHtmlId = str_replace('region', 'region_id', $regionHtmlId); if ($isRegionRequired) { $element->addClass('required-entry'); } if ($regionCollection && count($regionCollection) > 0) { $elementClass = $element->getClass(); $html .= '<label class="label" for="' . $regionIdHtmlId . '"><span>' . $element->getLabel() . '</span>' . '</label>'; $html .= '<div class="control">'; $html .= '<select id="' . $regionIdHtmlId . '" name="' . $regionIdHtmlName . '" ' . $element->serialize($htmlAttributes) . '>' . "\n"; foreach ($regionCollection as $region) { $selected = $regionId == $region['value'] ? ' selected="selected"' : ''; $regionVal = 0 == $region['value'] ? '' : (int) $region['value']; $html .= '<option value="' . $regionVal . '"' . $selected . '>' . $this->_escaper->escapeHtml(__($region['label'])) . '</option>'; } $html .= '</select>' . "\n"; $html .= '<input type="hidden" name="' . $regionHtmlName . '" id="' . $regionHtmlId . '" value=""/>'; $html .= '</div>'; $element->setClass($elementClass); } else { $html .= '<label class="label" for="' . $regionHtmlId . '"><span>' . $element->getLabel() . '</span></label>'; $html .= '<div class="control">'; $html .= '<input id="' . $regionHtmlId . '" name="' . $regionHtmlName . '" value="' . $element->getEscapedValue() . '" ' . $element->serialize($htmlAttributes) . "/>" . "\n"; $html .= '<input type="hidden" name="' . $regionIdHtmlName . '" id="' . $regionIdHtmlId . '" value=""/>'; $html .= '</div>' . "\n"; } $html .= '</div>' . "\n"; return $html; }
/** * Retrieve generic object with all the misc store information values * * @param Store $store * @return DataObject */ public function getStoreInformationObject(Store $store) { $info = new DataObject(['name' => $store->getConfig(self::XML_PATH_STORE_INFO_NAME), 'phone' => $store->getConfig(self::XML_PATH_STORE_INFO_PHONE), 'hours' => $store->getConfig(self::XML_PATH_STORE_INFO_HOURS), 'street_line1' => $store->getConfig(self::XML_PATH_STORE_INFO_STREET_LINE1), 'street_line2' => $store->getConfig(self::XML_PATH_STORE_INFO_STREET_LINE2), 'city' => $store->getConfig(self::XML_PATH_STORE_INFO_CITY), 'postcode' => $store->getConfig(self::XML_PATH_STORE_INFO_POSTCODE), 'region_id' => $store->getConfig(self::XML_PATH_STORE_INFO_REGION_CODE), 'country_id' => $store->getConfig(self::XML_PATH_STORE_INFO_COUNTRY_CODE), 'vat_number' => $store->getConfig(self::XML_PATH_STORE_INFO_VAT_NUMBER)]); if ($info->getRegionId()) { $info->setRegion($this->regionFactory->create()->load($info->getRegionId())->getName()); } if ($info->getCountryId()) { $info->setCountry($this->countryFactory->create()->loadByCode($info->getCountryId())->getName()); } return $info; }
/** * Get list of all available countries * * @return array */ public function getAllOptions() { $cacheKey = 'COUNTRYOFMANUFACTURE_SELECT_STORE_' . $this->_storeManager->getStore()->getCode(); if ($cache = $this->_configCacheType->load($cacheKey)) { $options = unserialize($cache); } else { $collection = $this->_countryFactory->create()->getResourceCollection()->loadByStore(); $options = $collection->toOptionArray(); $this->_configCacheType->save(serialize($options), $cacheKey); } return $options; }
/** * Import single rate * * @param array $rateData * @param array $regionsCache cache of regions of already used countries (is used to optimize performance) * @param array $storesCache cache of stores related to tax rate titles * @return array regions cache populated with regions related to country of imported tax rate * @throws \Magento\Framework\Exception\LocalizedException */ protected function _importRate(array $rateData, array $regionsCache, array $storesCache) { // data with index 1 must represent country code $countryCode = $rateData[1]; $country = $this->_countryFactory->create()->loadByCode($countryCode, 'iso2_code'); if (!$country->getId()) { throw new \Magento\Framework\Exception\LocalizedException(__('One of the countries has invalid code.')); } $regionsCache = $this->_addCountryRegionsToCache($countryCode, $regionsCache); // data with index 2 must represent region code $regionCode = $rateData[2]; if (!empty($regionsCache[$countryCode][$regionCode])) { $regionId = $regionsCache[$countryCode][$regionCode] == '*' ? 0 : $regionsCache[$countryCode][$regionCode]; // data with index 3 must represent postcode $postCode = empty($rateData[3]) ? null : $rateData[3]; $modelData = ['code' => $rateData[0], 'tax_country_id' => $rateData[1], 'tax_region_id' => $regionId, 'tax_postcode' => $postCode, 'rate' => $rateData[4], 'zip_is_range' => $rateData[5], 'zip_from' => $rateData[6], 'zip_to' => $rateData[7]]; // try to load existing rate /** @var $rateModel \Magento\Tax\Model\Calculation\Rate */ $rateModel = $this->_taxRateFactory->create()->loadByCode($modelData['code']); $rateModel->addData($modelData); // compose titles list $rateTitles = []; foreach ($storesCache as $fileFieldIndex => $storeId) { $rateTitles[$storeId] = $rateData[$fileFieldIndex]; } $rateModel->setTitle($rateTitles); $rateModel->save(); } return $regionsCache; }
protected function setUp() { $this->contextMock = $this->getMock('Magento\\Framework\\Model\\Context', array(), array(), '', false); $this->registryMock = $this->getMock('Magento\\Framework\\Registry', array(), array(), '', false); $this->directoryDataMock = $this->getMock('Magento\\Directory\\Helper\\Data', array(), array(), '', false); $this->eavConfigMock = $this->getMock('Magento\\Eav\\Model\\Config', array(), array(), '', false); $this->addressConfigMock = $this->getMock('Magento\\Customer\\Model\\Address\\Config', array(), array(), '', false); $this->regionFactoryMock = $this->getMock('Magento\\Directory\\Model\\RegionFactory', array('create'), array(), '', false); $this->countryFactoryMock = $this->getMock('Magento\\Directory\\Model\\CountryFactory', array('create'), array(), '', false); $regionCollectionMock = $this->getMock('Magento\\Directory\\Model\\Resource\\Region\\Collection', array(), array(), '', false); $regionCollectionMock->expects($this->any())->method('getSize')->will($this->returnValue(0)); $countryMock = $this->getMock('Magento\\Directory\\Model\\Country', array(), array(), '', false); $countryMock->expects($this->any())->method('getRegionCollection')->will($this->returnValue($regionCollectionMock)); $this->countryFactoryMock->expects($this->any())->method('create')->will($this->returnValue($countryMock)); $this->resourceMock = $this->getMock('Magento\\Customer\\Model\\Resource\\Customer', array(), array(), '', false); $this->resourceCollectionMock = $this->getMock('Magento\\Framework\\Data\\Collection\\Db', array(), array(), '', false); $this->model = $this->getMockForAbstractClass('Magento\\Customer\\Model\\Address\\AbstractAddress', array('context' => $this->contextMock, 'registry' => $this->registryMock, 'directoryData' => $this->directoryDataMock, 'eavConfig' => $this->eavConfigMock, 'addressConfig' => $this->addressConfigMock, 'regionFactory' => $this->regionFactoryMock, 'countryFactory' => $this->countryFactoryMock, 'resource' => $this->resourceMock, 'resourceCollection' => $this->resourceCollectionMock), '', true, false); }
/** * Returns true if and only if $value meets the validation requirements * * If $value fails validation, then this method returns false, and * getMessages() will return an array of messages that explain why the * validation failed. * * @param \Magento\Sales\Model\Quote\Address $value * @return boolean * @throws Zend_Validate_Exception If validation of $value is impossible */ public function isValid($value) { $messages = array(); $email = $value->getEmail(); if (!empty($email) && !\Zend_Validate::is($email, 'EmailAddress')) { $messages['invalid_email_format'] = 'Invalid email format'; } $countryId = $value->getCountryId(); if (!empty($countryId)) { $country = $this->countryFactory->create(); $country->load($countryId); if (!$country->getId()) { $messages['invalid_country_code'] = 'Invalid country code'; } } $this->_addMessages($messages); return empty($messages); }
protected function setUp() { $this->helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->scope = $this->getMockBuilder('\\Magento\\Framework\\App\\Config\\ScopeConfigInterface')->disableOriginalConstructor()->getMock(); $this->scope->expects($this->any())->method('getValue')->will($this->returnCallback([$this, 'scopeConfiggetValue'])); $this->error = $this->getMockBuilder('\\Magento\\Quote\\Model\\Quote\\Address\\RateResult\\Error')->setMethods(['setCarrier', 'setCarrierTitle', 'setErrorMessage'])->getMock(); $this->errorFactory = $this->getMockBuilder('Magento\\Quote\\Model\\Quote\\Address\\RateResult\\ErrorFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock(); $this->errorFactory->expects($this->any())->method('create')->willReturn($this->error); $this->rate = $this->getMock('Magento\\Shipping\\Model\\Rate\\Result', ['getError'], [], '', false); $rateFactory = $this->getMock('Magento\\Shipping\\Model\\Rate\\ResultFactory', ['create'], [], '', false); $rateFactory->expects($this->any())->method('create')->willReturn($this->rate); $this->country = $this->getMockBuilder('\\Magento\\Directory\\Model\\Country')->disableOriginalConstructor()->setMethods(['load'])->getMock(); $this->abstractModel = $this->getMockBuilder('Magento\\Framework\\Model\\AbstractModel')->disableOriginalConstructor()->setMethods(['getData'])->getMock(); $this->country->expects($this->any())->method('load')->willReturn($this->abstractModel); $this->countryFactory = $this->getMockBuilder('\\Magento\\Directory\\Model\\CountryFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock(); $this->countryFactory->expects($this->any())->method('create')->willReturn($this->country); $this->model = $this->helper->getObject('Magento\\Ups\\Model\\Carrier', ['scopeConfig' => $this->scope, 'rateErrorFactory' => $this->errorFactory, 'countryFactory' => $this->countryFactory, 'rateFactory' => $rateFactory]); }
protected function setUp() { $this->contextMock = $this->getMock('Magento\\Framework\\Model\\Context', [], [], '', false); $this->registryMock = $this->getMock('Magento\\Framework\\Registry', [], [], '', false); $this->directoryDataMock = $this->getMock('Magento\\Directory\\Helper\\Data', [], [], '', false); $this->eavConfigMock = $this->getMock('Magento\\Eav\\Model\\Config', [], [], '', false); $this->addressConfigMock = $this->getMock('Magento\\Customer\\Model\\Address\\Config', [], [], '', false); $this->regionFactoryMock = $this->getMock('Magento\\Directory\\Model\\RegionFactory', ['create'], [], '', false); $this->countryFactoryMock = $this->getMock('Magento\\Directory\\Model\\CountryFactory', ['create'], [], '', false); $regionCollectionMock = $this->getMock('Magento\\Directory\\Model\\Resource\\Region\\Collection', [], [], '', false); $regionCollectionMock->expects($this->any())->method('getSize')->will($this->returnValue(0)); $countryMock = $this->getMock('Magento\\Directory\\Model\\Country', [], [], '', false); $countryMock->expects($this->any())->method('getRegionCollection')->will($this->returnValue($regionCollectionMock)); $this->countryFactoryMock->expects($this->any())->method('create')->will($this->returnValue($countryMock)); $this->resourceMock = $this->getMock('Magento\\Customer\\Model\\Resource\\Customer', [], [], '', false); $this->resourceCollectionMock = $this->getMock('Magento\\Framework\\Data\\Collection\\Db', [], [], '', false); $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->model = $objectManager->getObject('Magento\\Customer\\Model\\Address\\AbstractAddress', ['context' => $this->contextMock, 'registry' => $this->registryMock, 'directoryData' => $this->directoryDataMock, 'eavConfig' => $this->eavConfigMock, 'addressConfig' => $this->addressConfigMock, 'regionFactory' => $this->regionFactoryMock, 'countryFactory' => $this->countryFactoryMock, 'resource' => $this->resourceMock, 'resourceCollection' => $this->resourceCollectionMock]); }
/** * Trigger pusher event with latest order information * * @param \Magento\Framework\Event\Observer $observer * @return \Jahvi\NewOrderNotification\Observer\DisplayNotification */ public function execute(Observer $observer) { if ($this->globalConfig->getValue('checkout/newordernotification/enabled')) { $appId = $this->globalConfig->getValue('checkout/newordernotification/app_id'); $appKey = $this->globalConfig->getValue('checkout/newordernotification/app_key'); $appSecret = $this->globalConfig->getValue('checkout/newordernotification/app_secret'); $pusher = new \Pusher($appKey, $appSecret, $appId, ['encrypted' => true]); // Get latest order $orderId = $observer->getEvent()->getOrderIds()[0]; $order = $this->orderFactory->create()->load($orderId); // Get last product in order data $product = $order->getAllVisibleItems()[0]->getProduct(); $shippingCity = $order->getShippingAddress()->getCity(); $productImage = $this->imageHelper->init($product, 'product_thumbnail_image'); // Get shipping city and country $shippingCountryCode = $order->getShippingAddress()->getCountryId(); $shippingCountry = $this->countryFactory->create()->loadByCode($shippingCountryCode); // Trigger pusher event with collected data $pusher->trigger('non_channel', 'new_order', ['product_name' => $product->getName(), 'product_image' => $productImage->getUrl(), 'product_url' => $product->getProductUrl(), 'shipping_city' => $shippingCity, 'shipping_country' => $shippingCountry->getName()]); } return $this; }
/** * {@inheritdoc} * * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function renderArray($addressAttributes, $format = null) { switch ($this->getType()->getCode()) { case 'html': $dataFormat = ElementFactory::OUTPUT_FORMAT_HTML; break; case 'pdf': $dataFormat = ElementFactory::OUTPUT_FORMAT_PDF; break; case 'oneline': $dataFormat = ElementFactory::OUTPUT_FORMAT_ONELINE; break; default: $dataFormat = ElementFactory::OUTPUT_FORMAT_TEXT; break; } $attributesMetadata = $this->_addressMetadataService->getAllAttributesMetadata(); $data = []; foreach ($attributesMetadata as $attributeMetadata) { if (!$attributeMetadata->isVisible()) { continue; } $attributeCode = $attributeMetadata->getAttributeCode(); if ($attributeCode == 'country_id' && isset($addressAttributes['country_id'])) { $data['country'] = $this->_countryFactory->create()->loadByCode($addressAttributes['country_id'])->getName(); } elseif ($attributeCode == 'region' && isset($addressAttributes['region'])) { $data['region'] = __($addressAttributes['region']); } elseif (isset($addressAttributes[$attributeCode])) { $value = $addressAttributes[$attributeCode]; $dataModel = $this->_elementFactory->create($attributeMetadata, $value, 'customer_address'); $value = $dataModel->outputValue($dataFormat); if ($attributeMetadata->getFrontendInput() == 'multiline') { $values = $dataModel->outputValue(ElementFactory::OUTPUT_FORMAT_ARRAY); // explode lines foreach ($values as $k => $v) { $key = sprintf('%s%d', $attributeCode, $k + 1); $data[$key] = $v; } } $data[$attributeCode] = $value; } } if ($this->getType()->getEscapeHtml()) { foreach ($data as $key => $value) { $data[$key] = $this->escapeHtml($value); } } $format = $format !== null ? $format : $this->getFormatArray($addressAttributes); return $this->filterManager->template($format, ['variables' => $data]); }
/** * Init mocks for tests */ protected function setUp() { $mockData = $this->mockConfigData = [Information::XML_PATH_STORE_INFO_NAME => 'Country Furnishings', Information::XML_PATH_STORE_INFO_PHONE => '000-000-0000', Information::XML_PATH_STORE_INFO_HOURS => '9 AM to 5 PM', Information::XML_PATH_STORE_INFO_STREET_LINE1 => '1234 Example Ct', Information::XML_PATH_STORE_INFO_STREET_LINE2 => 'Suite A', Information::XML_PATH_STORE_INFO_CITY => 'Aldburg', Information::XML_PATH_STORE_INFO_POSTCODE => '65804', Information::XML_PATH_STORE_INFO_REGION_CODE => 1989, Information::XML_PATH_STORE_INFO_COUNTRY_CODE => 'ED', Information::XML_PATH_STORE_INFO_VAT_NUMBER => '123456789']; $this->store = $this->getMock('Magento\\Store\\Model\\Store', [], [], '', false); $this->store->expects($this->any())->method('getConfig')->willReturnCallback(function ($path) use($mockData) { return isset($mockData[$path]) ? $mockData[$path] : null; }); $this->renderer = $this->getMockBuilder('Magento\\Store\\Model\\Address\\Renderer')->disableOriginalConstructor()->setMethods(['format'])->getMock(); $this->renderer->expects($this->once())->method('format')->willReturnCallback(function ($storeInfo) { return implode("\n", $storeInfo->getData()); }); $region = $this->getMock('Magento\\Framework\\DataObject', ['load', 'getName']); $region->expects($this->once())->method('load')->willReturnSelf(); $region->expects($this->once())->method('getName')->willReturn('Rohan'); $this->regionFactory = $this->getMock('Magento\\Directory\\Model\\RegionFactory', [], [], '', false); $this->regionFactory->expects($this->once())->method('create')->willReturn($region); $country = $this->getMock('Magento\\Framework\\DataObject', ['loadByCode', 'getName']); $country->expects($this->once())->method('loadByCode')->with('ED')->willReturnSelf(); $country->expects($this->once())->method('getName')->willReturn('Edoras'); $this->countryFactory = $this->getMock('Magento\\Directory\\Model\\CountryFactory', [], [], '', false); $this->countryFactory->expects($this->once())->method('create')->willReturn($country); $this->model = new Information($this->renderer, $this->regionFactory, $this->countryFactory); }
/** * Validate tax rate * * @param TaxRateDataObject $taxRate * @throws InputException * @return void * * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ private function validate(TaxRateDataObject $taxRate) { $exception = new InputException(); $countryCode = $taxRate->getCountryId(); if (!\Zend_Validate::is($countryCode, 'NotEmpty')) { $exception->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'country_id']); } else { if (!\Zend_Validate::is($this->countryFactory->create()->loadByCode($countryCode)->getId(), 'NotEmpty')) { $exception->addError(InputException::INVALID_FIELD_VALUE, ['fieldName' => 'country_id', 'value' => $countryCode]); } } $regionCode = $taxRate->getRegionId(); if (\Zend_Validate::is($regionCode, 'NotEmpty') && !\Zend_Validate::is($this->regionFactory->create()->load($regionCode)->getId(), 'NotEmpty')) { $exception->addError(InputException::INVALID_FIELD_VALUE, ['fieldName' => 'region_id', 'value' => $regionCode]); } if (!\Zend_Validate::is($taxRate->getPercentageRate(), 'NotEmpty')) { $exception->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'percentage_rate']); } if (!\Zend_Validate::is(trim($taxRate->getCode()), 'NotEmpty')) { $exception->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'code']); } if ($taxRate->getZipRange()) { $zipRangeFromTo = ['zip_from' => $taxRate->getZipRange()->getFrom(), 'zip_to' => $taxRate->getZipRange()->getTo()]; foreach ($zipRangeFromTo as $key => $value) { if (!is_numeric($value) || $value < 0) { $exception->addError(InputException::INVALID_FIELD_VALUE, ['fieldName' => $key, 'value' => $value]); } } if ($zipRangeFromTo['zip_from'] > $zipRangeFromTo['zip_to']) { $exception->addError('Range To should be equal or greater than Range From.'); } } else { if (!\Zend_Validate::is(trim($taxRate->getPostcode()), 'NotEmpty')) { $exception->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'postcode']); } } if ($exception->wasErrorAdded()) { throw $exception; } }
/** * Validate tax rate * * @param \Magento\Tax\Api\Data\TaxRateInterface $taxRate * @throws InputException * @return void * * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ private function validate(\Magento\Tax\Api\Data\TaxRateInterface $taxRate) { $exception = new InputException(); $countryCode = $taxRate->getTaxCountryId(); if (!\Zend_Validate::is($countryCode, 'NotEmpty')) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'country_id'])); } elseif (!\Zend_Validate::is($this->countryFactory->create()->loadByCode($countryCode)->getId(), 'NotEmpty')) { $exception->addError(__(InputException::INVALID_FIELD_VALUE, ['fieldName' => 'country_id', 'value' => $countryCode])); } $regionCode = $taxRate->getTaxRegionId(); // if regionCode eq 0 (all regions *), do not validate with existing region list if (\Zend_Validate::is($regionCode, 'NotEmpty') && $regionCode != "0" && !\Zend_Validate::is($this->regionFactory->create()->load($regionCode)->getId(), 'NotEmpty')) { $exception->addError(__(InputException::INVALID_FIELD_VALUE, ['fieldName' => 'region_id', 'value' => $regionCode])); } if (!\Zend_Validate::is($taxRate->getRate(), 'NotEmpty')) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'percentage_rate'])); } if (!\Zend_Validate::is(trim($taxRate->getCode()), 'NotEmpty')) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'code'])); } if ($taxRate->getZipIsRange()) { $zipRangeFromTo = ['zip_from' => $taxRate->getZipFrom(), 'zip_to' => $taxRate->getZipTo()]; foreach ($zipRangeFromTo as $key => $value) { if (!is_numeric($value) || $value < 0) { $exception->addError(__(InputException::INVALID_FIELD_VALUE, ['fieldName' => $key, 'value' => $value])); } } if ($zipRangeFromTo['zip_from'] > $zipRangeFromTo['zip_to']) { $exception->addError(__('Range To should be equal or greater than Range From.')); } } else { if (!\Zend_Validate::is(trim($taxRate->getTaxPostcode()), 'NotEmpty')) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'postcode'])); } } if ($exception->wasErrorAdded()) { throw $exception; } }
/** * @return \Magento\Directory\Model\Country */ protected function _createCountryInstance() { return $this->_countryFactory->create(); }
/** * @param string $countryCode * @return \Magento\Directory\Model\Country */ protected function getCountry($countryCode) { return $this->countryFactory->create()->loadByCode($countryCode); }
/** * Adopt specified address object to be compatible with Magento * * @param \Magento\Framework\DataObject $address * @return void */ protected function _applyStreetAndRegionWorkarounds(\Magento\Framework\DataObject $address) { // merge street addresses into 1 if ($address->hasStreet2()) { $address->setStreet(implode("\n", [$address->getStreet(), $address->getStreetLine(2)])); $address->unsStreet2(); } // attempt to fetch region_id from directory if ($address->getCountryId() && $address->getRegion()) { $regions = $this->_countryFactory->create()->loadByCode($address->getCountryId())->getRegionCollection()->addRegionCodeOrNameFilter($address->getRegion())->setPageSize(1); foreach ($regions as $region) { $address->setRegionId($region->getId()); $address->setExportedKeys(array_merge($address->getExportedKeys(), ['region_id'])); break; } } }
/** * Checks if state for current country id is required * * @param string $countryId * @return bool */ protected function isStateRequired($countryId) { $country = $this->countryFactory->create()->load($countryId); return $this->directoryHelper->isRegionRequired($countryId) && $country->getRegionCollection()->getSize(); }
/** * @param array $address * @return mixed */ protected function getRegionId($address) { $country = $this->countryFactory->create()->loadByCode($address['country_id']); return $country->getRegionCollection()->addFieldToFilter('name', $address['region'])->getFirstItem()->getId(); }