<?php
namespace Aqarmap\Bundle\MainBundle\Locale;
use JMS\I18nRoutingBundle\Router\LocaleResolverInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Default Locale Resolver.
*/
class DefaultLocaleResolver implements LocaleResolverInterface
{
private $cookieName;
private $hostMap;
public function __construct($cookieName, $acceptHeaderLanguages = true, array $hostMap = [])
{
$this->cookieName = $cookieName;
$this->hostMap = $hostMap;
}
public function resolveLocale(Request $request, array $availableLocales)
{
if ($this->hostMap && isset($this->hostMap[$host = $request->getHost()])) {
return $this->hostMap[$host];
}
// if a locale has been specifically set as a query parameter, use it
if ($request->query->has('hl')) {
$hostLanguage = $request->query->get('hl');
if (preg_match('#^[a-z]{2}(?:_[a-z]{2})?$#i', $hostLanguage)) {
return $hostLanguage;
}
}
// check if a session exists, and if it contains a locale
if ($request->hasPreviousSession()) {
$session = $request->getSession();
if ($session->has('_locale')) {
return $session->get('_locale');
}
}
// if user sends a cookie, use it
if ($request->cookies->has($this->cookieName)) {
$hostLanguage = $request->cookies->get($this->cookieName);
if (preg_match('#^[a-z]{2}(?:_[a-z]{2})?$#i', $hostLanguage)) {
return $hostLanguage;
}
}
}
}