1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace mindtwo\LaravelMultilingual\Http\Middleware; |
4
|
|
|
|
5
|
|
|
use Closure; |
6
|
|
|
use Illuminate\Http\Request; |
7
|
|
|
use mindtwo\LaravelMultilingual\Services\Locale; |
8
|
|
|
|
9
|
|
|
class Localization |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var Locale |
13
|
|
|
*/ |
14
|
|
|
protected $locale; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Handle an incoming request. |
18
|
|
|
* |
19
|
|
|
* @param Request $request |
20
|
|
|
* @param Closure $next |
21
|
|
|
* @param string|null $guard |
22
|
|
|
* |
23
|
|
|
* @throws \Illuminate\Container\EntryNotFoundException |
24
|
|
|
* |
25
|
|
|
* @return mixed |
26
|
|
|
*/ |
27
|
|
|
public function handle($request, Closure $next, $guard = null) |
|
|
|
|
28
|
|
|
{ |
29
|
|
|
$this->locale = app(config('laravel-multilingual.locale_class')); |
|
|
|
|
30
|
|
|
|
31
|
|
|
// Detect and save locale |
32
|
|
|
$newLocale = $this->detectAndSetLocale($request); |
33
|
|
|
|
34
|
|
|
// Create locale cookie |
35
|
|
|
$localeCookie = cookie()->forever('locale', $newLocale); |
36
|
|
|
|
37
|
|
|
// Redirect with cookie |
38
|
|
|
foreach (config('laravel-multilingual.locale_redirectors') as $redirector) { |
39
|
|
|
$redirector = app($redirector); |
40
|
|
|
if ($redirector->match($request, $newLocale, $this->locale->current)) { |
|
|
|
|
41
|
|
|
dd('test'); |
42
|
|
|
|
43
|
|
|
return $redirector->redirect($newLocale)->withCookie($localeCookie); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
// Proceed with cookie |
48
|
|
|
return $next($request)->withCookie($localeCookie); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param $request |
53
|
|
|
* |
54
|
|
|
* @throws \Illuminate\Container\EntryNotFoundException |
55
|
|
|
* |
56
|
|
|
* @return string locale |
57
|
|
|
*/ |
58
|
|
|
public function detectAndSetLocale($request): string |
59
|
|
|
{ |
60
|
|
|
$locale = $this->getRequestedLocale($request); |
61
|
|
|
|
62
|
|
|
app()->setLocale($locale); |
|
|
|
|
63
|
|
|
|
64
|
|
|
return $locale; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @param Request $request |
69
|
|
|
* |
70
|
|
|
* @throws \Illuminate\Container\EntryNotFoundException |
71
|
|
|
* |
72
|
|
|
* @return string |
73
|
|
|
*/ |
74
|
|
|
protected function getRequestedLocale(Request $request): string |
75
|
|
|
{ |
76
|
|
|
foreach (config('laravel-multilingual.locale_detectors') as $detector) { |
77
|
|
|
$detector = app($detector); |
78
|
|
|
if ($detector->match($request, $this->locale)) { |
79
|
|
|
return $detector->get($request, $this->locale); |
|
|
|
|
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
return $this->locale->default; |
|
|
|
|
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.