Completed
Push — master ( a309eb...aad9ff )
by Alexey
02:48
created

LanguageDropdown::isCheck()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 3
eloc 2
nc 3
nop 3
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
        $urlManager = Yii::$app->urlManager;
65
        foreach ($urlManager->languages as $language) {
66
            $isWildcard = substr($language, -2) === '-*';
67
68
            if ($this->isCheck($language, $appLanguage, $isWildcard)) {
69
                continue;
70
            }
71
72
            if ($isWildcard) {
73
                $language = substr($language, 0, 2);
74
            }
75
76
            $params['language'] = $language;
77
            $this->items[] = [
78
                'label' => self::label($language),
79
                'url' => $params,
80
            ];
81
        }
82
    }
83
84
    /**
85
     * @param string $language
86
     * @param string $appLanguage
87
     * @param string $isWildcard
88
     * @return bool
89
     */
90
    protected function isCheck($language, $appLanguage, $isWildcard)
91
    {
92
        return ($language === $appLanguage ||
93
            $isWildcard && substr($appLanguage, 0, 2) === substr($language, 0, 2));
94
    }
95
}
96