forked from codemix/yii2-localeurls
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LangSelector.php
96 lines (83 loc) · 2.75 KB
/
LangSelector.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
<?php
/**
* Created by PhpStorm.
* User: artem_000
* Date: 9/3/2015
* Time: 12:43 PM
*/
namespace integready\localeurls;
use Yii;
use yii\bootstrap\Dropdown;
/**
* Class LangSelector
* @package integready\localeurls
*/
class LangSelector extends Dropdown
{
private static $_labels;
private static $_currentLanguageLabel;
private $_isError;
public function init()
{
$route = Yii::$app->controller->route;
$appLanguage = Yii::$app->language;
$params = $_GET;
$this->_isError = $route === Yii::$app->errorHandler->errorAction;
array_unshift($params, '/' . $route);
foreach (Yii::$app->urlManager->languages as $language) {
$isWildcard = substr($language, -2) === '-*';
if ($language === $appLanguage ||
// Also check for wildcard language
$isWildcard && substr($appLanguage, 0, 2) === substr($language, 0, 2)
) {
self::$_currentLanguageLabel = $language;
continue; // Exclude the current language
}
if ($isWildcard) {
$language = substr($language, 0, 2);
}
$params['language'] = $language;
$this->items[] = [
'label' => self::label($language),
'url' => $params,
'options' => ['class' => [
$language,
]],
];
}
parent::init();
}
/**
* @param string $code
*
* @return string|null
*/
public static function label($code)
{
if (self::$_labels === null) {
self::$_labels = [
'ru-RU' => Yii::t(Yii::$app->urlManager->translateCategory, 'lang-russian'),
'en-US' => Yii::t(Yii::$app->urlManager->translateCategory, 'lang-english'),
'fr-FR' => Yii::t(Yii::$app->urlManager->translateCategory, 'lang-france'),
'zh-CN' => Yii::t(Yii::$app->urlManager->translateCategory, 'lang-chinese'),
];
}
return isset(self::$_labels[$code]) ? self::$_labels[$code] : null;
}
/**
* @inheritdoc
*/
public function run()
{
// Only show this widget if we're not on the error page
if ($this->_isError || count(Yii::$app->urlManager->languages) < 2) {
return '';
} else {
$html = '<li class="dropdown ' . self::$_currentLanguageLabel . '"><a href="#" data-toggle="dropdown" class="dropdown-toggle">' . PHP_EOL .
self::label(self::$_currentLanguageLabel) . '<b class="caret"></b></a>' . PHP_EOL;
$html .= parent::run();
$html .= '</li>';
return $html;
}
}
}