|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace yiicod\base\traits; |
|
4
|
|
|
|
|
5
|
|
|
use Yii; |
|
6
|
|
|
use yii\helpers\ArrayHelper; |
|
7
|
|
|
use yii\mongodb\Collection; |
|
8
|
|
|
use yii\mongodb\Query; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Class StateStorageTrait |
|
12
|
|
|
* Trait to work with file state storage as GlobalState in Yii 1 |
|
13
|
|
|
* |
|
14
|
|
|
* Just attach this trait to file and override getStorageFileName() static trait method |
|
15
|
|
|
* to provide new storage file name. str_replace('\\', '', self::class).'.bin' will be used by default. |
|
16
|
|
|
* Or override getStorageFilePath() method to change file folder destination. |
|
17
|
|
|
* |
|
18
|
|
|
* @author Virchenko Maksim <[email protected]> |
|
19
|
|
|
* |
|
20
|
|
|
* @package yiicod\base\traits |
|
21
|
|
|
*/ |
|
22
|
|
|
trait StateStorageTrait |
|
23
|
|
|
{ |
|
24
|
|
|
/** |
|
25
|
|
|
* Get storage state value |
|
26
|
|
|
* |
|
27
|
|
|
* @param string $key |
|
28
|
|
|
* @param $default |
|
29
|
|
|
* |
|
30
|
|
|
* @return mixed |
|
31
|
|
|
*/ |
|
32
|
|
|
public static function getStorageState(string $key, $default = null) |
|
33
|
|
|
{ |
|
34
|
|
|
$data = self::getStorageData(); |
|
35
|
|
|
|
|
36
|
|
|
return isset($data[$key]) ? $data[$key] : $default; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* Set storage state value |
|
41
|
|
|
* |
|
42
|
|
|
* @param string $key |
|
43
|
|
|
* @param $value |
|
44
|
|
|
*/ |
|
45
|
|
|
public static function setStorageState(string $key, $value) |
|
46
|
|
|
{ |
|
47
|
|
|
self::setStorageData([$key => $value]); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* Get storage data |
|
52
|
|
|
* |
|
53
|
|
|
* @return array|string |
|
54
|
|
|
*/ |
|
55
|
|
|
public static function getStorageData() |
|
56
|
|
|
{ |
|
57
|
|
|
$query = new Query(); |
|
58
|
|
|
$row = $query |
|
59
|
|
|
->from('yii_state') |
|
60
|
|
|
->where(['name' => self::getStorageKey()]) |
|
61
|
|
|
->one(); |
|
62
|
|
|
|
|
63
|
|
|
return $row['data'] ?? []; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* Add data to storage |
|
68
|
|
|
* |
|
69
|
|
|
* @param array $newData |
|
70
|
|
|
*/ |
|
71
|
|
|
public static function setStorageData(array $newData) |
|
72
|
|
|
{ |
|
73
|
|
|
$data = ArrayHelper::merge(self::getStorageData(), $newData); |
|
74
|
|
|
/** @var Collection $collection */ |
|
75
|
|
|
$collection = Yii::$app->mongodb->getCollection('yii_state'); |
|
76
|
|
|
$collection->update(['name' => self::getStorageKey()], ['name' => self::getStorageKey(), 'data' => $data], [ |
|
77
|
|
|
'upsert' => true, |
|
78
|
|
|
]); |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
|
|
/** |
|
82
|
|
|
* Method which has to be implemented by classes |
|
83
|
|
|
* Return path of storage folder to save data in |
|
84
|
|
|
* |
|
85
|
|
|
* @return string |
|
86
|
|
|
*/ |
|
87
|
|
|
abstract protected static function getStorageKey(): string; |
|
88
|
|
|
} |
|
89
|
|
|
|