first push
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\service;
|
||||
|
||||
use app\model\User;
|
||||
use app\model\Role;
|
||||
use app\model\Resource;
|
||||
|
||||
class ResourceService
|
||||
{
|
||||
/**
|
||||
* 获取用户可见菜单树
|
||||
*/
|
||||
public static function getMenuTreeForUser($userId)
|
||||
{
|
||||
$menuList = self::getUserMenus($userId);
|
||||
// 转树
|
||||
return self::buildTree($menuList);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户所有有权限的菜单资源(type=menu)
|
||||
*/
|
||||
public static function getUserMenus($userId)
|
||||
{
|
||||
$user = User::with('roles.resources')->find($userId);
|
||||
if (!$user) return [];
|
||||
// 合并所有角色下的菜单资源
|
||||
$allMenus = [];
|
||||
foreach ($user->roles as $role) {
|
||||
foreach ($role->resources as $res) {
|
||||
if ($res->type === 'menu') {
|
||||
$allMenus[$res->id] = $res;
|
||||
}
|
||||
}
|
||||
}
|
||||
return array_values($allMenus); // 去重后返回
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户所有有权限的按钮/功能权限 code
|
||||
*/
|
||||
public static function getButtonPermissionCodesForUser($userId)
|
||||
{
|
||||
$user = User::with('roles.resources')->find($userId);
|
||||
if (!$user) return [];
|
||||
$codes = [];
|
||||
foreach ($user->roles as $role) {
|
||||
foreach ($role->resources as $res) {
|
||||
if ($res->type === 'button' && $res->code) {
|
||||
$codes[$res->code] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return array_keys($codes); // 去重后返回权限code数组
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归构建菜单树
|
||||
* @param Resource[] $list
|
||||
* @param int $parentId
|
||||
* @return array
|
||||
*/
|
||||
protected static function buildTree($list, $parentId = 0)
|
||||
{
|
||||
$tree = [];
|
||||
foreach ($list as $item) {
|
||||
if ($item->parent_id == $parentId) {
|
||||
$children = self::buildTree($list, $item->id);
|
||||
$arr = [
|
||||
'id' => $item->id,
|
||||
'name' => $item->name,
|
||||
'path' => $item->url,
|
||||
'icon' => $item->icon ?? null,
|
||||
'code' => $item->code,
|
||||
'children' => $children,
|
||||
];
|
||||
$tree[] = $arr;
|
||||
}
|
||||
}
|
||||
return $tree;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user