78 lines
2.2 KiB
PHP
78 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace app\common\logic;
|
|
|
|
use app\common\model\User;
|
|
|
|
class PermLogic
|
|
{
|
|
/**
|
|
* 获取用户所有资源(合并角色+直接分配)
|
|
*/
|
|
public function getUserResources(int $userId)
|
|
{
|
|
$user = User::with(['roles.resources', 'resources'])->find($userId);
|
|
if (!$user) {
|
|
return collect();
|
|
}
|
|
|
|
$all = collect();
|
|
foreach ($user->roles as $role) {
|
|
$all = $all->merge($role->resources);
|
|
}
|
|
$all = $all->merge($user->resources);
|
|
return $all->unique('id')->values();
|
|
}
|
|
|
|
/**
|
|
* 构建目录/菜单树,节点包含权限与打开方式
|
|
*/
|
|
public function buildTree($resources, int $parentId = 0): array
|
|
{
|
|
$tree = [];
|
|
foreach ($resources as $node) {
|
|
if ($node->parent_id !== $parentId) continue;
|
|
|
|
// 子节点
|
|
$children = $this->buildTree($resources, $node->id);
|
|
|
|
// 本级权限列表
|
|
$authList = $resources
|
|
->filter(fn($r) => $r->type === 'permission' && $r->parent_id === $node->id)
|
|
->map(fn($r) => [
|
|
'id' => $r->id,
|
|
'title' => $r->name,
|
|
'auth_mark' => $r->code,
|
|
])->values()->all();
|
|
|
|
$tree[] = [
|
|
'id' => $node->id,
|
|
'name' => $node->name,
|
|
'path' => $node->url,
|
|
'meta' => [
|
|
'title' => $node->name,
|
|
'icon' => $node->icon,
|
|
'keepAlive' => true,
|
|
'authList' => $authList,
|
|
'openType' => $node->open_type, // 'internal' | 'external' | 'iframe'
|
|
],
|
|
'children' => $children,
|
|
];
|
|
}
|
|
return $tree;
|
|
}
|
|
|
|
/**
|
|
* 获取用户所有权限code
|
|
*/
|
|
public function getPermissionCodes(int $userId): array
|
|
{
|
|
$resources = $this->getUserResources($userId);
|
|
return $resources
|
|
->filter(fn($res) => $res->type === 'permission')
|
|
->pluck('code')
|
|
->unique()
|
|
->values()
|
|
->all();
|
|
}
|
|
} |