Files
zyt/server/app/adminapi/logic/auth/RoleLogic.php
T
2026-11-11 13:53:14 +08:00

215 lines
6.9 KiB
PHP
Executable File

<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\adminapi\logic\auth;
use app\common\{
cache\AdminAuthCache,
model\auth\SystemRole,
logic\BaseLogic,
model\auth\SystemRoleMenu
};
use think\facade\Db;
use app\adminapi\service\AdminAccessSyncService;
use app\common\model\auth\AdminRole;
/**
* 角色逻辑层
* Class RoleLogic
* @package app\adminapi\logic\auth
*/
class RoleLogic extends BaseLogic
{
/**
* @notes 添加角色
* @param array $params
* @return bool
* @author 段誉
* @date 2021/12/29 11:50
*/
public static function add(array $params): bool
{
self::$returnData = [];
Db::startTrans();
try {
$menuId = !empty($params['menu_id']) ? $params['menu_id'] : [];
$role = SystemRole::create([
'name' => $params['name'],
'desc' => $params['desc'] ?? '',
'sort' => $params['sort'] ?? 0,
'data_scope' => self::normalizeDataScope($params['data_scope'] ?? null),
]);
$data = [];
foreach ($menuId as $item) {
if (empty($item)) {
continue;
}
$data[] = [
'role_id' => $role['id'],
'menu_id' => $item,
];
}
if ($data !== []) { (new SystemRoleMenu)->insertAll($data); }
Db::commit();
// 返回本次已提交的角色编号,集团跨目录授权不能按名称或其他表的自增编号猜测。
self::$returnData = ['id' => (int) $role['id']];
return true;
} catch (\Exception $e) {
Db::rollback();
self::$error = $e->getMessage();
return false;
}
}
/**
* @notes 编辑角色
* @param array $params
* @return bool
* @author 段誉
* @date 2021/12/29 14:16
*/
public static function edit(array $params): bool
{
Db::startTrans();
try {
$role = SystemRole::where('id', $params['id'])->lock(true)->findOrEmpty();
if ($role->isEmpty()) { throw new \RuntimeException('角色不存在'); }
$adminIds = AdminAccessSyncService::roleAdminIds([(int) $params['id']]);
$tokens = AdminAccessSyncService::revoke($adminIds);
$menuId = !empty($params['menu_id']) ? $params['menu_id'] : [];
$roleRow = [
'id' => $params['id'],
'name' => $params['name'],
'desc' => $params['desc'] ?? '',
'sort' => $params['sort'] ?? 0,
];
// 分配权限等非编辑页提交的 edit 若不传 data_scope,不得把库里的范围覆盖成默认全部
if (array_key_exists('data_scope', $params)) {
$roleRow['data_scope'] = self::normalizeDataScope($params['data_scope'] ?? null);
}
SystemRole::update($roleRow);
// 显式空数组表示收回全部权限;省略字段表示保留原授权。
if (array_key_exists('menu_id', $params)) {
SystemRoleMenu::where(['role_id' => $params['id']])->delete();
$data = [];
foreach ($menuId as $item) {
$data[] = [
'role_id' => $params['id'],
'menu_id' => $item,
];
}
if ($data !== []) {
(new SystemRoleMenu)->insertAll($data);
}
}
Db::commit();
AdminAccessSyncService::clearCommitted($adminIds, $tokens);
return true;
} catch (\Exception $e) {
Db::rollback();
self::$error = $e->getMessage();
return false;
}
}
/**
* @notes 删除角色
* @param int $id
* @return bool
* @author 段誉
* @date 2021/12/29 14:16
*/
public static function delete(int $id)
{
Db::startTrans();
try {
SystemRole::where('id', $id)->lock(true)->findOrEmpty();
$adminIds = AdminAccessSyncService::roleAdminIds([$id]);
$tokens = AdminAccessSyncService::revoke($adminIds);
SystemRole::destroy(['id' => $id]);
// 原权限查询直接读关联表;软删角色时必须删除关联才能真正收回URI权限。
SystemRoleMenu::where('role_id', $id)->delete();
AdminRole::where('role_id', $id)->delete();
Db::commit();
AdminAccessSyncService::clearCommitted($adminIds, $tokens);
return true;
} catch (\Exception $error) {
Db::rollback();
self::$error = $error->getMessage();
return false;
}
}
/**
* @notes 角色详情
* @param int $id
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 段誉
* @date 2021/12/29 14:17
*/
public static function detail(int $id): array
{
$detail = SystemRole::field('id,name,desc,sort,data_scope')->find($id);
$authList = $detail->roleMenuIndex()->select()->toArray();
$menuId = array_column($authList, 'menu_id');
$detail['menu_id'] = $menuId;
return $detail->toArray();
}
/**
* 规范化 data_scope:合法值 1-4,非法或缺省统一回退为 1(全部),保持与历史默认一致不增加风险。
*/
private static function normalizeDataScope($value): int
{
$v = (int) $value;
if ($v >= 1 && $v <= 4) {
return $v;
}
return 1;
}
/**
* @notes 角色数据
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 段誉
* @date 2022/10/13 10:39
*/
public static function getAllData()
{
return SystemRole::order(['sort' => 'desc', 'id' => 'desc'])
->select()
->toArray();
}
}