-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSystemParamsService.php
281 lines (241 loc) · 8.06 KB
/
SystemParamsService.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
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
<?php
namespace yiicod\systemparams;
use RecursiveArrayIterator;
use RecursiveIteratorIterator;
use Yii;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
/**
* Class SystemParamService
* System params service to work with
*
* @author Virchenko Maksim <[email protected]>
*
* @package yiicod\systemparam
*/
class SystemParamsService
{
const ARRAY_KEYS_SEPARATOR = '.';
const PARAM_IS_NOT_SET = 'CONFIG_VALUE_IS_NOT_SET';
const CACHE_KEY = 'YII_SYSTEM_PARAM';
/**
* Cache duration
*
* @var int
*/
public $cacheDuration = 0;
/**
* Params array
*
* @var array
*/
private $params = [];
/**
* Get system param
*
* @param string $param
*
* @return mixed
*/
public function getParam(string $param)
{
if (empty($this->params)) {
$this->prepareParams();
}
return ArrayHelper::getValue($this->params, $param);
}
/**
* Prepare params
*
* @return bool
*/
protected function prepareParams()
{
$paramModel = Yii::$app->get('systemparams')->modelMap['systemParam']['class'];
//If table not exists
if (Yii::$app instanceof \yii\console\Application && null === Yii::$app->db->schema->getTableSchema($paramModel::tableName())) {
Yii::error('Table ' . $paramModel::tableName() . ' not exists');
return false;
}
if (0 === $this->cacheDuration || false === $this->loadParamsFromCache()) {
$this->loadParamsFromDb();
//Set params to cache
if (isset(Yii::$app->cache)) {
Yii::$app->cache->set(self::CACHE_KEY, Json::encode($this->params), $this->cacheDuration);
}
}
return true;
}
/**
* Load params from db.
*
* @return bool
*/
protected function loadParamsFromCache()
{
if ((isset(Yii::$app->cache) && $this->cacheDuration > 0 && false !== Yii::$app->cache->get(self::CACHE_KEY))) {
$this->params = Json::decode(Yii::$app->cache->get(self::CACHE_KEY));
return true;
}
return false;
}
/**
* Load params from db.
*
* @return bolean
*/
protected function loadParamsFromDb()
{
$paramModel = Yii::$app->get('systemparams')->modelMap['systemParam']['class'];
$records = $paramModel::find()->asArray()->all();
foreach ($records as $record) {
$this->params = ArrayHelper::merge($this->params, $this->generateArrayForParamValue(
$record[$paramModel::attributesMap()['fieldParamKey']],
$record[$paramModel::attributesMap()['fieldParamValue']]
));
}
return true;
}
/**
* Merge params
*
* @param $params
* @param bool $autoUpdate
*
* @return bool
*/
public function mergeParams(array $params, bool $autoUpdate = false)
{
$paramModel = Yii::$app->get('systemparams')->modelMap['systemParam']['class'];
$arrayOfKeys = $this->getArrayKeysRecursivelyInString($params);
$records = $paramModel::find()->all();
foreach ($records as $i => $model) {
$param = $model->{$paramModel::attributesMap()['fieldParamKey']};
if (self::PARAM_IS_NOT_SET !== $this->getParamValueByKey($param, $params)) {
$records[$param] = clone $model;
} else {
$model->delete();
}
unset($records[$i]);
}
foreach ($arrayOfKeys as $paramKey) {
/** @var ActiveRecord $model */
$model = new $paramModel();
if (isset($records[$paramKey])) {
$model->setIsNewRecord(false);
$model->setAttributes($records[$paramKey]->getAttributes(), false);
}
$model->{$paramModel::attributesMap()['fieldParamKey']} = $paramKey;
$value = $this->getParamValueByKey($paramKey, $params);
if (false === empty($value)) {
$model->{$paramModel::attributesMap()['fieldParamValue']} = is_bool($value['value']) ? intval($value['value']) : $value['value'];
$model->{$paramModel::attributesMap()['fieldValidator']} = isset($value['validator']) ? $value['validator'] : 'string';
$model->{$paramModel::attributesMap()['fieldDescription']} = isset($value['description']) ? $value['description'] : '';
} else {
$model->{$paramModel::attributesMap()['fieldParamValue']} = is_bool($value) ? intval($value) : $value;
$model->{$paramModel::attributesMap()['fieldValidator']} = 'string';
$model->{$paramModel::attributesMap()['fieldDescription']} = '';
}
if ($model->isNewRecord || (count(array_diff(
[
$model->{$paramModel::attributesMap()['fieldParamValue']},
$model->{$paramModel::attributesMap()['fieldValidator']},
$model->{$paramModel::attributesMap()['fieldDescription']},
],
[
$records[$paramKey]->{$paramModel::attributesMap()['fieldParamValue']},
$records[$paramKey]->{$paramModel::attributesMap()['fieldValidator']},
$records[$paramKey]->{$paramModel::attributesMap()['fieldDescription']},
]
)) && $autoUpdate)
) {
if (false == $model->save()) {
Yii::error($paramKey . ' ' . Json::encode($model->getErrors()), 'system.systemparam');
}
}
}
self::flushCache();
return true;
}
/**
* Flush system params cache
*/
public static function flushCache()
{
if (isset(Yii::$app->cache)) {
Yii::$app->cache->delete(self::CACHE_KEY);
}
}
/**
* Generate array of keys recursively in string.
*
* @param $dataArray
*
* @return array
*
* @author Virchenko Maksim <[email protected]>
*/
protected function getArrayKeysRecursivelyInString(array $dataArray): array
{
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($dataArray));
$keys = [];
foreach ($iterator as $key => $value) {
// Build long key name based on parent keys
$key = $iterator->getSubIterator(0)->key();
for ($i = 1; $i < $iterator->getDepth(); ++$i) {
$key = $key . self::ARRAY_KEYS_SEPARATOR . $iterator->getSubIterator($i)->key();
}
$keys[] = $key;
}
return array_unique($keys);
}
/**
* Return param value or false if param not exist.
*
* @param $pk
* @param $array
*
* @return bool
*
* @author Chaykovskiy Roman
*/
protected function getParamValueByKey($pk, $array)
{
$keys = explode(self::ARRAY_KEYS_SEPARATOR, $pk);
foreach ($keys as $key) {
$array = isset($array[$key]) ? $array[$key] : self::PARAM_IS_NOT_SET;
if (self::PARAM_IS_NOT_SET == $array) {
break;
}
}
return $array;
}
/**
* Generate multidimensional array for pk with value.
*
* @param $pk can be string like 'a|b...|n'
* @param $value
*
* @return array
*
* @author Chaykovskiy Roman
*/
protected function generateArrayForParamValue($pk, $value)
{
$keys = explode(self::ARRAY_KEYS_SEPARATOR, $pk);
$countOfKeys = count($keys);
$result = [];
$current = &$result;
foreach ($keys as $k => $keyValue) {
if ($countOfKeys == ($k + 1)) {
$current[$keyValue] = $value;
} else {
$current[$keyValue] = [];
// descend into the new array
$current = &$current[$keyValue];
}
}
return $result;
}
}