vendor/jms/i18n-routing-bundle/JMS/I18nRoutingBundle/Router/DefaultLocaleResolver.php line 52

Open in your IDE?
  1. <?php
  2. namespace JMS\I18nRoutingBundle\Router;
  3. use Symfony\Component\HttpFoundation\Request;
  4. /**
  5.  * Default Locale Resolver.
  6.  *
  7.  * These checks are performed by this method:
  8.  *
  9.  *     1. Check if the host is associated with a specific locale
  10.  *     2. Check for a query parameter named "hl"
  11.  *     3. Check for a locale in the session
  12.  *     4. Check for a cookie named "hl"
  13.  *     5. Check the Accept header for supported languages
  14.  *
  15.  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  16.  */
  17. class DefaultLocaleResolver implements LocaleResolverInterface
  18. {
  19.     private $cookieName;
  20.     private $hostMap;
  21.     public function __construct($cookieName, array $hostMap = array())
  22.     {
  23.         $this->cookieName $cookieName;
  24.         $this->hostMap $hostMap;
  25.     }
  26.     /**
  27.      * {@inheritDoc}
  28.      */
  29.     public function resolveLocale(Request $request, array $availableLocales)
  30.     {
  31.         if ($this->hostMap && isset($this->hostMap[$host $request->getHost()])) {
  32.             return $this->hostMap[$host];
  33.         }
  34.         // if a locale has been specifically set as a query parameter, use it
  35.         if ($request->query->has('hl')) {
  36.             $hostLanguage $request->query->get('hl');
  37.             if (preg_match('#^[a-z]{2}(?:_[a-z]{2})?$#i'$hostLanguage)) {
  38.                 return $hostLanguage;
  39.             }
  40.         }
  41.         // check if a session exists, and if it contains a locale
  42.         if ($request->hasPreviousSession()) {
  43.             $session $request->getSession();
  44.             if ($session->has('_locale')) {
  45.                 return $session->get('_locale');
  46.             }
  47.         }
  48.         // if user sends a cookie, use it
  49.         if ($request->cookies->has($this->cookieName)) {
  50.             $hostLanguage $request->cookies->get($this->cookieName);
  51.             if (preg_match('#^[a-z]{2}(?:_[a-z]{2})?$#i'$hostLanguage)) {
  52.                 return $hostLanguage;
  53.             }
  54.         }
  55.         // use accept header for locale matching if sent
  56.         if ($languages $request->getLanguages()) {
  57.             foreach ($languages as $lang) {
  58.                 if (in_array($lang$availableLocalestrue)) {
  59.                     return $lang;
  60.                 }
  61.             }
  62.         }
  63.         return null;
  64.     }
  65. }