1 | <?php |
||
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 |