1
|
|
|
<?php |
2
|
|
|
namespace jones\wschat\collections; |
3
|
|
|
|
4
|
|
|
use Yii; |
5
|
|
|
use yii\mongodb\Exception; |
6
|
|
|
use yii\mongodb\Query; |
7
|
|
|
use jones\wschat\components\AbstractStorage; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Class History |
11
|
|
|
* @package jones\wschat\collections |
12
|
|
|
* @property \MongoId $_id |
13
|
|
|
* @property string $chat_id |
14
|
|
|
* @property string $chat_title |
15
|
|
|
* @property string $user_id |
16
|
|
|
* @property string $username |
17
|
|
|
* @property string $avatar_16 |
18
|
|
|
* @property string $avatar_32 |
19
|
|
|
* @property integer $timestamp |
20
|
|
|
* @property string $message |
21
|
|
|
*/ |
22
|
|
|
class History extends AbstractStorage |
23
|
|
|
{ |
24
|
|
|
/** |
25
|
|
|
* Get name of mongo collection |
26
|
|
|
* |
27
|
|
|
* @access public |
28
|
|
|
* @static |
29
|
|
|
* @return string |
30
|
|
|
*/ |
31
|
|
|
public static function collectionName() |
32
|
|
|
{ |
33
|
|
|
return 'history'; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Get list of attributes |
38
|
|
|
* |
39
|
|
|
* @access public |
40
|
|
|
* @return array |
41
|
|
|
*/ |
42
|
|
View Code Duplication |
public function attributes() |
43
|
|
|
{ |
44
|
|
|
return [ |
45
|
|
|
'_id', 'chat_id', 'chat_title', 'user_id', 'username', 'avatar_16', |
46
|
|
|
'avatar_32', 'timestamp', 'message' |
47
|
|
|
]; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @inheritdoc |
52
|
|
|
*/ |
53
|
|
View Code Duplication |
public function getHistory($chatId, $limit = 10) |
54
|
|
|
{ |
55
|
|
|
$query = new Query(); |
56
|
|
|
$query->select(['user_id', 'username', 'message', 'timestamp', 'avatar_16', 'avatar_32']) |
57
|
|
|
->from(self::collectionName()) |
58
|
|
|
->where(['chat_id' => $chatId]); |
59
|
|
|
$query->orderBy(['timestamp' => SORT_DESC]); |
60
|
|
|
if ($limit) { |
61
|
|
|
$query->limit($limit); |
62
|
|
|
} |
63
|
|
|
return $query->all(); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @inheritdoc |
68
|
|
|
*/ |
69
|
|
|
public function storeMessage(array $params) |
70
|
|
|
{ |
71
|
|
|
try { |
72
|
|
|
/** @var \yii\mongodb\Collection $collection */ |
73
|
|
|
$collection = Yii::$app->mongodb->getCollection(self::collectionName()); |
74
|
|
|
$collection->insert($params); |
75
|
|
|
} catch (Exception $e) { |
76
|
|
|
Yii::error($e->getMessage()); |
77
|
|
|
return false; |
78
|
|
|
} |
79
|
|
|
return true; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
|