|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace PWWEB\Localisation\Middleware; |
|
4
|
|
|
|
|
5
|
|
|
use Closure; |
|
6
|
|
|
use Illuminate\Contracts\Session\Session; |
|
7
|
|
|
use Illuminate\Http\Request; |
|
8
|
|
|
use PWWEB\Localisation\Repositories\LanguageRepository; |
|
9
|
|
|
|
|
10
|
|
|
class Locale |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* Constant for the session key for locale. |
|
14
|
|
|
* |
|
15
|
|
|
* @const string |
|
16
|
|
|
*/ |
|
17
|
|
|
const SESSION_KEY = 'locale'; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Repository of languages to be used throughout the controller. |
|
21
|
|
|
* |
|
22
|
|
|
* @var \PWWEB\Localisation\Repositories\LanguageRepository |
|
23
|
|
|
*/ |
|
24
|
|
|
private $languageRepository; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Constructor for the middleware ensuring dependencies are injected. |
|
28
|
|
|
* |
|
29
|
|
|
* @param \PWWEB\Localisation\Repositories\LanguageRepository $languageRepo Repository of Languages |
|
30
|
|
|
*/ |
|
31
|
|
|
public function __construct(LanguageRepository $languageRepo) |
|
32
|
|
|
{ |
|
33
|
|
|
$this->languageRepository = $languageRepo; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Locale middleware handler. |
|
38
|
|
|
* |
|
39
|
|
|
* @param \Illuminate\Http\Request $request current request |
|
40
|
|
|
* @param Closure $next Next |
|
41
|
|
|
* |
|
42
|
|
|
* @return mixed |
|
43
|
|
|
*/ |
|
44
|
|
|
public function handle(Request $request, Closure $next) |
|
45
|
|
|
{ |
|
46
|
|
|
$session = $request->getSession(); |
|
47
|
|
|
if (null !== $session) { |
|
48
|
|
|
if (false === $session->has(self::SESSION_KEY)) { |
|
49
|
|
|
$session->put(self::SESSION_KEY, $request->getPreferredLanguage($this->languageRepository->getAllActive()->pluck('locale')->toArray())); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
if (true === $request->has('lang')) { |
|
53
|
|
|
$lang = $request->get('lang'); |
|
54
|
|
|
$check = $this->languageRepository->isLangActive($lang); |
|
|
|
|
|
|
55
|
|
|
|
|
56
|
|
|
if (false === is_null($check)) { |
|
57
|
|
|
$session->put(self::SESSION_KEY, $check->locale); |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
app()->setLocale($session->get(self::SESSION_KEY)); |
|
|
|
|
|
|
62
|
|
|
|
|
63
|
|
|
return $next($request); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
$lang = $request->server('HTTP_ACCEPT_LANGUAGE'); |
|
67
|
|
|
|
|
68
|
|
|
app()->setLocale($lang); |
|
69
|
|
|
|
|
70
|
|
|
return $next($request); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|