Files
zyt/identity-admin/server/app/service/TreeService.php
T
2026-11-11 13:53:14 +08:00

186 lines
8.4 KiB
PHP

<?php
declare(strict_types=1);
namespace app\service;
use app\exception\ApiError;
use app\repository\IdentityRepository;
final class TreeService
{
private const COMPONENTS = ['dashboard/index', 'system/users', 'system/roles', 'system/menus', 'system/depts', 'common/custom'];
public function __construct(private readonly IdentityRepository $repository)
{
}
public static function build(array $rows, int $pid = 0): array
{
$children = [];
foreach ($rows as $row) {
foreach (['id', 'pid', 'sort', 'disable', 'is_show'] as $field) {
if (isset($row[$field])) {
$row[$field] = (int) $row[$field];
}
}
$children[$row['pid']][] = $row;
}
$visit = static function (int $parent, array $seen) use (&$visit, $children): array {
$result = [];
foreach ($children[$parent] ?? [] as $row) {
if (isset($seen[$row['id']])) {
continue;
}
$row['children'] = $visit($row['id'], $seen + [$row['id'] => true]);
$result[] = $row;
}
return $result;
};
return $visit($pid, []);
}
/** Disabled or broken ancestor chains make descendants unavailable for authorization. */
public static function effective(array $rows): array
{
$byId = array_column($rows, null, 'id');
return array_values(array_filter($rows, static function (array $row) use ($byId): bool {
$seen = [];
$id = (int) $row['id'];
while ($id > 0) {
if (isset($seen[$id]) || !isset($byId[$id]) || (int) $byId[$id]['disable'] !== 0) {
return false;
}
$seen[$id] = true;
$id = (int) $byId[$id]['pid'];
}
return true;
}));
}
public function lists(string $kind): array
{
$table = $kind === 'menu' ? 'system_menu' : 'dept';
return self::build($this->repository->db->all("SELECT * FROM `{$table}` ORDER BY sort DESC,id ASC"));
}
public function save(string $kind, string $action, array $data): array
{
$table = $kind === 'menu' ? 'system_menu' : 'dept';
$allowed = ['id', 'pid', 'name', 'sort', 'disable'];
if ($kind === 'menu') {
$allowed = [...$allowed, 'type', 'paths', 'component', 'perms', 'icon', 'is_show'];
}
Input::only($data, $action === 'add' ? array_diff($allowed, ['id']) : $allowed);
return $this->repository->db->transaction(function () use ($kind, $action, $data, $table): array {
$id = $action === 'edit' ? Input::integer($data['id'] ?? null) : 0;
$old = $id ? $this->repository->require($table, $id) : [];
$source = array_replace($old, $data);
$values = [
'pid' => Input::integer($source['pid'] ?? 0, '上级编号', 0),
'name' => Input::text($source['name'] ?? null, '名称', 1, 64),
'sort' => Input::integer($source['sort'] ?? 0, '排序', 0, 1000000),
'disable' => Input::integer($source['disable'] ?? 0, '状态', 0, 1),
];
$this->validateParent($table, $id, $values['pid']);
if ($kind === 'menu') {
$values += $this->menuValues($source);
if ($values['type'] === 'A' && $values['pid'] === 0) {
throw new ApiError(422, '按钮必须归属目录或页面');
}
if ($id && $values['type'] === 'A' && $this->repository->db->one('SELECT id FROM system_menu WHERE pid=?', [$id])) {
throw new ApiError(409, '有子节点的菜单不能改为按钮');
}
if ($values['paths'] !== '' && $this->repository->db->one('SELECT id FROM system_menu WHERE paths=? AND id<>?', [$values['paths'], $id])) {
throw new ApiError(409, '菜单路径已存在');
}
} elseif ($this->repository->db->one('SELECT id FROM dept WHERE pid=? AND name=? AND id<>?', [$values['pid'], $values['name'], $id])) {
throw new ApiError(409, '同级部门名称已存在');
}
if ($id) {
$this->repository->update($table, $id, $values);
} else {
$id = $this->repository->insert($table, $values);
}
$row = $this->repository->require($table, $id);
foreach (['id', 'pid', 'sort', 'disable', 'is_show'] as $field) {
if (isset($row[$field])) { $row[$field] = (int) $row[$field]; }
}
$row['children'] = [];
return $row;
});
}
private function menuValues(array $source): array
{
$type = Input::text($source['type'] ?? null, '菜单类型', 1, 1);
if (!in_array($type, ['M', 'C', 'A'], true)) {
throw new ApiError(422, '菜单类型必须为M/C/A');
}
$paths = Input::text($source['paths'] ?? '', '路径', 0, 200);
$component = Input::text($source['component'] ?? '', '组件', 0, 64);
$perms = Input::text($source['perms'] ?? '', '权限', 0, 100);
if (($paths !== '' && (!preg_match('~^/[a-zA-Z0-9_/-]*$~D', $paths)
|| str_contains($paths, '//') || str_ends_with($paths, '/')
|| in_array($paths, ['/login', '/profile', '/403', '/'], true)))
|| ($type === 'C' && $paths === '')) {
throw new ApiError(422, '页面路径须为有效绝对路径');
}
if ($type === 'C' && !in_array($component, self::COMPONENTS, true)) {
throw new ApiError(422, '页面组件不在白名单内');
}
if ($paths === '/dashboard' && ($type !== 'C' || $component !== 'dashboard/index')) {
throw new ApiError(422, '首页路径仅允许使用首页组件');
}
if ($perms !== '' && !preg_match('~^[a-z][a-z0-9_.]*/[a-z][a-z0-9_]*$~D', $perms)) {
throw new ApiError(422, '权限键格式错误');
}
if (($type === 'A' || ($type === 'C' && $paths !== '/dashboard')) && $perms === '') {
throw new ApiError(422, '页面和按钮必须填写权限键');
}
return ['type' => $type, 'paths' => $type === 'A' ? '' : $paths,
'component' => $type === 'C' ? $component : '', 'perms' => $type === 'M' ? '' : $perms,
'icon' => Input::text($source['icon'] ?? '', '图标', 0, 64),
'is_show' => Input::integer($source['is_show'] ?? 1, '显示状态', 0, 1)];
}
private function validateParent(string $table, int $id, int $pid): void
{
$seen = [];
$depth = 0;
while ($pid > 0) {
if ($pid === $id || isset($seen[$pid])) {
throw new ApiError(422, '上级节点不能是自己或后代');
}
if (++$depth > 64) {
throw new ApiError(422, '层级不能超过64层');
}
$seen[$pid] = true;
$parent = $this->repository->requireReference($table, $pid, $table === 'system_menu' ? '上级菜单' : '上级部门');
if ($table === 'system_menu' && $parent['type'] === 'A') {
throw new ApiError(422, '按钮不能作为上级菜单');
}
$pid = (int) $parent['pid'];
}
}
public function delete(string $kind, array $data): array
{
Input::only($data, ['id']);
$id = Input::integer($data['id'] ?? null);
$table = $kind === 'menu' ? 'system_menu' : 'dept';
return $this->repository->db->transaction(function () use ($kind, $id, $table): array {
$this->repository->require($table, $id);
if ($this->repository->db->one("SELECT id FROM `{$table}` WHERE pid=?", [$id])) {
throw new ApiError(409, '存在子节点,不能删除');
}
if ($kind === 'dept' && $this->repository->db->one('SELECT admin_id FROM admin_dept WHERE dept_id=?', [$id])) {
throw new ApiError(409, '部门仍关联用户,不能删除');
}
if ($kind === 'menu') {
$this->repository->db->execute('DELETE FROM system_role_menu WHERE menu_id=?', [$id]);
}
$this->repository->db->execute("DELETE FROM `{$table}` WHERE id=?", [$id]);
return ['id' => $id];
});
}
}