/** * Clears cache and updates translations file * * @return array */ public function updateAndGetTranslations() { $this->eventManager->dispatch('adminhtml_cache_flush_system'); $translations = $this->translateResource->getTranslationArray(null, $this->localeResolver->getLocale()); $this->fileManager->updateTranslationFileContent(json_encode($translations)); return $translations; }
/** * Get current language * * @return string */ public function getLang() { if (!$this->hasData('lang')) { $this->setData('lang', substr($this->_localeResolver->getLocale(), 0, 2)); } return $this->getData('lang'); }
/** * Render block HTML * * @return string */ protected function _toHtml() { $localeData = (new DataBundle())->get($this->_localeResolver->getLocale()); // get days names $daysData = $localeData['calendar']['gregorian']['dayNames']; $this->assign('days', ['wide' => $this->encoder->encode(array_values(iterator_to_array($daysData['format']['wide']))), 'abbreviated' => $this->encoder->encode(array_values(iterator_to_array($daysData['format']['abbreviated'])))]); // get months names $monthsData = $localeData['calendar']['gregorian']['monthNames']; $this->assign('months', ['wide' => $this->encoder->encode(array_values(iterator_to_array($monthsData['format']['wide']))), 'abbreviated' => $this->encoder->encode(array_values(iterator_to_array($monthsData['format']['abbreviated'])))]); // get "today" and "week" words $this->assign('today', $this->encoder->encode($localeData['fields']['day']['relative']['0'])); $this->assign('week', $this->encoder->encode($localeData['fields']['week']['dn'])); // get "am" & "pm" words $this->assign('am', $this->encoder->encode($localeData['calendar']['gregorian']['AmPmMarkers']['0'])); $this->assign('pm', $this->encoder->encode($localeData['calendar']['gregorian']['AmPmMarkers']['1'])); // get first day of week and weekend days $this->assign('firstDay', (int) $this->_scopeConfig->getValue('general/locale/firstday', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)); $this->assign('weekendDays', $this->encoder->encode((string) $this->_scopeConfig->getValue('general/locale/weekend', \Magento\Store\Model\ScopeInterface::SCOPE_STORE))); // define default format and tooltip format $this->assign('defaultFormat', $this->encoder->encode($this->_localeDate->getDateFormat(\IntlDateFormatter::MEDIUM))); $this->assign('toolTipFormat', $this->encoder->encode($this->_localeDate->getDateFormat(\IntlDateFormatter::LONG))); // get days and months for en_US locale - calendar will parse exactly in this locale $englishMonths = (new DataBundle())->get('en_US')['calendar']['gregorian']['monthNames']; $enUS = new \stdClass(); $enUS->m = new \stdClass(); $enUS->m->wide = array_values(iterator_to_array($englishMonths['format']['wide'])); $enUS->m->abbr = array_values(iterator_to_array($englishMonths['format']['abbreviated'])); $this->assign('enUS', $this->encoder->encode($enUS)); return parent::_toHtml(); }
/** * Functions returns array with price formatting info * * @return array * @SuppressWarnings(PHPMD.NPathComplexity) */ public function getPriceFormat() { $localeData = (new DataBundle())->get($this->_localeResolver->getLocale()); $format = $localeData['NumberElements']['latn']['patterns']['currencyFormat'] ?: explode(';', $localeData['NumberPatterns'][1])[0]; $decimalSymbol = $localeData['NumberElements']['latn']['symbols']['decimal'] ?: $localeData['NumberElements'][0]; $groupSymbol = $localeData['NumberElements']['latn']['symbols']['group'] ?: $localeData['NumberElements'][1]; $pos = strpos($format, ';'); if ($pos !== false) { $format = substr($format, 0, $pos); } $format = preg_replace("/[^0\\#\\.,]/", "", $format); $totalPrecision = 0; $decimalPoint = strpos($format, '.'); if ($decimalPoint !== false) { $totalPrecision = strlen($format) - (strrpos($format, '.') + 1); } else { $decimalPoint = strlen($format); } $requiredPrecision = $totalPrecision; $t = substr($format, $decimalPoint); $pos = strpos($t, '#'); if ($pos !== false) { $requiredPrecision = strlen($t) - $pos - $totalPrecision; } if (strrpos($format, ',') !== false) { $group = $decimalPoint - strrpos($format, ',') - 1; } else { $group = strrpos($format, '.'); } $integerRequired = strpos($format, '.') - strpos($format, '0'); $result = ['pattern' => $this->_scopeResolver->getScope()->getCurrentCurrency()->getOutputFormat(), 'precision' => $totalPrecision, 'requiredPrecision' => $requiredPrecision, 'decimalSymbol' => $decimalSymbol, 'groupSymbol' => $groupSymbol, 'groupLength' => $group, 'integerRequired' => $integerRequired]; return $result; }
/** * return current locale code */ public function getCurrentLocale() { if ($this->_localeResolver->getLocale() == 'ja_JP') { return 'ja'; } return 'en'; }
/** * @param \Magento\Customer\Model\ResourceModel\Customer\Collection $subject * @param \Closure $proceed * @return \Magento\Customer\Model\ResourceModel\Customer\Collection */ public function aroundAddNameToSelect(Collection $subject, \Closure $proceed) { $fields = []; $customerAccount = $this->fieldsetConfig->getFieldset('customer_account'); foreach ($customerAccount as $code => $field) { if (isset($field['name'])) { $fields[$code] = $code; } } $connection = $subject->getConnection(); $concatenate = []; if (isset($fields['prefix'])) { $concatenate[] = $connection->getCheckSql('{{prefix}} IS NOT NULL AND {{prefix}} != \'\'', $connection->getConcatSql(['LTRIM(RTRIM({{prefix}}))', '\' \'']), '\'\''); } if ($this->localeResolver->getLocale() != 'ja_JP') { $concatenate[] = 'LTRIM(RTRIM({{firstname}}))'; } else { $concatenate[] = 'LTRIM(RTRIM({{lastname}}))'; } $concatenate[] = '\' \''; if (isset($fields['middlename'])) { $concatenate[] = $connection->getCheckSql('{{middlename}} IS NOT NULL AND {{middlename}} != \'\'', $connection->getConcatSql(['LTRIM(RTRIM({{middlename}}))', '\' \'']), '\'\''); } if ($this->localeResolver->getLocale() != 'ja_JP') { $concatenate[] = 'LTRIM(RTRIM({{lastname}}))'; } else { $concatenate[] = 'LTRIM(RTRIM({{firstname}}))'; } if (isset($fields['suffix'])) { $concatenate[] = $connection->getCheckSql('{{suffix}} IS NOT NULL AND {{suffix}} != \'\'', $connection->getConcatSql(['\' \'', 'LTRIM(RTRIM({{suffix}}))']), '\'\''); } $nameExpr = $connection->getConcatSql($concatenate); $subject->addExpressionAttributeToSelect('name', $nameExpr, $fields); return $subject; }
/** * Returns the result of filtering $value * * @param string $value * @return string */ public function outputFilter($value) { $filterInput = new \Zend_Filter_LocalizedToNormalized(['date_format' => DateTime::DATE_INTERNAL_FORMAT, 'locale' => $this->localeResolver->getLocale()]); $filterInternal = new \Zend_Filter_NormalizedToLocalized(['date_format' => $this->_dateFormat, 'locale' => $this->localeResolver->getLocale()]); $value = $filterInput->filter($value); $value = $filterInternal->filter($value); return $value; }
/** * Initialize select object * * @return $this */ protected function _initSelect() { parent::_initSelect(); $locale = $this->_localeResolver->getLocale(); $this->addBindParam(':region_locale', $locale); $this->getSelect()->joinLeft(['rname' => $this->_regionNameTable], 'main_table.region_id = rname.region_id AND rname.locale = :region_locale', ['name']); return $this; }
/** * @return array|void */ public function getConfig() { if (!$this->config->isActive()) { return []; } $clientToken = $this->config->getClientToken(); $config = ['payment' => ['braintree_paypal' => ['clientToken' => $clientToken, 'locale' => $this->localeResolver->getLocale(), 'merchantDisplayName' => $this->config->getMerchantNameOverride()]]]; return $config; }
/** * Process localized quantity to internal format * * @param float $qty * @return array|string */ public function process($qty) { $this->localFilter->setOptions(['locale' => $this->localeResolver->getLocale()]); $qty = $this->localFilter->filter((double) $qty); if ($qty < 0) { $qty = null; } return $qty; }
/** * {@inheritdoc} */ public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { $days = (new DataBundle())->get($this->localeResolver->getLocale())['calendar']['gregorian']['dayNames']['format']['abbreviated']; $select = $setup->getConnection()->select()->from($setup->getTable('core_config_data'), ['config_id', 'value'])->where('path = ?', 'carriers/dhl/shipment_days'); foreach ($setup->getConnection()->fetchAll($select) as $configRow) { $row = ['value' => implode(',', array_intersect_key(iterator_to_array($days), array_flip(explode(',', $configRow['value']))))]; $setup->getConnection()->update($setup->getTable('core_config_data'), $row, ['config_id = ?' => $configRow['config_id']]); } }
/** * Set template and redirect message * * @return null */ protected function _construct() { $this->_config = $this->_paypalConfigFactory->create()->setMethod($this->getMethodCode()); $mark = $this->_getMarkTemplate(); $mark->setPaymentAcceptanceMarkHref($this->_config->getPaymentMarkWhatIsPaypalUrl($this->_localeResolver))->setPaymentAcceptanceMarkSrc($this->_config->getPaymentMarkImageUrl($this->_localeResolver->getLocale())); // known issue: code above will render only static mark image $this->_initializeRedirectTemplateWithMark($mark); parent::_construct(); $this->setRedirectMessage(__('You will be redirected to the PayPal website.')); }
/** * {@inheritdoc} */ public function getConfig() { $config = ['payment' => ['paypalExpress' => ['paymentAcceptanceMarkHref' => $this->config->getPaymentMarkWhatIsPaypalUrl($this->localeResolver), 'paymentAcceptanceMarkSrc' => $this->config->getPaymentMarkImageUrl($this->localeResolver->getLocale())]]]; foreach ($this->methodCodes as $code) { if ($this->methods[$code]->isAvailable()) { $config['payment']['paypalExpress']['redirectUrl'][$code] = $this->getMethodRedirectUrl($code); $config['payment']['paypalExpress']['billingAgreementCode'][$code] = $this->getBillingAgreementCode($code); } } return $config; }
/** * Disable block output if logo turned off *M * @return string */ protected function _toHtml() { $type = $this->getLogoType(); // assigned in layout etc. $logoUrl = $this->_getConfig()->getAdditionalOptionsLogoUrl($this->_localeResolver->getLocale(), $type); if (!$logoUrl) { return ''; } $this->setLogoImageUrl($logoUrl); return parent::_toHtml(); }
/** * Load object by country id and code or default name * * @param \Magento\Framework\Model\AbstractModel $object * @param int $countryId * @param string $value * @param string $field * @return $this */ protected function _loadByCountry($object, $countryId, $value, $field) { $connection = $this->getConnection(); $locale = $this->_localeResolver->getLocale(); $joinCondition = $connection->quoteInto('rname.region_id = region.region_id AND rname.locale = ?', $locale); $select = $connection->select()->from(['region' => $this->getMainTable()])->joinLeft(['rname' => $this->_regionNameTable], $joinCondition, ['name'])->where('region.country_id = ?', $countryId)->where("region.{$field} = ?", $value); $data = $connection->fetchRow($select); if ($data) { $object->setData($data); } $this->_afterLoad($object); return $this; }
/** * Retrieve locale * * @return string */ public function getLocale() { if (null === $this->_localeCode) { $this->_localeCode = $this->_locale->getLocale(); } return $this->_localeCode; }
public function getFormFields() { $locale = $this->_localeResolver->getLocale(); $language = strtoupper(substr($locale, 0, strpos($locale, '_'))); $orderAmount = number_format($this->getOrder()->getGrandTotal(), 2, '.', ''); $billingAddress = $this->getOrder()->getBillingAddress(); $urlReturnOk = $this->_urlBuilder->getUrl("assist/standard/success", array('_secure' => true)); $urlReturnNo = $this->_urlBuilder->getUrl("assist/standard/cancel", array('_secure' => true)); $fields = array('Merchant_ID' => $this->getConfigData('merchant'), 'Delay' => $this->getConfigPaymentAction() == self::ACTION_AUTHORIZE ? 1 : 0, 'OrderNumber' => $this->getOrder()->getRealOrderId(), 'Language' => $language, 'OrderAmount' => $orderAmount, 'OrderCurrency' => $this->getOrder()->getBaseCurrencyCode(), 'Lastname' => $billingAddress->getLastname(), 'Firstname' => $billingAddress->getFirstname(), 'Email' => $this->getOrder()->getCustomerEmail(), 'MobilePhone' => $billingAddress->getMobile(), 'URL_RETURN_OK' => $urlReturnOk, 'URL_RETURN_NO' => $urlReturnNo, 'OrderComment' => '', 'Middlename' => $billingAddress->getMiddlename(), 'Address' => implode(", ", $billingAddress->getStreet()), 'HomePhone' => $billingAddress->getTelephone(), 'WorkPhone' => $billingAddress->getWorkphone(), 'Fax' => $billingAddress->getFax(), 'Country' => $billingAddress->getCountryId(), 'State' => $billingAddress->getRegionCode(), 'City' => $billingAddress->getCity(), 'Zip' => $billingAddress->getPostcode(), 'MobileDevice' => $this->getConfigData('mobile')); $fields = $this->_mergePaymentSystems($fields); /* if (Mage::helper('assist')->isOrderSecuredMd5()) { $x = array( $this->getConfigData('merchant'), $this->getOrder()->getRealOrderId(), $orderAmount, $this->getOrder()->getBaseCurrencyCode() ); $fields['Checkvalue'] = $this->secreyKey(implode(self::SEND_SEPARATOR, $x)); } if (Mage::helper('assist')->isOrderSecuredPgp()) { $y = md5(implode(self::SEND_SEPARATOR, array( $this->getConfigData('merchant'), $this->getOrder()->getRealOrderId(), $orderAmount, $this->getOrder()->getBaseCurrencyCode() ))); $keyFile = Mage::getBaseDir('var') . DS . self::PEM_DIR . DS . $this->getConfigData('merchant_key'); $fields['Signature'] = $this->sign($y, $keyFile); } */ //Mage::helper('assist')->debug($fields); $this->_debugger->debug(var_export($fields, true)); return $fields; }
/** * @param \Magento\Framework\View\Element\Template\Context $context * @param \Magento\Directory\Model\CurrencyFactory $currencyFactory * @param \Magento\Core\Helper\PostData $postDataHelper * @param \Magento\Framework\Locale\ResolverInterface $localeResolver * @param array $data */ public function __construct(\Magento\Framework\View\Element\Template\Context $context, \Magento\Directory\Model\CurrencyFactory $currencyFactory, \Magento\Core\Helper\PostData $postDataHelper, \Magento\Framework\Locale\ResolverInterface $localeResolver, array $data = array()) { $this->_currencyFactory = $currencyFactory; $this->_postDataHelper = $postDataHelper; parent::__construct($context, $data); $this->_locale = $localeResolver->getLocale(); }
/** * Convert collection items to select options array * * @param string|boolean $emptyLabel * @return array */ public function toOptionArray($emptyLabel = ' ') { $options = $this->_toOptionArray('country_id', 'name', ['title' => 'iso2_code']); $sort = []; foreach ($options as $data) { $name = (string) $this->_localeLists->getCountryTranslation($data['value']); if (!empty($name)) { $sort[$name] = $data['value']; } } $this->_arrayUtils->ksortMultibyte($sort, $this->_localeResolver->getLocale()); foreach (array_reverse($this->_foregroundCountries) as $foregroundCountry) { $name = array_search($foregroundCountry, $sort); unset($sort[$name]); $sort = [$name => $foregroundCountry] + $sort; } $options = []; foreach ($sort as $label => $value) { $option = ['value' => $value, 'label' => $label]; if ($this->helperData->isRegionRequired($value)) { $option['is_region_required'] = true; } $options[] = $option; } if (count($options) > 0 && $emptyLabel !== false) { array_unshift($options, ['value' => '', 'label' => $emptyLabel]); } return $options; }
/** * @return \Magento\Framework\View\Element\AbstractBlock */ protected function _beforeToHtml() { $result = parent::_beforeToHtml(); /** @var \Magento\Paypal\Model\Config $config */ $config = $this->_paypalConfigFactory->create(); $config->setMethod($this->_paymentMethodCode); $isInCatalog = $this->getIsInCatalogProduct(); if (!$this->_shortcutValidator->validate($this->_paymentMethodCode, $isInCatalog)) { $this->_shouldRender = false; return $result; } $quote = $isInCatalog || !$this->_checkoutSession ? null : $this->_checkoutSession->getQuote(); // set misc data $this->setShortcutHtmlId($this->_mathRandom->getUniqueHash('ec_shortcut_'))->setCheckoutUrl($this->getUrl($this->_startAction)); // use static image if in catalog if ($isInCatalog || null === $quote) { $this->setImageUrl($config->getExpressCheckoutShortcutImageUrl($this->_localeResolver->getLocale())); } else { /**@todo refactor checkout model. Move getCheckoutShortcutImageUrl to helper or separate model */ $parameters = ['params' => ['quote' => $quote, 'config' => $config]]; $checkoutModel = $this->_checkoutFactory->create($this->_checkoutType, $parameters); $this->setImageUrl($checkoutModel->getCheckoutShortcutImageUrl()); } // ask whether to create a billing agreement $customerId = $this->currentCustomer->getCustomerId(); // potential issue for caching if ($this->_paypalData->shouldAskToCreateBillingAgreement($config, $customerId)) { $this->setConfirmationUrl($this->getUrl($this->_startAction, [\Magento\Paypal\Model\Express\Checkout::PAYMENT_INFO_TRANSPORT_BILLING_AGREEMENT => 1])); $this->setConfirmationMessage(__('Would you like to sign a billing agreement to streamline further purchases with PayPal?')); } return $result; }
/** * Save translation * * @param String $string * @param String $translate * @param String $locale * @param int|null $storeId * @return $this */ public function saveTranslate($string, $translate, $locale = null, $storeId = null) { $write = $this->_getWriteAdapter(); $table = $this->getMainTable(); if ($locale === null) { $locale = $this->_localeResolver->getLocale(); } if ($storeId === null) { $storeId = $this->getStoreId(); } $select = $write->select()->from($table, ['key_id', 'translate'])->where('store_id = :store_id')->where('locale = :locale')->where('string = :string')->where('crc_string = :crc_string'); $bind = ['store_id' => $storeId, 'locale' => $locale, 'string' => $string, 'crc_string' => crc32($string)]; if ($row = $write->fetchRow($select, $bind)) { $original = $string; if (strpos($original, '::') !== false) { list(, $original) = explode('::', $original); } if ($original == $translate) { $write->delete($table, ['key_id=?' => $row['key_id']]); } elseif ($row['translate'] != $translate) { $write->update($table, ['translate' => $translate], ['key_id=?' => $row['key_id']]); } } else { $write->insert($table, ['store_id' => $storeId, 'locale' => $locale, 'string' => $string, 'translate' => $translate, 'crc_string' => crc32($string)]); } return $this; }
/** * Get locale * * @return string */ public function getLocale() { if (null === $this->_locale) { $this->_locale = $this->objectManager->get('Magento\\Framework\\Locale\\ResolverInterface'); } return $this->_locale->getLocale(); }
/** * Apply normalization filter to item qty value * * @param int $itemQty * @return int|array */ protected function normalize($itemQty) { if ($itemQty) { $filter = new \Zend_Filter_LocalizedToNormalized(['locale' => $this->resolver->getLocale()]); return $filter->filter($itemQty); } return $itemQty; }
/** * {@inheritdoc} */ public function getConfig() { $locale = $this->localeResolver->getLocale(); $config = ['payment' => ['paypalExpress' => ['paymentAcceptanceMarkHref' => $this->config->getPaymentMarkWhatIsPaypalUrl($this->localeResolver), 'paymentAcceptanceMarkSrc' => $this->config->getPaymentMarkImageUrl($locale), 'isContextCheckout' => false, 'inContextConfig' => []]]]; $isInContext = $this->isInContextCheckout(); if ($isInContext) { $config['payment']['paypalExpress']['isContextCheckout'] = $isInContext; $config['payment']['paypalExpress']['inContextConfig'] = ['inContextId' => self::IN_CONTEXT_BUTTON_ID, 'merchantId' => $this->config->getValue('merchant_id'), 'path' => $this->urlBuilder->getUrl('paypal/express/gettoken', ['_secure' => true]), 'clientConfig' => ['environment' => (int) $this->config->getValue('sandbox_flag') ? 'sandbox' : 'production', 'locale' => $locale, 'button' => [self::IN_CONTEXT_BUTTON_ID]]]; } foreach ($this->methodCodes as $code) { if ($this->methods[$code]->isAvailable()) { $config['payment']['paypalExpress']['redirectUrl'][$code] = $this->getMethodRedirectUrl($code); $config['payment']['paypalExpress']['billingAgreementCode'][$code] = $this->getBillingAgreementCode($code); } } return $config; }
/** * @inheritdoc */ public function getCountryTranslation($value, $locale = null) { if ($locale == null) { return (new RegionBundle())->get($this->localeResolver->getLocale())['Countries'][$value]; } else { return (new RegionBundle())->get($locale)['Countries'][$value]; } }
/** * @param Filter $filter * @param TimezoneInterface $localeDate * @param ResolverInterface $localeResolver * @param string $dateFormat * @param array $data */ public function __construct(Filter $filter, TimezoneInterface $localeDate, ResolverInterface $localeResolver, $dateFormat = 'M j, Y H:i:s A', array $data = []) { $this->filter = $filter; $this->localeDate = $localeDate; $this->locale = $localeResolver->getLocale(); $this->dateFormat = $dateFormat; $this->data = $data; }
/** * Get Key pieces for caching block content * * @return array */ public function getCacheKeyInfo() { $cacheKeyInfo = ['admin_top_nav', $this->getActive(), $this->_authSession->getUser()->getId(), $this->_localeResolver->getLocale()]; // Add additional key parameters if needed $newCacheKeyInfo = $this->getAdditionalCacheKeyInfo(); if (is_array($newCacheKeyInfo) && !empty($newCacheKeyInfo)) { $cacheKeyInfo = array_merge($cacheKeyInfo, $newCacheKeyInfo); } return $cacheKeyInfo; }
/** * Retrieve list of months translation * * @return array * @api */ public function getMonths() { $data = []; $months = (new DataBundle())->get($this->localeResolver->getLocale())['calendar']['gregorian']['monthNames']['format']['wide']; foreach ($months as $key => $value) { $monthNum = ++$key < 10 ? '0' . $key : $key; $data[$key] = $monthNum . ' - ' . $value; } return $data; }
/** * Convert dimensions in different measure types * * @param int|float $value * @param string $sourceDimensionMeasure * @param string $toDimensionMeasure * @return int|null|string */ public function convertMeasureDimension($value, $sourceDimensionMeasure, $toDimensionMeasure) { if ($value) { $locale = $this->localeResolver->getLocale(); $unitDimension = new \Zend_Measure_Length($value, $sourceDimensionMeasure, $locale); $unitDimension->setType($toDimensionMeasure); return $unitDimension->getValue(); } return null; }
/** * @param \Magento\Framework\View\Asset\Repository $assetRepo * @param \Magento\Framework\View\Asset\GroupedCollection $pageAssets * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig * @param \Magento\Framework\View\Page\FaviconInterface $favicon * @param Title $title * @param \Magento\Framework\Locale\ResolverInterface $localeResolver */ public function __construct(View\Asset\Repository $assetRepo, View\Asset\GroupedCollection $pageAssets, App\Config\ScopeConfigInterface $scopeConfig, View\Page\FaviconInterface $favicon, Title $title, \Magento\Framework\Locale\ResolverInterface $localeResolver) { $this->assetRepo = $assetRepo; $this->pageAssets = $pageAssets; $this->scopeConfig = $scopeConfig; $this->favicon = $favicon; $this->title = $title; $this->localeResolver = $localeResolver; $this->setElementAttribute(self::ELEMENT_TYPE_HTML, self::HTML_ATTRIBUTE_LANG, str_replace('_', '-', $this->localeResolver->getLocale())); }