1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Containers\Localization\Middlewares; |
4
|
|
|
|
5
|
|
|
use Closure; |
6
|
|
|
use Illuminate\Foundation\Application; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class Localization |
10
|
|
|
* |
11
|
|
|
* @author Mahmoud Zalt <[email protected]> |
12
|
|
|
*/ |
13
|
|
|
class Localization |
14
|
|
|
{ |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Localization constructor. |
18
|
|
|
* |
19
|
|
|
* @param \Illuminate\Foundation\Application $app |
20
|
|
|
*/ |
21
|
|
|
public function __construct(Application $app) |
22
|
|
|
{ |
23
|
|
|
$this->app = $app; |
|
|
|
|
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Handle an incoming request. |
29
|
|
|
* |
30
|
|
|
* @param \Illuminate\Http\Request $request |
31
|
|
|
* @param \Closure $next |
32
|
|
|
* |
33
|
|
|
* @return mixed |
34
|
|
|
*/ |
35
|
|
|
public function handle($request, Closure $next) |
36
|
|
|
{ |
37
|
|
|
// find and validate the lang on that request |
38
|
|
|
$lang = $this->validateLanguage($this->findLanguage($request)); |
39
|
|
|
|
40
|
|
|
// set the local language |
41
|
|
|
$this->app->setLocale($lang); |
42
|
|
|
|
43
|
|
|
// get the response after the request is done |
44
|
|
|
$response = $next($request); |
45
|
|
|
|
46
|
|
|
// set Content Languages header in the response |
47
|
|
|
$response->headers->set('Content-Language', $lang); |
48
|
|
|
|
49
|
|
|
// return the response |
50
|
|
|
return $response; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @param $lang |
55
|
|
|
* |
56
|
|
|
* @return string|Exception |
57
|
|
|
*/ |
58
|
|
|
private function validateLanguage($lang) |
59
|
|
|
{ |
60
|
|
|
// check the languages defined is supported |
61
|
|
|
if (!array_key_exists($lang, $this->getSupportedLanguages())) { |
62
|
|
|
// respond with error |
63
|
|
|
$lang = abort(403, 'Language not supported.'); |
|
|
|
|
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return $lang; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @param $request |
71
|
|
|
* |
72
|
|
|
* @return string |
73
|
|
|
*/ |
74
|
|
|
private function findLanguage($request) |
75
|
|
|
{ |
76
|
|
|
// read the language from the request header, if the header is missed, take the default local language |
77
|
|
|
return $request->header('Content-Language') ? : $this->app->config->get('app.locale'); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @return array |
82
|
|
|
*/ |
83
|
|
|
private function getSupportedLanguages() |
84
|
|
|
{ |
85
|
|
|
return $this->app->config->get('localization.supported_languages'); |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
} |
89
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: