1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Shamaseen\Repository\Middlewares; |
4
|
|
|
|
5
|
|
|
use App; |
6
|
|
|
use Closure; |
7
|
|
|
use Illuminate\Http\Request; |
8
|
|
|
use Illuminate\Support\Facades\Cookie; |
9
|
|
|
|
10
|
|
|
class MultiLanguage |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Handle an incoming request. |
14
|
|
|
* |
15
|
|
|
* @return mixed |
16
|
|
|
*/ |
17
|
|
|
public function handle(Request $request, Closure $next) |
18
|
|
|
{ |
19
|
|
|
$preferred = Cookie::get('language'); |
20
|
|
|
|
21
|
|
|
if (!$preferred) { |
22
|
|
|
$configLocale = config('app.locale'); |
23
|
|
|
|
24
|
|
|
$browserLanguage = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && $_SERVER['HTTP_ACCEPT_LANGUAGE'] |
25
|
|
|
? $_SERVER['HTTP_ACCEPT_LANGUAGE'] |
26
|
|
|
: $configLocale; |
27
|
|
|
$preferred = $this->preferredLanguage(config('app.locales', [$configLocale]), $browserLanguage); |
28
|
|
|
|
29
|
|
|
Cookie::queue(Cookie::forever('language', $preferred)); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
App::setLocale($preferred); |
|
|
|
|
33
|
|
|
|
34
|
|
|
return $next($request); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Detect the preferred language form the user browser setting. |
39
|
|
|
* |
40
|
|
|
* @return int|string |
41
|
|
|
*/ |
42
|
|
|
public function preferredLanguage(array $available_languages, $http_accept_language) |
43
|
|
|
{ |
44
|
|
|
$available_languages = array_flip($available_languages); |
45
|
|
|
|
46
|
|
|
$langs = []; |
47
|
|
|
preg_match_all('~([\w-]+)(?:[^,\d]+([\d.]+))?~', strtolower($http_accept_language), $matches, PREG_SET_ORDER); |
48
|
|
|
foreach ($matches as $match) { |
49
|
|
|
list($a, $b) = explode('-', $match[1]) + ['', '']; |
50
|
|
|
|
51
|
|
|
$value = isset($match[2]) ? (float) $match[2] : 1.0; |
52
|
|
|
|
53
|
|
|
if (isset($available_languages[$match[1]])) { |
54
|
|
|
$langs[$match[1]] = max($value, $langs[$match[1]] ?? 0); |
55
|
|
|
continue; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
if (isset($available_languages[$a])) { |
59
|
|
|
$langs[$a] = max($value, $langs[$a] ?? 0); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
arsort($langs); |
63
|
|
|
|
64
|
|
|
return array_keys($langs)[0] ?? 'en'; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|