/** * 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; }
/** * {@inheritDoc} */ public function getLocalesFor($document, $includeFallbacks = false) { if (!is_object($document)) { throw new InvalidArgumentException('Parameter $document needs to be an object, ' . gettype($document) . ' given'); } $this->errorIfClosed(); $metadata = $this->getClassMetadata(get_class($document)); $locales = $this->unitOfWork->getLocalesFor($document); if ($includeFallbacks) { $fallBackLocales = array(); foreach ($locales as $locale) { $fallBackLocales = array_merge($fallBackLocales, $this->localeChooserStrategy->getFallbackLocales($document, $metadata, $locale)); } $locales = array_unique(array_merge($locales, $fallBackLocales)); } return $locales; }