Пример #1
0
 /**
  * Get name format based on locale, if locale is not passed locale from system configuration will be used.
  *
  * @param string|null $locale
  * @throws \RuntimeException
  */
 public function getNameFormat($locale = null)
 {
     if (!$locale) {
         $locale = $this->localeSettings->getLocale();
     }
     $nameFormats = $this->localeSettings->getNameFormats();
     // match by locale (for example - "fr_CA")
     if (isset($nameFormats[$locale])) {
         return $nameFormats[$locale];
     }
     // match by locale language (for example - "fr")
     $localeParts = \Locale::parseLocale($locale);
     if (isset($localeParts[\Locale::LANG_TAG])) {
         $match = $localeParts[\Locale::LANG_TAG];
         if (isset($match, $nameFormats[$match])) {
             return $nameFormats[$match];
         }
     }
     // match by default locale in system configuration settings
     $match = $this->localeSettings->getLocale();
     if ($match !== $locale && isset($nameFormats[$match])) {
         return $nameFormats[$match];
     }
     // fallback to default constant locale
     $match = LocaleConfiguration::DEFAULT_LOCALE;
     if (isset($nameFormats[$match])) {
         return $nameFormats[$match];
     }
     throw new \RuntimeException(sprintf('Cannot get name format for "%s"', $locale));
 }
Пример #2
0
 /**
  * Build locale object from a string.
  *
  * @param string $locale The locale as string
  *
  * @return Locale A Locale object
  */
 public static function parse($locale)
 {
     if (empty($locale)) {
         throw new \InvalidArgumentException('Locale string can not be empty');
     }
     $result = \Locale::parseLocale($locale);
     if (!is_array($result)) {
         throw new \RuntimeException(sprintf('Unable to parse locale "%s"', $locale));
     }
     $language = null;
     $region = null;
     $variants = array();
     foreach ($result as $key => $value) {
         if ('language' === $key) {
             $language = new Language($value);
         } elseif ('region' === $key) {
             $region = new Region($value);
         } elseif (0 === strpos($key, 'variant')) {
             $variants[] = new Variant($value);
         }
     }
     if (null === $language) {
         throw new \RuntimeException(sprintf('Unable to retrieve a valid language for locale "%s"', $locale));
     }
     return new self($language, $region, $variants);
 }
Пример #3
0
 /**
  * Parse header
  *
  * @param   null|\Zend\Http\Header\AcceptLanguage   $header
  * @return  array
  */
 public function parseHeader($header)
 {
     $locales = array();
     $controller = $this->getController();
     if ($controller instanceof ServiceLocatorAwareInterface) {
         $availables = $controller->getServiceLocator()->get('Locale')->getAvailableLocales();
     } else {
         $availables = array(IntlLocale::getDefault());
     }
     if ($header instanceof AcceptLanguage) {
         foreach ($header->getPrioritized() as $part) {
             if ($part instanceof LanguageFieldValuePart) {
                 $locale = IntlLocale::parseLocale($part->getLanguage());
                 $key = $locale['language'];
                 if (isset($locale['region'])) {
                     $key .= '_' . $locale['region'];
                 }
                 if ($availables) {
                     $key = IntlLocale::lookup($availables, $key, false, '');
                 }
                 if ($key) {
                     $locales[$key] = max($part->getPriority(), empty($locales[$key]) ? 0 : $locales[$key]);
                 }
             }
         }
     }
     return $locales;
 }
 /**
  * set Language to Session
  * 
  * @param string $lang Requested language
  */
 protected function setSessionLanguage($lang)
 {
     session()->set('applocale', $lang);
     $locale = \Locale::parseLocale($lang);
     session()->set('language', $locale['language']);
     $this->log->info("Language Switched:{$locale['language']}");
 }
Пример #5
0
 public function __construct($locale)
 {
     $this->localeArray = Locale::parseLocale($locale);
     $this->localeString = Locale::composeLocale($this->localeArray);
     $this->initMonths();
     $this->initDays();
     $this->initPattern();
 }
 public function convert($locale)
 {
     $parts = \Locale::parseLocale($locale);
     if (!isset($parts['region'])) {
         $parts['region'] = $this->country;
     }
     $locale = \Locale::canonicalize(\Locale::composeLocale($parts));
     return $locale;
 }
Пример #7
0
 /**
  * Switch Language
  *
  * @param  string  $lang    Language iso code
  * @param  Session $session Session Facade
  * @return Redirect         HTTP Redirect
  */
 public function switchLang($lang)
 {
     $this->log->info("Language switch Request to {$lang}");
     if (array_key_exists($lang, config()->get('languages'))) {
         $this->log->info('Language Switched');
         session()->set('applocale', $lang);
         $locale = \Locale::parseLocale($lang);
         session()->set('language', $locale['language']);
     }
     return redirect()->back();
 }
Пример #8
0
 /**
  * Normalize locale
  *
  * @param string $locale
  * @return string
  */
 public static function normalizeLocale($locale)
 {
     $parsed = IntlLocale::parseLocale($locale);
     if (empty($parsed) || empty($parsed['language'])) {
         return null;
     }
     $result = $parsed['language'];
     if (!empty($parsed['region'])) {
         $result .= '_' . strtoupper($parsed['region']);
     }
     return $result;
 }
Пример #9
0
 /**
  * Clean locale leaving only language and script
  *
  * @param string $locale
  * @return string
  */
 protected function cleanLocale($locale)
 {
     $localeParts = \Locale::parseLocale($locale);
     $cleanLocaleParts = [];
     if (isset($localeParts['language'])) {
         $cleanLocaleParts['language'] = $localeParts['language'];
     }
     if (isset($localeParts['script'])) {
         $cleanLocaleParts['script'] = $localeParts['script'];
     }
     return \Locale::composeLocale($cleanLocaleParts);
 }
Пример #10
0
 public function actionScan($argv)
 {
     if (count($argv) < 1) {
         exit("usage: gini i18n scan [<locales>]\n");
     }
     $info = \Gini\Core::moduleInfo(APP_ID);
     if (!isset($info->id)) {
         echo "gini i18n scan: Invalid app path!\n";
         exit;
     }
     $path = $info->path;
     $domain = str_replace('/', '-', $info->id);
     $l10n_path = $path . '/' . RAW_DIR . '/l10n';
     \Gini\File::ensureDir($l10n_path);
     $l10n_template = $l10n_path . '/template.pot';
     if (file_exists($l10n_template)) {
         unlink($l10n_template);
     }
     $keywords = '--keyword=T';
     //$package = sprintf('--package-name=%s --package-version=%s',
     $cmd = sprintf('cd %s && find class view -name "*.php" -o -name "*.phtml" | xargs xgettext -LPHP %s --from-code=UTF-8 -i --copyright-holder=%s --foreign-user --package-name=%s --package-version=%s --msgid-bugs-address=%s -o %s', escapeshellarg($path), $keywords, escapeshellarg($info->author ?: 'Gini Team'), escapeshellarg($info->id), escapeshellarg($info->version), escapeshellarg($info->email ?: '*****@*****.**'), escapeshellarg($l10n_template));
     passthru($cmd);
     // extract msgid ""{context}\004{txt} to msgctxt and msgid
     $cmd = sprintf("sed 's/msgid   \"\\(.*\\)''/msgctxt \"\\1\"\\nmsgid \"/g' %s", escapeshellarg($l10n_template));
     // echo $cmd . "\n"; die;
     file_put_contents($l10n_template, `{$cmd}`);
     $locales = $argv;
     foreach (glob($l10n_path . '/*.po') as $fname) {
         $locale = basename($fname, '.po');
         $locales[] = $locale;
     }
     foreach (array_unique($locales) as $locale) {
         $locale_arr = \Locale::parseLocale($locale);
         if (!isset($locale_arr['language'])) {
             continue;
         }
         $l10n_pofile = $l10n_path . '/' . $locale . '.po';
         if (!file_exists($l10n_pofile)) {
             $cmd = sprintf('msginit --no-translator -o %1$s -i %2$s -l %3$s', escapeshellarg($l10n_pofile), escapeshellarg($l10n_template), escapeshellarg($locale));
         } else {
             $cmd = sprintf('msgmerge --update --suffix=none --no-fuzzy-matching -q %1$s %2$s', escapeshellarg($l10n_pofile), escapeshellarg($l10n_template));
         }
         passthru($cmd);
     }
     echo "done.\n";
     //merge po file to different locale directory
 }
Пример #11
0
 /**
  * Returns the ISO representation of the locale
  * ("lang-REGION" as opposed to its canonical "lang_REGION")
  *
  * @return string
  */
 public function toIso()
 {
     $locale = IntlLocale::parseLocale($this->getCurrent());
     $result = $locale['language'];
     if (!empty($locale['region'])) {
         $result .= '-' . $locale['region'];
     }
     return $result;
 }
Пример #12
0
 /**
  * Sets the locale to the given locale
  *
  * This function will also set the "old" setlocale, mainly timezone support for PHP5.3 - PHP5.5
  *
  * @param string $locale Locale we want to set in RFC 4646 format
  * @return string Returns the setted locale
  */
 public function setDefault($locale)
 {
     $result = '';
     if (!empty($locale)) {
         $locale = \Locale::parseLocale($locale);
         $locale = \Locale::composeLocale($locale);
         \Locale::setDefault($locale);
         $result = $this->getDefault();
         $this->_setOptions();
     }
     return $result;
 }
Пример #13
0
 /**
  * Parses a locale string and returns an array of key-value locale tags.
  *
  * @uses Locale
  *
  * @param string $locale
  * @return string
  */
 public static function decompose($locale)
 {
     return \Locale::parseLocale($locale);
 }
Пример #14
0
 /**
  * Normalize locale
  *
  * @param   string  $locale
  * @return  string
  */
 public static function normalizeLocale($locale)
 {
     if (empty($locale)) {
         return '';
     }
     $parsed = IntlLocale::parseLocale($locale);
     // @codeCoverageIgnoreStart
     if (empty($parsed) || empty($parsed['language'])) {
         return $locale;
     }
     // @codeCoverageIgnoreEnd
     $result = strtolower($parsed['language']);
     if (!empty($parsed['region'])) {
         $result .= '_' . strtoupper($parsed['region']);
     }
     return $result;
 }
Пример #15
0
 public function setLocale($category, $candidates)
 {
     $categoryName = self::categoryToName($category);
     if (!is_array($candidates)) {
         $candidates = array($candidates);
     }
     if (!count($candidates)) {
         throw new \InvalidArgumentException('Invalid locale');
     }
     $base = $this->getBaseDir($this->component);
     $newLocale = null;
     foreach ($candidates as $candidate) {
         if (!is_string($candidate)) {
             throw new \InvalidArgumentException('Invalid locale');
         }
         $locale = \Locale::parseLocale($candidate);
         if (!is_array($locale) || !isset($locale['language'])) {
             throw new \InvalidArgumentException('Invalid locale');
         }
         // For anything else than LC_MESSAGES,
         // we take the first candidate as is.
         if ($categoryName != 'LC_MESSAGES') {
             $newLocale = $candidate;
         }
         if ($newLocale !== null) {
             continue;
         }
         $catalog = str_replace('\\', '_', ltrim($this->component, '\\'));
         if (isset($locale['region'])) {
             $normLocale = $locale['language'] . '_' . $locale['region'];
             $file = $base . DIRECTORY_SEPARATOR . $normLocale . DIRECTORY_SEPARATOR . $categoryName . DIRECTORY_SEPARATOR . $catalog . '.mo';
             if (file_exists($file)) {
                 $newLocale = $normLocale;
                 continue;
             }
         }
         $file = $base . DIRECTORY_SEPARATOR . $locale['language'] . DIRECTORY_SEPARATOR . $categoryName . DIRECTORY_SEPARATOR . $catalog . '.mo';
         if (file_exists($file)) {
             $newLocale = $locale['language'];
             continue;
         }
     }
     if ($newLocale === null) {
         $newLocale = 'en_US';
     }
     $this->locales[$category] = $newLocale;
     return $newLocale;
 }
Пример #16
0
 /**
  * set locale system-wide
  * @param \Zend\Mvc\MvcEvent $e
  */
 public function setDefaultLocale(MvcEvent $e)
 {
     static::$alias = $e->getRouteMatch()->getParam(self::LOCALE_ROUTE_PARAM);
     static::$locale = static::getLocaleByAlias(static::$alias);
     if (Locale::setDefault(static::$locale) === false) {
         throw new \RuntimeException(sprintf('Not valid locale %s to set it as default', static::$locale));
     }
     // Set translator
     $translator = $e->getApplication()->getServiceManager()->get('MvcTranslator');
     $parsedLocale = \Locale::parseLocale(static::$locale);
     $languageAndRegion = $parsedLocale['language'] . '-' . $parsedLocale['region'];
     $translator->setLocale($languageAndRegion);
 }
Пример #17
0
 /**
  * Tries to find Language entity by string. String should be in correct RFC3066bis standard.
  *
  * @param string $languageString  Language string
  * @param string $firstResultOnly Return first result
  *
  * @return \Newscoop\Entity\Language|null Returns found entity or null
  */
 public function findByRFC3066bis($languageString, $firstResultOnly = true)
 {
     if (count(explode('-', $languageString)) < 2) {
         throw new \Exception('Language string in correct according to RFC3066bis standard.', 1);
     }
     $queryBuilder = $this->getEntityManager()->getRepository('\\Newscoop\\Entity\\Language')->createQueryBuilder('L');
     $localeArray = \Locale::parseLocale($languageString);
     if (array_key_exists('language', $localeArray) && array_key_exists('region', $localeArray) && array_key_exists('script', $localeArray)) {
         $queryBuilder->where('L.RFC3066bis = :longLocale')->orWhere('L.RFC3066bis = :shortLocale')->setParameter('longLocale', $localeArray['language'] . '-' . $localeArray['script'] . '-' . $localeArray['region'])->setParameter('shortLocale', $localeArray['language'] . '-' . $localeArray['region']);
     } elseif (array_key_exists('language', $localeArray) && array_key_exists('script', $localeArray)) {
         $queryBuilder->where('L.RFC3066bis = :strictLocale')->orWhere('L.RFC3066bis LIKE :nonStrictLocale')->setParameter('strictLocale', $localeArray['language'] . '-' . $localeArray['script'])->setParameter('nonStrictLocale', $localeArray['language'] . '-' . $localeArray['script'] . '%');
     } elseif (array_key_exists('language', $localeArray) && array_key_exists('region', $localeArray)) {
         $queryBuilder->where('L.RFC3066bis = :strictLocale')->orWhere('L.RFC3066bis LIKE :nonStrictLocale')->setParameter('strictLocale', $localeArray['language'] . '-' . $localeArray['region'])->setParameter('nonStrictLocale', $localeArray['language'] . '-%' . $localeArray['region']);
     } else {
         throw new \Exception('Parsed RFC3066bis string did not match expected results.', 1);
     }
     $foundLanguages = $queryBuilder->getQuery()->getResult();
     return $firstResultOnly ? $foundLanguages[0] : $foundLanguages;
 }
 private function getLanguage($locale)
 {
     $parts = \Locale::parseLocale($locale);
     return $parts['language'];
 }
Пример #19
0
function updateLocaleSetting($locale)
{
    global $error, $Settings, $success;
    if ($Settings->getSetting('locale') == $locale) {
        return true;
    }
    $newLocale = Locale::parseLocale($locale);
    // If ['language'] isn't set, then we can't pick a language, so whole Locale is invalid. Region part of Locale isn't as important as Language is. Could default to English if no langauge, so Region would work, but they could just append en_ to the locale themself
    if (isset($newLocale['language'])) {
        $locale = Locale::composeLocale($newLocale);
        if ($Settings->setSetting('locale', $locale)) {
            // Apply new locale so language displays correctly from now on
            \Grase\Locale::applyLocale($locale);
            $success[] = T_("Locale updated");
            AdminLog::getInstance()->log(T_("Locale updated to") . $locale);
        } else {
            $error[] = T_("Error updating Locale");
        }
    } else {
        $error[] = T_("Invalid Locale");
    }
}
Пример #20
0
 /**
  * Returns a key-value array of locale ID subtag elements
  *
  * @return array Returns an array containing a list of key-value pairs,
  *     where the keys identify the particular locale ID subtags, and the
  *     values are the associated subtag values. The array will be ordered
  *     as the locale id subtags e.g. in the locale id if variants are
  *     '-varX-varY-varZ' then the returned array will have variant0=>varX ,
  *     variant1=>varY , variant2=>varZ
  */
 public function parseLocale()
 {
     return IntlLocale::parseLocale($this->getLocale());
 }
Пример #21
0
 /**
  * Parses a locale into components.
  *
  * @param  reference $language The two-letter language code of type `CUStringObject` (always lowercased).
  * @param  reference $region **OPTIONAL. OUTPUT.** The two-letter country/region code of type `CUStringObject`
  * (always uppercased).
  * @param  reference $script **OPTIONAL. OUTPUT.** The four-letter script code of type `CUStringObject` (always
  * titlecased).
  * @param  reference $variants **OPTIONAL. OUTPUT.** The variants of type `CArrayObject` with elements of type
  * `CUStringObject` (always uppercased).
  * @param  reference $keywords **OPTIONAL. OUTPUT.** The keyword-value pairs of type `CMapObject` with values of
  * type `CUStringObject`.
  *
  * @return void
  */
 public function components(&$language, &$region = null, &$script = null, &$variants = null, &$keywords = null)
 {
     $subtags = Locale::parseLocale($this->m_name);
     if (CMap::hasKey($subtags, Locale::LANG_TAG)) {
         $language = $subtags[Locale::LANG_TAG];
     }
     if (CMap::hasKey($subtags, Locale::REGION_TAG)) {
         $region = $subtags[Locale::REGION_TAG];
     }
     if (CMap::hasKey($subtags, Locale::SCRIPT_TAG)) {
         $script = $subtags[Locale::SCRIPT_TAG];
     }
     $variants = CArray::make();
     for ($i = 0; $i < 15; $i++) {
         $key = Locale::VARIANT_TAG . $i;
         if (CMap::hasKey($subtags, $key)) {
             CArray::push($variants, $subtags[$key]);
         }
     }
     $variants = oop_a($variants);
     $keywords = oop_m($this->keywords($this->m_name));
 }
 /**
  * Get address format based on locale or region, if argument is not passed locale from
  * system configuration will be used.
  *
  * @param string|null $localeOrRegion
  * @throws \RuntimeException
  */
 public function getAddressFormat($localeOrRegion = null)
 {
     if (!$localeOrRegion) {
         $localeOrRegion = $this->localeSettings->getLocale();
     }
     $addressFormats = $this->localeSettings->getAddressFormats();
     // matched by country (for example - "RU")
     if (isset($addressFormats[$localeOrRegion][LocaleSettings::ADDRESS_FORMAT_KEY])) {
         return $addressFormats[$localeOrRegion][LocaleSettings::ADDRESS_FORMAT_KEY];
     }
     // matched by locale region - "CA"
     $localeParts = \Locale::parseLocale($localeOrRegion);
     if (isset($localeParts[\Locale::REGION_TAG])) {
         $match = $localeParts[\Locale::REGION_TAG];
         if (isset($match, $addressFormats[$match][LocaleSettings::ADDRESS_FORMAT_KEY])) {
             return $addressFormats[$match][LocaleSettings::ADDRESS_FORMAT_KEY];
         }
     }
     // match by default country in system configuration settings
     $match = $this->localeSettings->getCountry();
     if ($match !== $localeOrRegion && isset($addressFormats[$match][LocaleSettings::ADDRESS_FORMAT_KEY])) {
         return $addressFormats[$match][LocaleSettings::ADDRESS_FORMAT_KEY];
     }
     // fallback to default country
     $match = LocaleConfiguration::DEFAULT_COUNTRY;
     if (isset($addressFormats[$match][LocaleSettings::ADDRESS_FORMAT_KEY])) {
         return $addressFormats[$match][LocaleSettings::ADDRESS_FORMAT_KEY];
     }
     throw new \RuntimeException(sprintf('Cannot get address format for "%s"', $localeOrRegion));
 }
Пример #23
0
 /**
  * Instantiate the locale and message bundles using the resource paths.
  *
  * @uses Locale
  * @uses Titon\Common\Config
  *
  * @return $this
  */
 public function initialize()
 {
     if ($data = $this->getLocaleBundle()->loadResource(null, 'locale')) {
         $data = \Locale::parseLocale($data['code']) + $data;
         $config = $this->allConfig();
         unset($config['code'], $config['initialize']);
         $this->addConfig($config + $data);
     }
     // Force parent config to merge
     $this->getParentLocale();
     return $this;
 }
Пример #24
0
 public static function normalize($locale)
 {
     return str_replace('_', '-', \Locale::composeLocale(\Locale::parseLocale($locale)));
 }
 /**
  * Try to parse locale and return it in format "language"_"region",
  * if locale is empty or cannot be parsed then return locale
  *
  * @param string $locale
  * @throws \RuntimeException
  * @return string
  */
 public static function getValidLocale($locale = null)
 {
     if (!$locale) {
         $locale = LocaleConfiguration::DEFAULT_LOCALE;
     }
     $localeParts = \Locale::parseLocale($locale);
     $lang = null;
     $script = null;
     $region = null;
     if (isset($localeParts[\Locale::LANG_TAG])) {
         $lang = $localeParts[\Locale::LANG_TAG];
     }
     if (isset($localeParts[\Locale::SCRIPT_TAG])) {
         $script = $localeParts[\Locale::SCRIPT_TAG];
     }
     if (isset($localeParts[\Locale::REGION_TAG])) {
         $region = $localeParts[\Locale::REGION_TAG];
     }
     $variants = array(array($lang, $script, $region), array($lang, $region), array($lang, $script, LocaleConfiguration::DEFAULT_COUNTRY), array($lang, LocaleConfiguration::DEFAULT_COUNTRY), array($lang), array(LocaleConfiguration::DEFAULT_LOCALE, LocaleConfiguration::DEFAULT_COUNTRY), array(LocaleConfiguration::DEFAULT_LOCALE));
     $locales = self::getLocales();
     foreach ($variants as $elements) {
         $locale = implode('_', array_filter($elements));
         if (isset($locales[$locale])) {
             return $locale;
         }
     }
     throw new \RuntimeException(sprintf('Cannot validate locale "%s"', $locale));
 }
Пример #26
0
 /**
  * Parses a locale string.
  *
  * @param string $locale
  *
  * @return Locale
  *
  * @throws \InvalidArgumentException
  */
 public static function parse($locale)
 {
     $locale = (string) $locale;
     if ($locale === '') {
         throw new \InvalidArgumentException('Locale string cannot be empty.');
     }
     $subtags = \Locale::parseLocale($locale);
     return self::build($subtags);
 }