-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLocaleMiddleware.php
More file actions
88 lines (73 loc) · 2.43 KB
/
LocaleMiddleware.php
File metadata and controls
88 lines (73 loc) · 2.43 KB
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
78
79
80
81
82
83
84
85
86
87
88
<?php
namespace App\Middleware;
use Slim\Http\Request;
use Slim\Http\Response;
use Psr\Http\Message\UriInterface;
use Illuminate\Contracts\Translation\Translator;
class LocaleMiddleware
{
/**
* Translator
*/
private $translator;
/**
* @var string []
*/
private $allowedLocales;
/**
* @var string
*/
private $defaultLocale;
/**
* @param Translator $translator
* @param string[] $allowedLocales list of allowed locales that can be set
* @param string $defaultLocale the default locale if a current locale is not set
*/
public function __construct(Translator $translator, array $allowedLocales, string $defaultLocale)
{
$this->translator = $translator;
$this->allowedLocales = $allowedLocales;
$this->defaultLocale = $defaultLocale;
}
/**
* Retrieves the current locale from (in the given order):
*
* - the current URL path
* - the locale stored in the session
* - the default locale
*
* The translator is set to the current locale and the locale is passed
* as a request attribute.
*/
public function __invoke(Request $request, Response $response, $next)
{
$locale = $this->getLocaleFromUri($request->getUri());
if ($locale === null) {
// retrieve locale from session if not found in path, otherwise use default locale
$locale = array_key_exists('locale', $_SESSION) ? $_SESSION['locale'] : $this->defaultLocale;
}
$_SESSION['locale'] = $locale;
$this->translator->setLocale($locale);
$this->translator->setFallback($locale);
return $next($request->withAttribute('locale', $locale), $response);
}
/**
* Tries to retrieve the locale from the URI.
*
* The locale is assumed to be the first part in the path, e.g. "/en/home" yields "en" as result.
*
* @param UriInterface $uri
* @return string|null the locale if found in the url and one of the allowed locales, othwerwise null
*/
private function getLocaleFromUri(UriInterface $uri)
{
$escapedLocales = array_map(function ($locale) {
return preg_quote($locale);
}, $this->allowedLocales);
$pattern = sprintf('#^/?(%s)/#', implode('|', $escapedLocales));
if (preg_match($pattern, $uri->getPath(), $matches)) {
return $matches[1];
}
return null;
}
}