本文整理汇总了PHP中Locale::getPrimaryLanguage方法的典型用法代码示例。如果您正苦于以下问题:PHP Locale::getPrimaryLanguage方法的具体用法?PHP Locale::getPrimaryLanguage怎么用?PHP Locale::getPrimaryLanguage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Locale
的用法示例。
在下文中一共展示了Locale::getPrimaryLanguage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: parseData
protected function parseData($path)
{
preg_match('~guide-?(.*)/(.+)\\.md$~', $path, $matches);
$language = $matches[1] ? $matches[1] : Yii::$app->sourceLanguage;
$language = Locale::getPrimaryLanguage($language);
$slug = strtolower($matches[2]);
$doc = file_get_contents($path);
$doc = Markdown::process($doc, 'gfm');
$html = new HTMLDocument();
@$html->loadHTML($doc);
$html->addPrefix("/{lang}/", 'a', 'href');
$imgPath = dirname($path) . '/images';
$imgPath = $this->publishImages($imgPath);
if ($imgPath) {
$html->addPrefix(function ($src) use($imgPath) {
return $imgPath . '/' . basename($src);
}, 'img', 'src');
}
foreach (['h1', 'h2', 'h3', 'h4'] as $tag) {
/** @var \DOMElement $item */
foreach ($html->getElementsByTagName($tag) as $item) {
/** @var \DOMElement $span */
if ($span = $item->getElementsByTagName('span')[0]) {
$item->setAttribute('id', $span->getAttribute('id'));
}
}
}
/** @var DOMElement $title */
$title = $html->getElementsByTagName('h1')[0];
return ['language' => $language, 'slug' => $slug, 'title' => $title->textContent, 'description' => $html->saveHTML()];
}
示例2: __invoke
/**
* @param $name
* @return string
*/
public function __invoke($name)
{
if ($this->fragments == null) {
//
$serviceManager = $this->event->getApplication()->getServiceManager();
// get translator
$translator = $serviceManager->get('Translator');
$locale = $translator->getLocale();
$language = \Locale::getPrimaryLanguage($locale);
// try to get fragments from cache
$cache = $serviceManager->get('Application\\Cache');
if ($cache) {
$cacheKey = sprintf('page-fragments-%s-%s', $this->page->getId(), $language);
$page_fragments = $cache->getItem($cacheKey);
}
// fetch from the DB
if ($page_fragments == null) {
/** @var \Doctrine\ORM\EntityManager $entity_manager */
$entity_manager = $serviceManager->get('Doctrine\\ORM\\EntityManager');
$page_fragments_repository = $entity_manager->getRepository('Msingi\\Cms\\Entity\\PageFragment');
$page_fragments = $page_fragments_repository->fetchFragmentsArray($this->page->getId(), $language);
}
// store to cache
if ($cache) {
$cache->setItem($cacheKey, $page_fragments);
}
$this->fragments = $page_fragments;
}
return isset($this->fragments[$name]) ? $this->fragments[$name] : '';
}
示例3: validate
/**
* Validates a Locale
*
* @param string $locale The locale to be validated
* @param Constraint $constraint Locale Constraint
*
* @throws UnexpectedTypeException
*/
public function validate($locale, Constraint $constraint)
{
if (null === $locale || '' === $locale) {
return;
}
if (!is_scalar($locale) && !(is_object($locale) && method_exists($locale, '__toString'))) {
throw new UnexpectedTypeException($locale, 'string');
}
$locale = (string) $locale;
if ($this->strictMode) {
if (!in_array($locale, $this->getAllowedLocales())) {
$this->context->addViolation($constraint->message, array('%string%' => $locale));
}
} else {
if ($this->intlExtension) {
$primary = \Locale::getPrimaryLanguage($locale);
} else {
$splittedLocale = explode('_', $locale);
$primary = count($splittedLocale) > 1 ? $splittedLocale[0] : $locale;
}
if (!in_array($locale, $this->getAllowedLocales()) && !in_array($primary, $this->getAllowedLocales())) {
$this->context->addViolation($constraint->message, array('%string%' => $locale));
}
}
}
示例4: __invoke
/** {@inheritdoc} */
public function __invoke(\Interop\Container\ContainerInterface $container, $name, callable $callback, array $options = null)
{
$locale = \Locale::getDefault();
$primaryLanguage = \Locale::getPrimaryLanguage($locale);
$mvcTranslator = $callback();
$mvcTranslator->setPluginManager($container->get('TranslatorPluginManager'));
$translator = $mvcTranslator->getTranslator();
// Set language
$translator->setLocale($locale);
if ($primaryLanguage != $locale) {
// Set primary language as fallback, i.e. "de" if locale is "de_DE".
// This enables translation file patterns for "de" to match all
// variants.
$translator->setFallbackLocale($primaryLanguage);
}
// Load translations for ZF validator messages
$translator->addTranslationFilePattern('phparray', \Zend\I18n\Translator\Resources::getBasePath(), \Zend\I18n\Translator\Resources::getPatternForValidator());
// Set up event listener for missing translations
if ($primaryLanguage != 'en') {
$config = $container->get('Library\\UserConfig');
if (@$config['debug']['report missing translations']) {
$translator->enableEventManager();
$translator->getEventManager()->attach(\Zend\I18n\Translator\Translator::EVENT_MISSING_TRANSLATION, array($this, 'onMissingTranslation'));
}
}
return $mvcTranslator;
}
示例5: switchAction
/**
* Action for locale switch
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @param $_locale The locale to set
*
* @return \Symfony\Bundle\FrameworkBundle\Controller\RedirectResponse
*
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function switchAction(Request $request, $_locale)
{
// Check if the Language is allowed
if (!in_array(\Locale::getPrimaryLanguage($_locale), $this->allowedLanguages)) {
throw new NotFoundHttpException('This language is not available');
}
// tries to detect a Region from the user-provided locales
$providedLanguages = $request->getLanguages();
$locales = array();
foreach ($providedLanguages as $locale) {
if (strpos($locale . '_', $_locale) !== false && strlen($locale) > 2) {
$locales[] = $locale;
}
}
if (count($locales) > 0) {
$this->session->set('localeIdentified', $locales[0]);
} else {
$this->session->set('localeIdentified', $_locale);
}
// Add the listener
$this->session->set('setLocaleCookie', true);
// Redirect the User
if ($request->headers->has('referer') && true === $this->useReferrer) {
return new RedirectResponse($request->headers->get('referer'));
}
if (null !== $this->redirectToRoute) {
return new RedirectResponse($this->router->generate($this->redirectToRoute));
}
return new RedirectResponse($request->getScheme() . '://' . $request->getHttpHost() . $this->redirectToUrl);
}
示例6: _getOptionLocales
/**
* Get options array for locale dropdown
*
* @param bool $translatedName translation flag
* @return array
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
protected function _getOptionLocales($translatedName = false)
{
$currentLocale = $this->localeResolver->getLocale();
$locales = \ResourceBundle::getLocales('') ?: [];
$languages = (new LanguageBundle())->get($currentLocale)['Languages'];
$countries = (new RegionBundle())->get($currentLocale)['Countries'];
$options = [];
$allowedLocales = $this->_config->getAllowedLocales();
foreach ($locales as $locale) {
if (!in_array($locale, $allowedLocales)) {
continue;
}
$language = \Locale::getPrimaryLanguage($locale);
$country = \Locale::getRegion($locale);
if (!$languages[$language] || !$countries[$country]) {
continue;
}
if ($translatedName) {
$label = ucwords(\Locale::getDisplayLanguage($locale, $locale)) . ' (' . \Locale::getDisplayRegion($locale, $locale) . ') / ' . $languages[$language] . ' (' . $countries[$country] . ')';
} else {
$label = $languages[$language] . ' (' . $countries[$country] . ')';
}
$options[] = ['value' => $locale, 'label' => $label];
}
return $this->_sortOptionArray($options);
}
示例7: getNameForValidNumber
/**
* Returns a carrier name for the given phone number, in the language provided. The carrier name
* is the one the number was originally allocated to, however if the country supports mobile
* number portability the number might not belong to the returned carrier anymore. If no mapping
* is found an empty string is returned.
*
* <p>This method assumes the validity of the number passed in has already been checked, and that
* the number is suitable for carrier lookup. We consider mobile and pager numbers possible
* candidates for carrier lookup.
*
* @param PhoneNumber $number a valid phone number for which we want to get a carrier name
* @param string $languageCode the language code in which the name should be written
* @return string a carrier name for the given phone number
*/
public function getNameForValidNumber(PhoneNumber $number, $languageCode)
{
$languageStr = \Locale::getPrimaryLanguage($languageCode);
$scriptStr = "";
$regionStr = \Locale::getRegion($languageCode);
return $this->prefixFileReader->getDescriptionForNumber($number, $languageStr, $scriptStr, $regionStr);
}
示例8: getBestFit
public static function getBestFit($locale)
{
$primary = Locale::getPrimaryLanguage($locale);
foreach (self::getSystemLocales() as $systemLocale) {
if ($primary === Locale::getPrimaryLanguage($systemLocale)) {
return $systemLocale;
}
}
}
示例9: getLangRows
/**
* @return Generator|array
*/
protected function getLangRows()
{
foreach ($this->getLanguages() as $locale) {
$primaryLanguage = Locale::getPrimaryLanguage($locale);
$displayLanguage = Locale::getDisplayLanguage($locale, $primaryLanguage);
$displayLanguage = mb_convert_case($displayLanguage, MB_CASE_TITLE, "UTF-8");
(yield [$primaryLanguage, $displayLanguage, $locale, 10]);
}
}
示例10: configureOptions
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$configs = $this->options;
$resolver->setDefaults(array('culture' => \Locale::getPrimaryLanguage(\Locale::getDefault()), 'widget' => 'choice', 'years' => range(date('Y') - 5, date('Y') + 5), 'configs' => array('dateFormat' => null)))->setNormalizers(array('configs' => function (Options $options, $value) use($configs) {
$result = array_merge($configs, $value);
if ('single_text' !== $options['widget'] || isset($result['buttonImage'])) {
$result['showOn'] = 'button';
}
return $result;
}));
}
示例11: handle
public function handle($request, Closure $next)
{
if (Session::has('applocale') and array_key_exists(Session::get('applocale'), Config::get('languages'))) {
App::setLocale(Session::get('applocale'));
setlocale(LC_TIME, Session::get('applocale'));
Carbon::setLocale(\Locale::getPrimaryLanguage(Session::get('applocale')));
} else {
App::setLocale(Config::get('app.fallback_locale'));
setlocale(LC_TIME, Config::get('app.fallback_locale'));
Carbon::setLocale(\Locale::getPrimaryLanguage(Config::get('app.fallback_locale')));
}
return $next($request);
}
示例12: onRoute
/**
* Called after routing
*
* @param MvcEvent $event
*/
public function onRoute(MvcEvent $event)
{
$serviceManager = $event->getApplication()->getServiceManager();
/* @var RouteMatch $routeMatch */
$routeMatch = $event->getRouteMatch();
$language = '';
// check if the language is set by routing (parameter, domain name, etc)
if ($routeMatch->getParam('language') == '') {
// get route
$route = explode('/', $routeMatch->getMatchedRouteName());
//
$module = $route[0];
/** @var \Msingi\Cms\Settings $settings */
$settings = $event->getApplication()->getServiceManager()->get('Settings');
// get defaults from settings
$multilanguage = (bool) $settings->get($module . ':languages:multilanguage');
$language_default = $settings->get($module . ':languages:default');
$languages_enabled = $settings->get($module . ':languages:enabled');
if ($multilanguage && is_array($languages_enabled)) {
/** @var \Zend\Http\Request $request */
$request = $event->getRequest();
// try to get language from cookie
if ($request->getCookie('language') != '') {
$language = $event->getRequest()->getCookie('language');
}
// try to get language from browser
if ($language == '' && isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$language = \Locale::getPrimaryLanguage(\Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']));
}
// fallback to default language if given one is not supported
if (!in_array($language, $languages_enabled)) {
$language = $language_default;
}
} else {
// not multilanguage module, use default language
$language = $language_default;
}
$routeMatch->setParam('language', $language);
} else {
$language = $routeMatch->getParam('language');
$language_default = $language;
}
// translator
$translator = $serviceManager->get('Translator');
$translator->setLocale($language)->setFallbackLocale($language_default);
// cache
$cache = $serviceManager->get('Application\\Cache');
if ($cache) {
$translator->setCache($cache);
}
}
示例13: __invoke
/**
*
*
* @param string $templateName
* @param string $to
* @param array $params
* @return
*/
public function __invoke($templateName, $to, array $params = array())
{
// set mail language if not given
if (!isset($params['language']) && $this->translator) {
$params['language'] = \Locale::getPrimaryLanguage($this->translator->getLocale());
}
// set root url if not given
if (!isset($params['root_url']) && $this->router) {
$params['root_url'] = rtrim($this->router->assemble(array('language' => $params['language']), array('name' => 'frontend/index')), '/');
}
//
$params['to'] = $to;
return $this->mailer->sendMail($templateName, $to, $params);
}
示例14: handle
public function handle($request, Closure $next)
{
$sessionAppLocale = session()->get('applocale');
if (session()->has('applocale') and array_key_exists($sessionAppLocale, Config::get('languages'))) {
app()->setLocale($sessionAppLocale);
setlocale(LC_TIME, $sessionAppLocale);
Carbon::setLocale(\Locale::getPrimaryLanguage($sessionAppLocale));
return $next($request);
}
$fallbackLocale = Config::get('app.fallback_locale');
app()->setLocale($fallbackLocale);
setlocale(LC_TIME, $fallbackLocale);
Carbon::setLocale(\Locale::getPrimaryLanguage($fallbackLocale));
return $next($request);
}
示例15: build
/**
* @param string $locale
* @return Context
*/
public function build($locale = null)
{
$context = Context::of();
foreach ($this->defaults as $key => $default) {
$context[$key] = $default;
}
if (is_null($locale)) {
$locale = $context->getLocale();
}
$locale = $this->converter->convert($locale);
$fallbackLanguages = $this->fallbackLanguages;
$language = \Locale::getPrimaryLanguage($locale);
$languages = [$language];
if (isset($fallbackLanguages[$language])) {
$languages = array_merge($languages, $fallbackLanguages[$language]);
}
$context->setLanguages($languages)->setLocale($locale);
return $context;
}