Completed
Push — master ( f66611...392013 )
by Alexey
03:23
created

LanguageDropdown   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 12
dl 0
loc 64
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A run() 0 6 2
A init() 0 8 1
A label() 0 9 3
B renderLanguageItems() 0 15 6
1
<?php
2
3
namespace app\widgets;
4
5
use Yii;
6
use yii\bootstrap\Dropdown;
7
8
/**
9
 * Class LanguageDropdown
10
 * @package app\widgets
11
 */
12
class LanguageDropdown extends Dropdown
13
{
14
    private static $_labels;
15
16
    private $_isError;
17
18
    /**
19
     * @inheritdoc
20
     */
21
    public function init()
22
    {
23
        $route = Yii::$app->controller->route;
24
        $params = $_GET;
25
        $this->_isError = $route === Yii::$app->errorHandler->errorAction;
26
        array_unshift($params, '/' . $route);
27
        $this->renderLanguageItems();
28
        parent::init();
29
    }
30
31
    /**
32
     * @return string
33
     */
34
    public function run()
35
    {
36
        if ($this->_isError) {
37
            return '';
38
        } else {
39
            return parent::run();
40
        }
41
    }
42
43
    /**
44
     * @param $code
45
     * @return mixed|null
46
     */
47
    public static function label($code)
48
    {
49
        if (self::$_labels === null) {
50
            self::$_labels = [
51
                'ru' => Yii::t('app', 'Русский'),
52
                'en' => Yii::t('app', 'English'),
53
            ];
54
        }
55
        return isset(self::$_labels[$code]) ? self::$_labels[$code] : null;
56
    }
57
58
    /**
59
     * Render items language select
60
     */
61
    public function renderLanguageItems()
62
    {
63
        $appLanguage = Yii::$app->language;
64
        foreach (Yii::$app->urlManager->languages as $language) {
65
            $isWildcard = substr($language, -2) === '-*';
66
            if ($language === $appLanguage || $isWildcard && substr($appLanguage, 0, 2) === substr($language, 0, 2)) {
67
                continue; // Exclude the current language
68
            }
69
            if ($isWildcard) {
70
                $language = substr($language, 0, 2);
71
            }
72
            $params['language'] = $language;
73
            $this->items[] = [
74
                'label' => self::label($language),
75
                'url' => $params,
76
            ];
77
        }
78
    }
79
}
80