repository->db->one('SELECT COUNT(*) AS n FROM system_role' . $where, $params)['n']; $offset = ($page - 1) * $size; $rows = $this->repository->db->all('SELECT * FROM system_role' . $where . " ORDER BY sort DESC,id ASC LIMIT {$size} OFFSET {$offset}", $params); return ['lists' => array_map($this->repository->publicRole(...), $rows), 'count' => $count, 'page_no' => $page, 'page_size' => $size]; } public function save(string $action, array $data): array { $allowed = ['name', 'desc', 'sort', 'disable', 'menu_id']; Input::only($data, $action === 'edit' ? [...$allowed, 'id'] : $allowed); return $this->repository->db->transaction(function () use ($action, $data): array { $id = $action === 'edit' ? Input::integer($data['id'] ?? null) : 0; $old = $id ? $this->repository->require('system_role', $id) : []; $source = array_replace($old, $data); $values = ['name' => Input::text($source['name'] ?? null, '角色名称'), 'desc' => Input::text($source['desc'] ?? '', '角色说明', 0, 500), 'sort' => Input::integer($source['sort'] ?? 0, '排序', 0, 1000000), 'disable' => Input::integer($source['disable'] ?? 0, '状态', 0, 1)]; if ($this->repository->db->one('SELECT id FROM system_role WHERE name=? AND id<>?', [$values['name'], $id])) { throw new ApiError(409, '角色名称已存在'); } $menus = array_key_exists('menu_id', $data) ? Input::ids($data['menu_id'], '菜单') : ($id ? $this->repository->ids('system_role_menu', 'role_id', $id, 'menu_id') : []); foreach ($menus as $menuId) { $this->repository->requireReference('system_menu', $menuId, '菜单'); } if ($id) { $this->repository->update('system_role', $id, $values); } else { $id = $this->repository->insert('system_role', $values); } // Explicit [] clears authorization. Missing menu_id preserves the existing grants. $this->repository->replace('system_role_menu', 'role_id', $id, 'menu_id', $menus); return $this->repository->publicRole($this->repository->require('system_role', $id)); }); } public function delete(array $data): array { Input::only($data, ['id']); $id = Input::integer($data['id'] ?? null); return $this->repository->db->transaction(function () use ($id): array { $this->repository->require('system_role', $id); if ($this->repository->db->one('SELECT admin_id FROM admin_role WHERE role_id=?', [$id])) { throw new ApiError(409, '角色仍关联用户,不能删除'); } $this->repository->db->execute('DELETE FROM system_role WHERE id=?', [$id]); return ['id' => $id]; }); } }