Languages.php
3.12 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
<?php
namespace thread\app\model;
use Yii;
use yii\base\{
ErrorException, Component, BootstrapInterface
};
use thread\app\model\interfaces\{
LanguageModel as iLanguageModel,
Languages as iLanguages
};
/**
* class Languages
*
* @package thread\app\model
* @author FilamentV <vortex.filament@gmail.com>
* @copyright (c) 2015, Thread
*/
class Languages extends Component implements iLanguages, BootstrapInterface
{
/**
* @var null
*/
public $languageModel = null;
/**
* @var null
*/
protected $lang = null;
/**
* @var array
*/
protected $defaultLang = [
'by_default' => true,
'alias' => 'en',
'local' => 'en-EN',
'label' => 'EN',
];
/**
* @var array
*/
protected $items = [];
/**
* @throws ErrorException
*/
public function init()
{
$this->lang = new $this->languageModel;
if (!($this->lang instanceof iLanguageModel)) {
throw new ErrorException($this->languageModel . ' must be implemented ' . iLanguageModel::class);
}
$this->items = $this->getAll();
foreach ($this->items as $item) {
if ($item['by_default']) {
$this->defaultLang = $item->getAttributes();
break;
}
}
parent::init();
}
/**
* @param $app
*/
public function bootstrap($app)
{
$this->init();
$app->language = $this->defaultLang['local'];
}
/**
* @return mixed
*/
public function getAll(): array
{
return $this->lang->getLanguages();
}
/**
* @param string $lang
* @return boolean
*/
public function isExistsByAlias(string $lang)
{
$r = false;
foreach ($this->items as $item) {
if ($item['alias'] == $lang) {
$r = true;
break;
}
}
return $r;
}
/**
* @return array
*/
public function getDefault(): array
{
return $this->defaultLang;
}
/**
* @param string $lang
* @return mixed
*/
public function getLangByAlias(string $lang): array
{
$r = null;
foreach ($this->items as $item) {
if ($item['alias'] == $lang) {
$r = (!is_array($item)) ? $item->getAttributes() : $item;
break;
}
}
return $r;
}
/**
* @param string $lang
* @return mixed
*/
public function getLangByLocal(string $lang): array
{
$r = null;
foreach ($this->items as $item) {
if ($item['local'] == $lang) {
$r = (!is_array($item)) ? $item->getAttributes() : $item;
break;
}
}
return $r;
}
/**
* @return array|mixed
*/
public function getCurrent()
{
$curr_lang = [];
foreach ($this->items as $item) {
if ($item['local'] == Yii::$app->language) {
$curr_lang = $item;
break;
}
}
return $curr_lang;
}
}