-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathDefaultLocaleResolver.php
executable file
·77 lines (65 loc) · 2.27 KB
/
DefaultLocaleResolver.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
namespace JMS\I18nRoutingBundle\Router;
use Symfony\Component\HttpFoundation\Request;
/**
* Default Locale Resolver.
*
* These checks are performed by this method:
*
* 1. Check if the host is associated with a specific locale
* 2. Check for a query parameter named "hl"
* 3. Check for a locale in the session
* 4. Check for a cookie named "hl"
* 5. Check the Accept header for supported languages
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class DefaultLocaleResolver implements LocaleResolverInterface
{
private $cookieName;
private $hostMap;
public function __construct($cookieName, array $hostMap = array())
{
$this->cookieName = $cookieName;
$this->hostMap = $hostMap;
}
/**
* {@inheritDoc}
*/
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;
}
}
// use accept header for locale matching if sent
if ($languages = $request->getLanguages()) {
foreach ($languages as $lang) {
if (in_array($lang, $availableLocales, true)) {
return $lang;
}
}
}
return null;
}
}