Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
MessageService.php
1<?php
2
4
6use Bitrix\Im\V2\Common\ContextCustomer;
11
13{
14 use ContextCustomer;
15
16 private Message $message;
17
18 public function __construct(Message $message)
19 {
20 $this->message = $message;
21 }
22
23 public function getMessageContext(int $range, array $select = []): Result
24 {
25 $result = new Result();
26
27 $messageId = $this->message->getMessageId() ?? 0;
28 $chat = $this->message->getChat();
29
30 $startId = $chat->getStartId();
31
32 $idsBefore = [];
33 $idsAfter = [];
34 if ($range > 0)
35 {
36 $idsBefore = MessageTable::query()
37 ->setSelect(['ID'])
38 ->where('ID', '<', $messageId)
39 ->where('ID', '>=', $startId)
40 ->where('CHAT_ID', $chat->getChatId())
41 ->setOrder(['DATE_CREATE' => 'DESC', 'ID' => 'DESC'])
42 ->setLimit($range)
43 ->fetchCollection()
44 ->getIdList()
45 ;
46 $idsAfter = MessageTable::query()
47 ->setSelect(['ID'])
48 ->where('ID', '>', $messageId)
49 ->where('CHAT_ID', $chat->getChatId())
50 ->setOrder(['DATE_CREATE' => 'ASC', 'ID' => 'ASC'])
51 ->setLimit($range)
52 ->fetchCollection()
53 ->getIdList()
54 ;
55 }
56 $targetMessage = $messageId < $startId ? [] : [$messageId];
57
58 $ids = array_merge($idsBefore, $targetMessage, $idsAfter);
59
60 if (empty($ids))
61 {
62 return $result->setResult(new MessageCollection());
63 }
64
65 if (empty($select))
66 {
67 return $result->setResult(new MessageCollection($ids));
68 }
69
70 $ormCollection = MessageTable::query()->whereIn('ID', $ids)->setSelect($select)->fetchCollection();
71
72 return $result->setResult(new MessageCollection($ormCollection));
73 }
74
75 public static function deleteByChatId(int $chatId, int $userId): Result
76 {
77 MessageTable::deleteBatch(['=CHAT_ID' => $chatId]);
78 $readService = new ReadService($userId);
79 $readService->deleteByChatId($chatId);
80
81 return new Result();
82 }
83
84 public function fillContextPaginationData(array $rest, MessageCollection $messages, int $range): array
85 {
86 $rest['hasPrevPage'] = $this->getCountHigherMessages($messages, $this->message->getId() ?? 0) >= $range;
87 $lastSelectedId = $this->getLastSelectedId($messages);
88 $lastMessageIdInChat = $this->message->getChat()->getLastMessageId();
89 $rest['hasNextPage'] = $lastSelectedId > 0 && $lastMessageIdInChat > 0 && $lastSelectedId < $lastMessageIdInChat;
90
91 return $rest;
92 }
93
94 private function getCountHigherMessages(MessageCollection $messages, int $id): int
95 {
96 $count = 0;
97
98 foreach ($messages as $message)
99 {
100 if ($message->getId() < $id)
101 {
102 ++$count;
103 }
104 }
105
106 return $count;
107 }
108
109 private function getLastSelectedId(MessageCollection $messages): int
110 {
111 return max($messages->getIds() ?: [0]);
112 }
113}
getMessageContext(int $range, array $select=[])
static deleteByChatId(int $chatId, int $userId)
fillContextPaginationData(array $rest, MessageCollection $messages, int $range)