1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sludio\HelperBundle\Translatable\Router; |
4
|
|
|
|
5
|
|
|
use JMS\I18nRoutingBundle\Router\LocaleResolverInterface; |
6
|
|
|
use Symfony\Component\HttpFoundation\Request; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Default Locale Resolver. |
10
|
|
|
* |
11
|
|
|
* These checks are performed by this method: |
12
|
|
|
* |
13
|
|
|
* 1. Check if the host is associated with a specific locale |
14
|
|
|
* 2. Check for a query parameter named "hl" |
15
|
|
|
* 3. Check for a locale in the session |
16
|
|
|
* 4. Check for a cookie named "hl" |
17
|
|
|
* 5. Check the Accept header for supported languages |
18
|
|
|
* |
19
|
|
|
* @author Johannes M. Schmitt <[email protected]> |
20
|
|
|
*/ |
21
|
|
|
class DefaultLocaleResolver implements LocaleResolverInterface |
22
|
|
|
{ |
23
|
|
|
private $cookieName; |
24
|
|
|
private $hostMap; |
25
|
|
|
|
26
|
|
|
public function __construct($cookieName, array $hostMap = []) |
27
|
|
|
{ |
28
|
|
|
$this->cookieName = $cookieName; |
29
|
|
|
$this->hostMap = $hostMap; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* {@inheritdoc} |
34
|
|
|
*/ |
35
|
|
|
public function resolveLocale(Request $request, array $availableLocales) |
36
|
|
|
{ |
37
|
|
|
if (!empty($this->hostMap) && isset($this->hostMap[$host = $request->getHost()])) { |
38
|
|
|
return $this->hostMap[$host]; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
// if a locale has been specifically set as a query parameter, use it |
42
|
|
|
if ($request->query->has('hl')) { |
43
|
|
|
$hostLanguage = $request->query->get('hl'); |
44
|
|
|
|
45
|
|
|
if (preg_match('#^[a-z]{2}(?:_[a-z]{2})?$#i', $hostLanguage)) { |
46
|
|
|
return $hostLanguage; |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
// check if a session exists, and if it contains a locale |
51
|
|
|
if ($request->hasPreviousSession()) { |
52
|
|
|
$session = $request->getSession(); |
53
|
|
|
if ($session->has('_locale')) { |
54
|
|
|
return $session->get('_locale'); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
// if user sends a cookie, use it |
59
|
|
|
if ($request->cookies->has($this->cookieName)) { |
60
|
|
|
$hostLanguage = $request->cookies->get($this->cookieName); |
61
|
|
|
|
62
|
|
|
if (preg_match('#^[a-z]{2}(?:_[a-z]{2})?$#i', $hostLanguage)) { |
63
|
|
|
return $hostLanguage; |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$languages = []; |
68
|
|
|
foreach ($request->getLanguages() as $language) { |
69
|
|
|
if (strlen($language) != 2) { |
70
|
|
|
$newLang = explode('_', $language, 2); |
71
|
|
|
$languages[] = reset($newLang); |
72
|
|
|
} else { |
73
|
|
|
$languages[] = $language; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
$languages = array_unique($languages); |
77
|
|
|
if (!empty($languages)) { |
78
|
|
|
foreach ($languages as $lang) { |
79
|
|
|
if (in_array($lang, $availableLocales, true)) { |
80
|
|
|
return $lang; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
return null; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|