94 lines
2.5 KiB
PHP
94 lines
2.5 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
namespace App\Controller\Api\V1;
|
||
|
|
|
||
|
|
use App\Controller\AbstractController;
|
||
|
|
use App\Middleware\AuthMiddleware;
|
||
|
|
use App\Model\User;
|
||
|
|
use Hyperf\HttpServer\Annotation\Controller;
|
||
|
|
use Hyperf\HttpServer\Annotation\Middleware;
|
||
|
|
use Hyperf\HttpServer\Annotation\RequestMapping;
|
||
|
|
|
||
|
|
#[Controller(prefix: "/api/v1/users")]
|
||
|
|
class UserController extends AbstractController
|
||
|
|
{
|
||
|
|
/**
|
||
|
|
* 用户列表
|
||
|
|
*
|
||
|
|
* 支持分页、按 username/email 模糊搜索、按 status 精确筛选
|
||
|
|
*/
|
||
|
|
#[RequestMapping(path: "", methods: "GET")]
|
||
|
|
#[Middleware(AuthMiddleware::class)]
|
||
|
|
public function index(): array
|
||
|
|
{
|
||
|
|
$page = max(1, (int) $this->request->input('page', 1));
|
||
|
|
$per_page = min(100, max(1, (int) $this->request->input('per_page', 15)));
|
||
|
|
|
||
|
|
$query = User::query();
|
||
|
|
|
||
|
|
// 按 username 模糊搜索
|
||
|
|
$username = $this->request->input('username');
|
||
|
|
if ($username !== null && $username !== '') {
|
||
|
|
$query->where('username', 'like', '%' . $username . '%');
|
||
|
|
}
|
||
|
|
|
||
|
|
// 按 email 模糊搜索
|
||
|
|
$email = $this->request->input('email');
|
||
|
|
if ($email !== null && $email !== '') {
|
||
|
|
$query->where('email', 'like', '%' . $email . '%');
|
||
|
|
}
|
||
|
|
|
||
|
|
// 按 status 精确筛选
|
||
|
|
$status = $this->request->input('status');
|
||
|
|
if ($status !== null && $status !== '') {
|
||
|
|
$query->where('status', (int) $status);
|
||
|
|
}
|
||
|
|
|
||
|
|
// 按 created_at 降序排序
|
||
|
|
$query->orderBy('created_at', 'desc');
|
||
|
|
|
||
|
|
$total = $query->count();
|
||
|
|
$items = $query->offset(($page - 1) * $per_page)
|
||
|
|
->limit($per_page)
|
||
|
|
->get();
|
||
|
|
|
||
|
|
return [
|
||
|
|
'code' => 0,
|
||
|
|
'message' => '获取成功',
|
||
|
|
'data' => [
|
||
|
|
'items' => $items,
|
||
|
|
'total' => $total,
|
||
|
|
'page' => $page,
|
||
|
|
'per_page' => $per_page,
|
||
|
|
],
|
||
|
|
];
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 用户详情
|
||
|
|
*
|
||
|
|
* @param int $id 用户 ID
|
||
|
|
*/
|
||
|
|
#[RequestMapping(path: "{id}", methods: "GET")]
|
||
|
|
#[Middleware(AuthMiddleware::class)]
|
||
|
|
public function show(int $id): \Psr\Http\Message\ResponseInterface|array
|
||
|
|
{
|
||
|
|
$user = User::query()->find($id);
|
||
|
|
|
||
|
|
if (!$user) {
|
||
|
|
return $this->response->json([
|
||
|
|
'code' => 404,
|
||
|
|
'message' => '用户不存在',
|
||
|
|
])->withStatus(404);
|
||
|
|
}
|
||
|
|
|
||
|
|
return [
|
||
|
|
'code' => 0,
|
||
|
|
'message' => '获取成功',
|
||
|
|
'data' => $user,
|
||
|
|
];
|
||
|
|
}
|
||
|
|
}
|