getPreferredLanguage() public method

Returns the preferred language.
public getPreferredLanguage ( array $locales = null ) : string | null
$locales array An array of ordered available locales
return string | null The preferred locale
Example #1
0
 /**
  * Chooses a language for a request
  *
  * @return $response or null
  **/
 public function switchLocaleForRequest(Request $request)
 {
     $session = $request->getSession();
     $parts = explode('.', $request->getHost());
     if (count($parts) === 3) {
         $locale = $parts[0];
         if ($locale == $session->getLocale()) {
             return;
         }
         if ($this->manager->isAvailable($locale)) {
             $session->setLocale($locale);
             $preferred = $request->getPreferredLanguage($this->manager->getAvailableLanguageCodes());
             if ($preferred != $locale) {
                 $session->setFlash('locale_change_adjust', $preferred);
             } else {
                 $session->setFlash('locale_change_contribute', $locale);
             }
             return;
         }
         $host = $parts[1] . '.' . $parts[2];
     } else {
         $host = $parts[0] . '.' . $parts[1];
     }
     $locale = $request->getPreferredLanguage($this->manager->getAvailableLanguageCodes());
     $url = sprintf('http://%s.%s%s', $locale, $host, $request->getRequestUri());
     $response = new RedirectResponse($url);
     $preferredLanguage = $this->getRequestPreferredLanguage($request);
     if ($preferredLanguage && $locale != $preferredLanguage) {
         $allLanguageCodes = array_keys($this->manager->getLanguages());
         if (in_array($preferredLanguage, $allLanguageCodes)) {
             $session->setFlash('locale_missing', $preferredLanguage);
         }
     }
     return $response;
 }
 /**
  * Guess the locale based on the browser settings
  *
  * @param Request $request
  *
  * @return boolean
  */
 public function guessLocale(Request $request)
 {
     $validator = $this->metaValidator;
     // Get the preferred locale from the Browser.
     $preferredLocale = $request->getPreferredLanguage();
     $availableLocales = $request->getLanguages();
     if (!$preferredLocale or count($availableLocales) === 0) {
         return false;
     }
     // If the preferred primary locale is allowed, return the locale.
     if ($validator->isAllowed($preferredLocale)) {
         $this->identifiedLocale = $preferredLocale;
         return true;
     }
     // Get a list of available and allowed locales and return the first result
     $matchLocale = function ($v) use($validator) {
         return $validator->isAllowed($v);
     };
     $result = array_values(array_filter($availableLocales, $matchLocale));
     if (!empty($result)) {
         $this->identifiedLocale = $result[0];
         return true;
     }
     return false;
 }
 /**
  * action for / to redirect to the best language based on the request language order
  */
 public function defaultLanguageAction(Request $request, $contentDocument)
 {
     if (!$contentDocument instanceof RouteAwareInterface) {
         throw new \Exception('The route passed to the language selection action must emulate content to have the correct route generated.');
     }
     // TODO: use lunetics/LocaleBundle https://github.com/symfony-cmf/cmf-sandbox/issues/54
     $defaultPreferredLangs = $this->chooser->getDefaultLocalesOrder();
     $bestLang = $request->getPreferredLanguage($defaultPreferredLangs);
     // we only care about the first 2 characters, even if the user's preference is de_CH.
     $bestLang = substr($bestLang, 0, 2);
     /*
      * Let the router generate the route for the requested language. The
      * route provides its children, which should be the urls for each locale
      * as content.
      */
     $routeParams = $request->query->all();
     // do not lose eventual get parameters
     $routeParams['_locale'] = $bestLang;
     // and set the locale
     $routeParams['content'] = $contentDocument;
     // and the content for the router
     $url = $this->router->generate('', $routeParams, true);
     /* Note: I wanted to send a 300 "Multiple Choices" header along with a
      * Location header, but user agents may behave inconsistently in
      * response to this.
      *
      * For example Chrome was not redirecting unless the headers were
      * carefully tailored for it. (In particular, it doesn't like the
      * lowercase 'location' header that results from calling
      * $response->headers->set('Location', '...')
      */
     $response = new RedirectResponse($url, 301);
     $response->setVary('accept-language');
     return $response;
 }
Example #4
0
 /**
  * Returns the locale from the request, the session or the HTTP header.
  *
  * @param Request $request
  *
  * @return string
  */
 private function getLocale(Request $request)
 {
     if (null !== $request->attributes->get('_locale')) {
         return $this->formatLocaleId($request->attributes->get('_locale'));
     }
     if (null !== ($session = $request->getSession()) && $session->has('_locale')) {
         return $session->get('_locale');
     }
     return $request->getPreferredLanguage($this->availableLocales);
 }
Example #5
0
 /**
  * @Route("/map")
  */
 public function mapAction(Request $request)
 {
     $request->isXmlHttpRequest();
     // is it an Ajax request?
     $request->getPreferredLanguage(array('en', 'fr'));
     $request->query->get('page');
     // get a $_GET parameter
     $request->request->get('page');
     // get a $_POST parameter
     return $this->redirect('http://maps.google.com');
 }
Example #6
0
 public function requestAction(Request $request)
 {
     $page = $request->query->get('page', 1);
     $session = $request->getSession();
     $session->set('foo', 'bar');
     $session->get('foo');
     $request->isXmlHttpRequest();
     // is it an Ajax request?
     $request->getPreferredLanguage(array('en', 'fr'));
     $request->query->get('page');
     // get a $_GET parameter
     $request->request->get('page');
     // get a $_POST parameter
 }
Example #7
0
 /**
  * @Route("/app/example", name="homepage")
  */
 public function indexAction(Request $request)
 {
     // is it an Ajax request?
     $isAjax = $request->isXmlHttpRequest();
     // what's the preferred language of the user?
     $language = $request->getPreferredLanguage(array('en', 'fr'));
     // get the value of a $_GET parameter
     $pageName = $request->query->get('page');
     // get the value of a $_POST parameter
     $pageName = $request->request->get('page');
     // store a message for the very next request
     $this->addFlash('notice', 'Congratulations, your action succeeded!');
     return $this->render('default/index.html.twig');
 }
 /**
  * action for / to redirect to the best language based on the request language order
  */
 public function defaultLanguageAction(Request $request)
 {
     $defaultPreferredLangs = $this->chooser->getPreferredLanguages($request->getLocale());
     $bestLang = $request->getPreferredLanguage($defaultPreferredLangs);
     // we only care about the first 2 characters, even if the user's preference is de_CH.
     $bestLang = substr($bestLang, 0, 2);
     /* Note: I wanted to send a 300 "Multiple Choices" header along with a
      * Location header, but user agents may behave inconsistently in
      * repsonse to this.
      *
      * For example Chrome was not redirecting unless the headers were
      * carefully tailored for it. (In particular, it doesn't like the
      * lowercase 'location' header that results from calling
      * $response->headers->set('Location', '...')
      */
     $url = $this->router->generate($this->routename, array('_locale' => $bestLang, '/'), true);
     $response = new RedirectResponse($url, 301);
     $response->setVary('accept-language');
     return $response;
 }
 /**
  * Redirects from base path to localized one depending on client preferred language
  * @Route("/")
  */
 public function indexLangRedirectAction(Request $request)
 {
     $lang = $request->getPreferredLanguage($this->supportedLanguages);
     return $this->redirect($this->generateUrl('homepage', ['_locale' => $lang]));
 }
 /**
  * Gets the preferred site based on the given request
  *
  * @param array   $sites   An array of enabled sites
  * @param Request $request A request instance
  *
  * @return SiteInterface|null
  */
 protected function getPreferredSite(array $sites, Request $request)
 {
     if (count($sites) === 0) {
         return null;
     }
     $sitesLocales = array_map(function (SiteInterface $site) {
         return $site->getLocale();
     }, $sites);
     $language = $request->getPreferredLanguage($sitesLocales);
     $host = $request->getHost();
     foreach ($sites as $site) {
         if (in_array($site->getHost(), array('localhost', $host)) && $language === $site->getLocale()) {
             return $site;
         }
     }
     return reset($sites);
 }
 /**
  * Searches a valid locale in HTTP headers.
  *
  * @param Request $request the request to search in
  *
  * @return string found locale
  */
 protected function searchInHeaders(Request $request)
 {
     if (empty($this->locales)) {
         return $request->getPreferredLanguage();
     }
     return $request->getPreferredLanguage($this->locales);
 }
 /**
  * @param Request $request
  */
 public function negotiate(Request $request)
 {
     return $request->getPreferredLanguage();
 }
 /**
  * The Request Object
  *
  * @Route("/lesson5/request", name="request_object")
  *
  * @param Request $request
  * @return Response
  */
 public function requestObjectAction(Request $request)
 {
     $request->isXmlHttpRequest();
     // is it an Ajax request?
     $request->getPreferredLanguage(array('en', 'fr'));
     $request->query->get('page');
     // get a $_GET parameter
     $request->request->get('page');
     // get a $_POST parameter
     return new Response('Hello world!');
 }
 public function detect(Request $request)
 {
     return $request->getPreferredLanguage();
 }
Example #15
0
 /**
  * This method returns the user locale and store it in session, if there is no user this method return default
  * language or the browser language if it is present in translations.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *
  * @return string The locale string as en, fr, es, etc.
  */
 public function getUserLocale(Request $request)
 {
     $locales = $this->getAvailableLocales();
     $preferred = explode('_', $request->getPreferredLanguage());
     if ($request->attributes->get('_locale')) {
         $locale = $request->attributes->get('_locale');
     } elseif (($user = $this->getCurrentUser()) && $user->getLocale()) {
         $locale = $user->getLocale();
     } elseif ($request->getSession() && ($sessionLocale = $request->getSession()->get('_locale'))) {
         $locale = $sessionLocale;
     } elseif (count($preferred) > 0 && isset($locales[$preferred[0]])) {
         $locale = $preferred[0];
     } else {
         $locale = $this->defaultLocale;
     }
     if ($session = $request->getSession()) {
         $session->set('_locale', $locale);
     }
     return $locale;
 }
Example #16
0
 public function testGetPreferredLanguage()
 {
     $request = new Request();
     $this->assertNull($request->getPreferredLanguage());
     $this->assertNull($request->getPreferredLanguage(array()));
     $this->assertEquals('fr', $request->getPreferredLanguage(array('fr')));
     $this->assertEquals('fr', $request->getPreferredLanguage(array('fr', 'en')));
     $this->assertEquals('en', $request->getPreferredLanguage(array('en', 'fr')));
     $this->assertEquals('fr-ch', $request->getPreferredLanguage(array('fr-ch', 'fr-fr')));
     $request = new Request();
     $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6');
     $this->assertEquals('en', $request->getPreferredLanguage(array('en', 'en-us')));
     $request = new Request();
     $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6');
     $this->assertEquals('en', $request->getPreferredLanguage(array('fr', 'en')));
     $request = new Request();
     $request->headers->set('Accept-language', 'zh, en-us; q=0.8');
     $this->assertEquals('en', $request->getPreferredLanguage(array('fr', 'en')));
     $request = new Request();
     $request->headers->set('Accept-language', 'zh, en-us; q=0.8, fr-fr; q=0.6, fr; q=0.5');
     $this->assertEquals('en', $request->getPreferredLanguage(array('fr', 'en')));
 }
 private function mapRequest(Request $request, $full = false)
 {
     $mapRequest = array();
     if ($full) {
         $mapRequest['ip'] = $request->getClientIp();
         $mapRequest['method'] = $request->getMethod();
         $mapRequest['host'] = $request->getHttpHost();
         $mapRequest['port'] = $request->getPort();
         $mapRequest['scheme'] = $request->getScheme();
         $mapRequest['uri'] = $request->getUri();
         $mapRequest['requestUri'] = $request->getRequestUri();
         $mapRequest['queryString'] = $request->getQueryString();
         $mapRequest['isSecure'] = $request->isSecure();
         $mapRequest['content'] = $request->getContent();
         $mapRequest['preferredLanguage'] = $request->getPreferredLanguage();
         $mapRequest['languages'] = $request->getLanguages();
         $mapRequest['charsets'] = $request->getCharsets();
         $mapRequest['acceptableContentTypes'] = $request->getAcceptableContentTypes();
         $mapRequest['isXmlHttpRequest'] = $request->isXmlHttpRequest();
         $mapRequest['to_string'] = $request->__toString();
         $mapRequest['server'] = $request->server;
         $mapRequest['headers'] = $request->headers;
         $mapRequest['cookies'] = $request->cookies;
         $mapRequest['oriLocale'] = $request->getLocale();
         $mapRequest['guessedLocale'] = $this->getLocaleManager()->getGuessedLocale();
     }
     $mapRequest['locale'] = $request->getLocale();
     $mapRequest['_route'] = $request->get('_route');
     $mapRequest['_controller'] = $request->get('_controller');
     $mapRequest['_route_params'] = $request->get('_route_params');
     return $mapRequest;
 }