Files
hyperf_service/app/Cache/Redis/Admin/RoleCache.php
2025-01-21 16:20:16 +08:00

131 lines
3.4 KiB
PHP

<?php
namespace App\Cache\Redis\Admin;
use App\Cache\Redis\RedisCache;
use App\Constants\Admin\AuthCode;
use App\Constants\Common\RoleCode;
use App\Constants\RedisCode;
use App\Model\AdminMenu;
use App\Model\AdminRoleMenu;
use App\Service\ServiceTrait\Admin\AdminRoleMenuTrait;
use Hyperf\Di\Annotation\Inject;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
class RoleCache
{
use AdminRoleMenuTrait;
/**
* 注入 redis 方法
* @var RedisCache $redis
*/
#[Inject]
protected RedisCache $redis;
/**
* 注入模型
* @var AdminRoleMenu $adminRoleMenuModel
*/
#[Inject]
protected AdminRoleMenu $adminRoleMenuModel;
/**
* 注入模型
* @var AdminMenu $adminMenuModel
*/
#[Inject]
protected AdminMenu $adminMenuModel;
/**
* @var string
*/
private string $roleMenuArrKey;
/**
* @var string
*/
private string $roleMenuListKey;
/**
* @var int
*/
private int $roleId = 0;
/**
* 获取 key
* @return void
*/
private function getKey(): void
{
$this->roleMenuArrKey = AdminRedisKey::adminMenuArrByRoleId($this->roleId);
$this->roleMenuListKey = AdminRedisKey::adminMenuListByRoleId($this->roleId);
}
/**
* @param int $roleId
* @return array|array[]
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws \RedisException
*/
public function getRoleCache(int $roleId): array
{
$this->roleId = $roleId;
$this->getKey();
if ($this->redis->exists($this->roleMenuArrKey,RedisCode::SYSTEM_DB) && $this->redis->exists($this->roleMenuListKey,RedisCode::SYSTEM_DB)) {
return [
'role_arr' => $this->redis->sMembers($this->roleMenuArrKey,RedisCode::SYSTEM_DB),
'role_list' => json_decode($this->redis->get($this->roleMenuListKey,RedisCode::SYSTEM_DB),true),
];
}
if ($this->roleId == RoleCode::SUPER_ADMIN) {
$menuIds = $this->adminMenuModel->getAllIds();
$data = (new MenuCache)->getMenu();
// $menuList = $this->adminMenuModel->getAllMenu();
} else {
$menuIds = $this->adminRoleMenuModel->getMenuByRoleId($this->roleId);
$menuList = $this->adminMenuModel->getRoleMenu($menuIds);
$data = $this->getDbMenu($menuList);
}
if (empty($menuIds) || empty($menuList)) {
return [
'role_arr' => [],
'role_list' => []
];
}
$this->delRoleCache();
$this->redis->set($this->roleMenuListKey,json_encode($data),RedisCode::SYSTEM_DB);
$this->redis->sAddBatch($this->roleMenuArrKey,$menuIds,RedisCode::SYSTEM_DB);
return [
'role_arr' => $menuIds,
'role_list' => $data
];
}
/**
* @param int $roleId
* @return void
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws \RedisException
*/
public function delRoleCache(int $roleId = 0): void
{
if ($roleId > 0) {
$this->roleId = $roleId;
$this->getKey();
}
$this->redis->delete($this->roleMenuArrKey,RedisCode::SYSTEM_DB);
$this->redis->delete($this->roleMenuListKey,RedisCode::SYSTEM_DB);
}
}