hyperf-chat/app/Cache/UnreadTalkCache.php

84 lines
1.8 KiB
PHP
Raw Normal View History

2021-05-20 22:23:48 +08:00
<?php
namespace App\Cache;
use App\Cache\Repository\HashRedis;
2021-07-29 23:30:42 +08:00
use App\Traits\StaticInstance;
2021-05-20 22:23:48 +08:00
/**
* 私信消息未读数 - 缓存助手
*
* @package App\Cache
*/
2021-07-21 23:31:41 +08:00
class UnreadTalkCache extends HashRedis
2021-05-20 22:23:48 +08:00
{
2021-07-29 23:30:42 +08:00
use StaticInstance;
2021-05-20 22:23:48 +08:00
public $name = 'unread-talk';
/**
* 消息未读数自增
*
* @param int $sender 发送者ID
* @param int $receive 接收者ID
*/
public function increment(int $sender, int $receive)
{
$this->incr($this->flag($sender, $receive), 1);
}
/**
* 读取消息未读数
*
* @param int $sender 发送者ID
* @param int $receive 接收者ID
* @return int
*/
2021-05-22 20:54:30 +08:00
public function read(int $sender, int $receive): int
2021-05-20 22:23:48 +08:00
{
return (int)$this->get($this->flag($sender, $receive));
}
/**
* 消息未读数清空
*
* @param int $sender 发送者ID
* @param int $receive 接收者ID
*/
public function reset(int $sender, int $receive)
{
2021-05-21 22:56:42 +08:00
$this->rem($this->flag($sender, $receive));
2021-05-20 22:23:48 +08:00
}
/**
* 获取 Hash 成员 key
*
2021-08-20 22:38:46 +08:00
* @param int $sender
* @param int $receive
2021-05-20 22:23:48 +08:00
* @return string
*/
2021-08-20 22:38:46 +08:00
public function flag(int $sender, int $receive): string
2021-05-20 22:23:48 +08:00
{
return sprintf("%s_%s", $sender, $receive);
}
/**
* 读取指定用户的未读消息列表
*
* @param int $user_id 用户ID
* @return array
*/
2021-05-22 20:54:30 +08:00
public function reads(int $user_id): array
2021-05-20 22:23:48 +08:00
{
$iterator = null;
$arr = [];
2021-05-21 22:56:42 +08:00
while ($elements = $this->redis()->hscan($this->getCacheKey(), $iterator, '*_' . $user_id, 20)) {
2021-05-20 22:23:48 +08:00
foreach ($elements as $key => $value) {
$arr[explode('_', $key)[0]] = $value;
}
}
return $arr;
}
}