forked from s-lyn/yii2-multilanguage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Start.php
103 lines (85 loc) · 2.81 KB
/
Start.php
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
namespace pjhl\multilanguage;
use Yii;
use pjhl\multilanguage\components\helpers\Detect;
class Start {
public static function run($event = null) {
$langExpected = static::detectExpectLang();
if ($langExpected !== null) {
// Make redirect to correct language url
static::makeRedirectTo($langExpected);
}
}
/**
* Returns expected link language
* @return array|null Null - no lang expecte
*/
public static function detectExpectLang() {
$langExpected = null;
$lang = null;
// Save the language in a config of the yii2
$lang_id = Detect::run();
if ($lang_id !== null) {
$lang = LangHelper::getLanguageByParam('id', $lang_id);
if ($lang !== null) {
Yii::$app->language = $lang['locale'];
}
}
// Detect current link language
$current = static::detectLinkLang();
if ($current && $lang) {
if ($lang['id'] != $current['id']) {
$langExpected = $lang;
}
}
return $langExpected;
}
/**
* Returns current link language
* @return array|null
*/
public static function detectLinkLang() {
$languageInurl = Yii::$app->request->languageInurl;
if ($languageInurl) {
$current = LangHelper::getLanguageByParam('url', $languageInurl);
} else {
$current = LangHelper::getLanguageByParam('default', true);
}
return $current;
}
/**
* Creates link for language redirect
* @param string|false $link
*/
public static function redirectLink($lang) {
$link = null;
if (!$lang) {
return $link;
}
// Do not make redirect on test env
$isTestEnv = defined('YII_ENV') && YII_ENV === 'test';
$isTestEnv2 = defined('YII_ENV_TEST') && YII_ENV_TEST;
if ($isTestEnv || $isTestEnv2) {
return;
}
if (Yii::$app->getRequest()->getMethod() === 'GET' && !Yii::$app->getRequest()->isAjax) {
$isDefault = isset($lang['default']) && $lang['default'];
$link = \yii\helpers\Url::current([
'x-language-url' => $isDefault ? false : $lang['url']
]);
}
return $link;
}
/**
* Make redirect to correct language url.
* Ajax and not GET requests will be ignored
* @param array $lang
*/
private static function makeRedirectTo($lang) {
$link = static::redirectLink($lang);
if ($link !== null) {
Yii::$app->getResponse()->redirect($link)->send();
Yii::$app->end();
}
}
}