diff --git a/.htaccess b/.htaccess new file mode 100644 index 0000000..0519ecb --- /dev/null +++ b/.htaccess @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/.phpstorm.meta.php b/.phpstorm.meta.php index 5ba7d5f..6f93e37 100644 --- a/.phpstorm.meta.php +++ b/.phpstorm.meta.php @@ -4,7 +4,7 @@ // Reflect override(\Psr\Container\ContainerInterface::get(0), map('@')); - override(\Hyperf\Utils\Context::get(0), map('@')); + override(\Hyperf\Context\Context::get(0), map('@')); override(\make(0), map('@')); override(\di(0), map('@')); diff --git a/app/Command/Bilibili/BilibiliUpUserReport.php b/app/Command/Bilibili/BilibiliUpUserReport.php index 2799c82..ff6faff 100644 --- a/app/Command/Bilibili/BilibiliUpUserReport.php +++ b/app/Command/Bilibili/BilibiliUpUserReport.php @@ -9,17 +9,11 @@ use Hyperf\Crontab\Annotation\Crontab; use Hyperf\Di\Annotation\Inject; -/** - * @Crontab(name="BilibiliUpUserReport", rule="00 * * * *", callback="execute", memo="BilibiliUp主数据采集定时任务") - */ +#[Crontab(rule: "00 * * * *", name: "BilibiliUpUserReport", callback: "execute", memo: "BilibiliUp主数据采集定时任务")] class BilibiliUpUserReport { - /** - * - * @Inject() - * @var UpUser - */ - private $biliUpUser; + #[Inject] + private UpUser $biliUpUser; /** * 定时记录主播数据变化情况 diff --git a/app/Command/Bilibili/BilibiliVideoReport.php b/app/Command/Bilibili/BilibiliVideoReport.php index f3ca972..a001b5c 100644 --- a/app/Command/Bilibili/BilibiliVideoReport.php +++ b/app/Command/Bilibili/BilibiliVideoReport.php @@ -8,17 +8,11 @@ use Hyperf\Crontab\Annotation\Crontab; use Hyperf\Di\Annotation\Inject; -/** - * @Crontab(name="BilibiliVideoReport", rule="00 * * * *", callback="execute", memo="BilibiliUp视频数据报表采集") - */ +#[Crontab(rule: "00 * * * *", name: "BilibiliVideoReport", callback: "execute", memo: "BilibiliUp视频数据报表采集")] class BilibiliVideoReport { - /** - * - * @Inject() - * @var Video - */ - private $video; + #[Inject] + private Video $video; /** * 定时记录视频数据变化 diff --git a/app/Command/InitCommand.php b/app/Command/InitCommand.php index 92eb2c1..d60b151 100644 --- a/app/Command/InitCommand.php +++ b/app/Command/InitCommand.php @@ -13,23 +13,16 @@ use Donjan\Permission\Models\Permission; use Donjan\Permission\Models\Role; -/** - * @Command - */ +#[Command] class InitCommand extends HyperfCommand { - /** - * 执行的命令行 - * - * @var string - */ - protected $name = 'init'; + protected ?string $name = 'init'; public function configure() { parent::configure(); - $this->setHelp('HyperfCms 项目初始化'); - $this->setDescription('HyperfCms 项目初始化'); + $this->setHelp('项目初始化'); + $this->setDescription('项目初始化'); } /** diff --git a/app/Command/InitDataSeederCommand.php b/app/Command/InitDataSeederCommand.php index 7074b6a..894d218 100644 --- a/app/Command/InitDataSeederCommand.php +++ b/app/Command/InitDataSeederCommand.php @@ -4,26 +4,19 @@ namespace App\Command; -use App\Model\Auth\User; use App\Model\System\DictData; use App\Model\System\DictType; -use App\Model\System\GlobalConfig; -use Hyperf\Command\Command as HyperfCommand; use Hyperf\Command\Annotation\Command; use Donjan\Permission\Models\Permission; -use Donjan\Permission\Models\Role; +use Hyperf\Command\Command as HyperfCommand; -/** - * @Command - */ +#[Command] class InitDataSeederCommand extends HyperfCommand { /** * 执行的命令行 - * - * @var string */ - protected $name = 'init:data_seeder'; + protected ?string $name = 'init:data_seeder'; public function configure() { diff --git a/app/Controller/AbstractController.php b/app/Controller/AbstractController.php index 6b78f40..fd67974 100644 --- a/app/Controller/AbstractController.php +++ b/app/Controller/AbstractController.php @@ -1,6 +1,6 @@ $this->request->input('username') ?? '', + 'username' => $this->request->input('username') ?? '', 'password' => $this->request->input('password') ?? '', 'code_key' => $this->request->input('code_key') ?? '', - 'captcha' => $this->request->input('captcha') ?? '', + 'captcha' => $this->request->input('captcha') ?? '' ]; $rules = [ 'username' => 'required', 'password' => 'required|min:6|max:18', 'code_key' => 'required', - 'captcha' => 'required', + 'captcha' => 'required' ]; $message = [ 'username.required' => ' username 缺失', @@ -53,28 +47,28 @@ public function login() 'password.min' => ' password 最少6位数', 'password.max' => ' password 最多18位数', 'code_key.required' => '验证码KEY缺失', - 'captcha.required' => '验证码缺失', + 'captcha.required' => '验证码缺失' ]; $this->verifyParams($params, $rules, $message); - $responseData = LoginService::getInstance()->login($params); return $this->success($responseData); } + /** * 注册操作 - * @RequestMapping(path="register", methods="post") * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'register', methods: array('POST'))] public function register() { $params = [ - 'username' => $this->request->input('username') ?? '', + 'username' => $this->request->input('username') ?? '', 'password' => $this->request->input('password') ?? '', 'password_confirmation' => $this->request->input('password_confirmation') ?? '', 'desc' => $this->request->input('desc') ?? '', 'code_key' => $this->request->input('code_key') ?? '', - 'captcha' => $this->request->input('captcha') ?? '', + 'captcha' => $this->request->input('captcha') ?? '' ]; $rules = [ 'username' => 'required|min:4|max:18|unique:users', @@ -82,7 +76,7 @@ public function register() 'password_confirmation' => 'required|min:6|max:18', 'desc' => 'required', 'code_key' => 'required', - 'captcha' => 'required', + 'captcha' => 'required' ]; $message = [ 'username.required' => ' username 缺失', @@ -97,7 +91,7 @@ public function register() 'password.max' => ' password 最多18位数', 'password_confirmation.max' => ' password 最多18位数', 'code_key.required' => '验证码KEY缺失', - 'captcha.required' => '验证码缺失', + 'captcha.required' => '验证码缺失' ]; $this->verifyParams($params, $rules, $message); @@ -107,31 +101,27 @@ public function register() return $this->successByMessage('注册成功, 跳转登陆中...'); } - /** - * 初始化操作 - * @RequestMapping(path="initialization", methods="get") - * @Middlewares({ - @Middleware(RequestMiddleware::class) - * }) + * 初始化用户 + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface - * @throws \Psr\SimpleCache\InvalidArgumentException */ + #[RequestMapping(path: 'initialization', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function initialization() { - $list = LoginService::getInstance()->initialization(); - return $this->success($list); + return $this->success(LoginService::getInstance()->initialization()); } /** - * 获取前端路由 - * @RequestMapping(path="routers", methods="get") - * @Middlewares({ - @Middleware(RequestMiddleware::class) - * }) + * 获取路由操作 + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface - * @throws \Psr\SimpleCache\InvalidArgumentException */ + #[RequestMapping(path: 'routers', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function getRouters() { $list = LoginService::getInstance()->getRouters(); @@ -139,17 +129,17 @@ public function getRouters() } /** - * 退出登录操作 - * @RequestMapping(path="logout", methods="post") - * @Middlewares({ - @Middleware(RequestMiddleware::class) -* }) + * 登出操作 + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface * @throws \Psr\SimpleCache\InvalidArgumentException */ + #[RequestMapping(path: 'logout', methods: array('POST'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function logOut() { $this->jwt->logout(); return $this->success([], '退出登录成功'); } -} +} \ No newline at end of file diff --git a/app/Controller/Auth/PermissionController.php b/app/Controller/Auth/PermissionController.php index 37a2fbb..d7c4e00 100644 --- a/app/Controller/Auth/PermissionController.php +++ b/app/Controller/Auth/PermissionController.php @@ -14,32 +14,27 @@ use Hyperf\Di\Annotation\Inject; use Hyperf\HttpServer\Annotation\Controller; use Hyperf\HttpServer\Annotation\Middleware; -use App\Middleware\RequestMiddleware; -use App\Middleware\PermissionMiddleware; -use Hyperf\HttpServer\Annotation\Middlewares; use Hyperf\HttpServer\Annotation\RequestMapping; /** * 权限控制器 * Class PermissionController - * @Controller(prefix="setting/user_module/permission") */ +#[Controller(prefix: 'setting/user_module/permission')] class PermissionController extends AbstractController { - /** - * @Inject() - * @var Permission - */ - private $permission; + #[Inject] + private Permission $permission; /** * 获取权限数据列表 - * @RequestMapping(path="list", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * @Author YiYuan + * @Date 2023/12/1 + * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'list', methods: array('get'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function index() { $permissionQuery = $this->permission->newQuery(); @@ -66,10 +61,13 @@ public function index() } /** - * 根据用户获取权限树状列表(用于分配用户权限) - * @RequestMapping(path="tree_by_user", methods="get") - * @Middleware(RequestMiddleware::class) + * 根据用户获取权限树状列表 + * @Author YiYuan + * @Date 2023/12/1 + * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'tree_by_user', methods: array('get'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function treeByUser() { $userId = $this->request->all()['user_id'] ?? ''; @@ -92,10 +90,13 @@ public function treeByUser() } /** - * 根据角色获取权限树状列表(用于分配角色权限) - * @RequestMapping(path="tree_by_role", methods="get") - * @Middleware(RequestMiddleware::class) + * 根据角色获取权限树状列表 + * @Author YiYuan + * @Date 2023/12/1 + * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'tree_by_role', methods: array('get'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function treeByRole() { $roleId = $this->request->all()['role_id'] ?? ''; @@ -118,13 +119,15 @@ public function treeByRole() } /** - * @Explanation(content="添加权限操作") - * @RequestMapping(path="store", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 添加权限操作 + * @Author YiYuan + * @Date 2023/12/1 + * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '添加权限操作')] + #[RequestMapping(path: 'store', methods: array('post'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function store() { $postData = $this->request->all(); @@ -174,14 +177,14 @@ public function store() /** * 获取单个权限的数据 - * @param int $id - * @RequestMapping(path="edit/{id}", methods="get") - * @Middleware(RequestMiddleware::class) + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'edit/{id}', methods: array('get'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function edit(int $id) { - $permissionInfo = Permission::findById($id); if (empty($permissionInfo)) $this->throwExp(StatusCode::ERR_VALIDATION, '获取权限信息失败'); @@ -191,15 +194,15 @@ public function edit(int $id) } /** - * @Explanation(content="修改权限操作") - * @param int $id - * @RequestMapping(path="update/{id}", methods="put") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 修改权限操作 + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '修改权限操作')] + #[RequestMapping(path: 'update/{id}', methods: array('put'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function update(int $id) { $postData = $this->request->all(); @@ -248,15 +251,15 @@ public function update(int $id) } /** - * @Explanation(content="删除权限操作") - * @param int $id - * @RequestMapping(path="destroy/{id}", methods="delete") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 删除权限操作 + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '删除权限操作')] + #[RequestMapping(path: 'destroy/{id}', methods: array('delete'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function destroy(int $id) { $params = [ @@ -273,20 +276,21 @@ public function destroy(int $id) $this->verifyParams($params, $rules, $message); if (!Permission::query()->where('parent_id', $id)->get()->isEmpty()) $this->throwExp(StatusCode::ERR_VALIDATION, '该权限下还有子权限,删除失败'); - + if (!Permission::query()->where('id', $id)->delete()) $this->throwExp(StatusCode::ERR_VALIDATION, '删除权限信息失败'); return $this->successByMessage('删除权限信息成功'); } /** - * @Explanation(content="分配用户角色") - * @RequestMapping(path="accord_user_role", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 分配用户角色 + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '分配用户角色')] + #[RequestMapping(path: 'accord_user_role', methods: array('post'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function accordUserRole() { $postData = $this->request->all() ?? []; @@ -317,16 +321,16 @@ public function accordUserRole() return $this->successByMessage( '分配用户角色成功'); } - /** - * @Explanation(content="分配角色权限") - * @RequestMapping(path="accord_role_permission", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 分配角色权限 + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '分配角色权限')] + #[RequestMapping(path: 'accord_role_permission', methods: array('post'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function accordRolePermission() { $postData = $this->request->all() ?? []; @@ -359,14 +363,15 @@ public function accordRolePermission() } /** - * @Explanation(content="分配用户权限") - * @RequestMapping(path="accord_user_permission", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 分配用户权限 + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '分配用户权限')] + #[RequestMapping(path: 'accord_user_permission', methods: array('post'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function accordUserPermission() { $postData = $this->request->all() ?? ''; diff --git a/app/Controller/Auth/RoleController.php b/app/Controller/Auth/RoleController.php index 26863df..32ca838 100644 --- a/app/Controller/Auth/RoleController.php +++ b/app/Controller/Auth/RoleController.php @@ -11,32 +11,27 @@ use Hyperf\Di\Annotation\Inject; use Hyperf\HttpServer\Annotation\Controller; use Hyperf\HttpServer\Annotation\Middleware; -use App\Middleware\RequestMiddleware; -use App\Middleware\PermissionMiddleware; -use Hyperf\HttpServer\Annotation\Middlewares; use Hyperf\HttpServer\Annotation\RequestMapping; /** * 角色控制器 * Class RoleController - * @Controller(prefix="setting/user_module/role") */ +#[Controller(prefix: 'setting/user_module/role')] class RoleController extends AbstractController { - /** - * @Inject() - * @var Role - */ - private $role; + #[Inject] + private Role $role; /** * 获取角色数据列表 - * @RequestMapping(path="list", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * @Author YiYuan + * @Date 2023/12/1 + * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'list', methods: array('get'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function index() { $roleQuery = $this->role->newQuery(); @@ -54,10 +49,13 @@ public function index() } /** - * 获取角色数据列表 - * @RequestMapping(path="tree", methods="get") + * 获取角色数据树状列表 + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'tree', methods: array('get'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function tree() { $roleQuery = $this->role->newQuery(); @@ -70,13 +68,15 @@ public function tree() } /** - * @Explanation(content="添加角色操作") - * @RequestMapping(path="store", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 添加角色操作 + * @Author YiYuan + * @Date 2023/12/1 + * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '添加角色操作')] + #[RequestMapping(path: 'store', methods: array('post'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function store() { $postData = $this->request->all(); @@ -100,11 +100,12 @@ public function store() /** * 获取单个角色的数据 - * @param int $id - * @RequestMapping(path="edit/{id}", methods="get") - * @Middleware(RequestMiddleware::class) + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'edit/{id}', methods: array('get'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function edit(int $id) { $roleInfo = Role::getOneByRoleId($id); @@ -116,15 +117,15 @@ public function edit(int $id) } /** - * @Explanation(content="修改角色操作") - * @param int $id - * @RequestMapping(path="update/{id}", methods="put") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 修改角色操作 + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '修改角色操作')] + #[RequestMapping(path: 'update/{id}', methods: array('put'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function update(int $id) { $postData = $this->request->all(); @@ -151,15 +152,15 @@ public function update(int $id) } /** - * @Explanation(content="删除角色操作") - * @param int $id - * @RequestMapping(path="destroy/{id}", methods="delete") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 删除角色操作 + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '删除角色操作')] + #[RequestMapping(path: 'destroy/{id}', methods: array('delete'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function destroy(int $id) { $params = [ @@ -179,5 +180,4 @@ public function destroy(int $id) return $this->successByMessage('删除角色信息成功'); } - } diff --git a/app/Controller/Auth/UserController.php b/app/Controller/Auth/UserController.php index daf480b..98eab27 100644 --- a/app/Controller/Auth/UserController.php +++ b/app/Controller/Auth/UserController.php @@ -13,42 +13,35 @@ use App\Model\Auth\User; use Donjan\Permission\Models\Role; use Hyperf\DbConnection\Db; +use Hyperf\Di\Annotation\AnnotationCollector; use Hyperf\Di\Annotation\Inject; use Hyperf\HttpServer\Annotation\Controller; use Hyperf\HttpServer\Annotation\Middleware; -use App\Middleware\RequestMiddleware; -use App\Middleware\PermissionMiddleware; -use Hyperf\HttpServer\Annotation\Middlewares; use Hyperf\HttpServer\Annotation\RequestMapping; use League\Flysystem\Filesystem; /** * 用户控制器 * Class UserController - * @Controller(prefix="setting/user_module/user") */ +#[Controller(prefix: 'setting/user_module/user')] class UserController extends AbstractController { - /** - * @Inject() - * @var User - */ - private $user; + #[Inject] + private User $user; - /** - * @Inject() - * @var Filesystem - */ - private $filesystem; + #[Inject] + private Filesystem $filesystem; /** * 获取用户数据列表 - * @RequestMapping(path="list", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * @Author YiYuan + * @Date 2023/12/1 + * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'list', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function index() { $userQuery = $this->user->newQuery(); @@ -80,13 +73,15 @@ public function index() } /** - * @Explanation(content="添加用户操作") - * @RequestMapping(path="store", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 添加 + * @Author YiYuan + * @Date 2023/12/1 + * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '添加用户操作')] + #[RequestMapping(path: 'store', methods: array('post'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function store() { $postData = $this->request->all(); @@ -151,11 +146,12 @@ public function store() /** * 获取单个用户的数据 - * @param int $id - * @RequestMapping(path="edit/{id}", methods="get") - * @Middleware(RequestMiddleware::class) + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'edit/{id}', methods: array('get'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function edit(int $id) { $userInfo = User::getOneByUid($id); @@ -168,13 +164,14 @@ public function edit(int $id) ]); } - /** * 获取当前登陆用户的数据 - * @RequestMapping(path="profile", methods="get") - * @Middleware(RequestMiddleware::class) + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'profile', methods: array('get'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function profile() { $userInfo = UserService::getInstance()->getUserInfoByToken(); @@ -192,11 +189,12 @@ public function profile() /** * 获取当前登陆用户的数据 - * @param int $id - * @RequestMapping(path="profile/{id}", methods="put") - * @Middleware(RequestMiddleware::class) + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'profile/{id}', methods: array('put'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function profileEdit($id) { if (empty($id)) $this->throwExp(StatusCode::ERR_VALIDATION, 'ID 不能为空'); @@ -215,10 +213,15 @@ public function profileEdit($id) } /** - * @Explanation(content="上传用户头像") - * @RequestMapping(path="upload_avatar", methods="post") - * @Middleware(RequestMiddleware::class) + * 上传用户头像 + * @Author YiYuan + * @Date 2023/12/1 + * @return \Psr\Http\Message\ResponseInterface + * @throws \League\Flysystem\FilesystemException */ + #[Explanation(content: '上传用户头像')] + #[RequestMapping(path: 'upload_avatar', methods: array('post'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function uploadAvatar() { $params = [ @@ -268,17 +271,16 @@ public function uploadAvatar() ], '上传图片成功'); } - /** - * @Explanation(content="修改用户资料") - * @param int $id - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) - * @RequestMapping(path="update/{id}", methods="put") + * 修改 + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '修改用户资料')] + #[RequestMapping(path: 'update/{id}', methods: array('put'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function update(int $id) { if (empty($id)) $this->throwExp(StatusCode::ERR_VALIDATION, 'ID 不能为空'); @@ -337,15 +339,15 @@ public function update(int $id) } /** - * @Explanation(content="删除用户") - * @param int $id - * @RequestMapping(path="destroy/{id}", methods="delete") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 删除用户 + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '删除用户')] + #[RequestMapping(path: 'destroy/{id}', methods: array('delete'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function destroy(int $id) { if ($id == 0) { @@ -364,14 +366,15 @@ public function destroy(int $id) } /** - * @Explanation(content="修改用户密码") - * @RequestMapping(path="reset_password", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 修改用户密码 + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '修改用户密码')] + #[RequestMapping(path: 'reset_password', methods: array('post'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function resetPassword() { $postData = $this->request->all() ?? []; @@ -409,15 +412,17 @@ public function resetPassword() return $this->success([], '修改密码成功'); } + /** - * @Explanation(content="修改用户状态") - * @RequestMapping(path="change_status", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 修改用户状态 + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '修改用户状态')] + #[RequestMapping(path: 'change_status', methods: array('post'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function changeStatus() { $postData = $this->request->all() ?? []; diff --git a/app/Controller/Blog/AlbumController.php b/app/Controller/Blog/AlbumController.php index ee8d8a9..44c541c 100644 --- a/app/Controller/Blog/AlbumController.php +++ b/app/Controller/Blog/AlbumController.php @@ -1,7 +1,6 @@ photoAlbum->newQuery(); $albumName = $this->request->input('album_name') ?? ''; $albumStatus = $this->request->input('album_status') ?? ''; - if (!empty($albumName)) $photoAlbumQuery->where('album_name', 'like', '%' . $albumName . '%'); - if (strlen($albumStatus) > 0) $photoAlbumQuery->where('album_status', $albumStatus); - + if (!empty($albumName)) { + $photoAlbumQuery->where('album_name', 'like', '%' . $albumName . '%'); + } + if (strlen($albumStatus) > 0) { + $photoAlbumQuery->where('album_status', $albumStatus); + } $total = $photoAlbumQuery->count(); $photoAlbumQuery = $this->pagingCondition($photoAlbumQuery, $this->request->all()); $data = $photoAlbumQuery->get(); - - return $this->success([ - 'list' => $data, - 'total' => $total, - ]); + return $this->success(['list' => $data, 'total' => $total]); } /** - * 获取相册列表 - * @RequestMapping(path="album_option", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) + * 相册选项列表 + * @Author YiYuan + * @Date 2023/12/1 + * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'album_option', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function albumOptionList() { $photoAlbumQuery = $this->photoAlbum->newQuery(); $photoAlbumQuery = $photoAlbumQuery->select('id', 'album_name'); $data = $photoAlbumQuery->get(); - - return $this->success([ - 'list' => $data, - ]); + return $this->success(['list' => $data]); } /** - * @Explanation(content="添加相册") - * @RequestMapping(path="store", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 添加 + * @Author YiYuan + * @Date 2023/12/1 + * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '添加相册操作')] + #[RequestMapping(path: 'store', methods: array('POST'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function store() { $postData = $this->request->all(); - $params = [ - 'album_name' => $postData['album_name'] ?? '', - 'album_desc' => $postData['album_desc'] ?? '', - 'album_type' => $postData['album_type'] ?? 1, - 'album_status' => $postData['album_status'] ?? 1, - 'album_author' => $postData['album_author'] ?? '', - 'album_cover' => $postData['album_cover'] ?? '', - 'album_question' => $postData['album_question'] ?? '', - 'album_answer' => $postData['album_answer'] ?? '', - 'album_sort' => $postData['album_sort'] ?? 99 - ]; + $params = ['album_name' => $postData['album_name'] ?? '', 'album_desc' => $postData['album_desc'] ?? '', 'album_type' => $postData['album_type'] ?? 1, 'album_status' => $postData['album_status'] ?? 1, 'album_author' => $postData['album_author'] ?? '', 'album_cover' => $postData['album_cover'] ?? '', 'album_question' => $postData['album_question'] ?? '', 'album_answer' => $postData['album_answer'] ?? '', 'album_sort' => $postData['album_sort'] ?? 99]; //配置验证 - $rules = [ - 'album_name' => 'required', - ]; + $rules = ['album_name' => 'required']; //错误信息 - $message = [ - 'album_name.required' => '[album_name]缺失', - ]; + $message = ['album_name.required' => '[album_name]缺失']; if ($params['album_type'] == 2) { $rules['album_question'] = 'required'; $rules['album_answer'] = 'required'; @@ -112,7 +94,6 @@ public function store() $message['album_answer.required'] = '[album_answer]缺失'; } $this->verifyParams($params, $rules, $message); - $photoAlbumObj = new PhotoAlbum(); $photoAlbumObj->album_name = $params['album_name']; $photoAlbumObj->album_desc = $params['album_desc']; @@ -123,69 +104,53 @@ public function store() $photoAlbumObj->album_question = $params['album_question']; $photoAlbumObj->album_answer = $params['album_answer']; $photoAlbumObj->album_sort = $params['album_sort']; - if (!$photoAlbumObj->save()) $this->throwExp(StatusCode::ERR_EXCEPTION, '添加相册错误'); - + if (!$photoAlbumObj->save()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '添加相册错误'); + } return $this->successByMessage('添加相册成功'); } /** - * 获取单个字典数据信息 + * 获取编辑选项 + * @Author YiYuan + * @Date 2023/12/1 * @param int $id - * @RequestMapping(path="edit/{id}", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'edit/{id}', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function edit(int $id) { $dictDataInfo = PhotoAlbum::findById($id); - if (empty($dictDataInfo)) $this->throwExp(StatusCode::ERR_USER_ABSENT, '获取相册信息失败'); - - return $this->success([ - 'list' => $dictDataInfo - ]); + if (empty($dictDataInfo)) { + $this->throwExp(StatusCode::ERR_USER_ABSENT, '获取相册信息失败'); + } + return $this->success(['list' => $dictDataInfo]); } /** - * @Explanation(content="修改相册信息") + * 修改 + * @Author YiYuan + * @Date 2023/12/1 * @param int $id - * @RequestMapping(path="update/{id}", methods="put") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '修改相册')] + #[RequestMapping(path: 'update/{id}', methods: array('PUT'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function update(int $id) { - if (empty($id)) $this->throwExp(StatusCode::ERR_VALIDATION, 'ID 不能为空'); + if (empty($id)) { + $this->throwExp(StatusCode::ERR_VALIDATION, 'ID 不能为空'); + } $postData = $this->request->all(); - $params = [ - 'id' => $id, - 'album_name' => $postData['album_name'] ?? '', - 'album_desc' => $postData['album_desc'] ?? '', - 'album_type' => $postData['album_type'] ?? 1, - 'album_status' => $postData['album_status'] ?? 1, - 'album_author' => $postData['album_author'] ?? '', - 'album_cover' => $postData['album_cover'] ?? '', - 'album_question' => $postData['album_question'] ?? '', - 'album_answer' => $postData['album_answer'] ?? '', - 'album_sort' => $postData['album_sort'] ?? 99 - ]; + $params = ['id' => $id, 'album_name' => $postData['album_name'] ?? '', 'album_desc' => $postData['album_desc'] ?? '', 'album_type' => $postData['album_type'] ?? 1, 'album_status' => $postData['album_status'] ?? 1, 'album_author' => $postData['album_author'] ?? '', 'album_cover' => $postData['album_cover'] ?? '', 'album_question' => $postData['album_question'] ?? '', 'album_answer' => $postData['album_answer'] ?? '', 'album_sort' => $postData['album_sort'] ?? 99]; //配置验证 - $rules = [ - 'album_name' => 'required', - 'id' => 'required|integer', - ]; + $rules = ['album_name' => 'required', 'id' => 'required|integer']; //错误信息 - $message = [ - 'album_name.required' => '[album_name]缺失', - 'id.required' => '[id]缺失', - 'id.integer' => '[id] 必须为整型', - ]; + $message = ['album_name.required' => '[album_name]缺失', 'id.required' => '[id]缺失', 'id.integer' => '[id] 必须为整型']; $this->verifyParams($params, $rules, $message); - $photoAlbumObj = PhotoAlbum::findById($id); $photoAlbumObj->album_name = $params['album_name']; $photoAlbumObj->album_desc = $params['album_desc']; @@ -196,33 +161,41 @@ public function update(int $id) $photoAlbumObj->album_question = $params['album_question']; $photoAlbumObj->album_answer = $params['album_answer']; $photoAlbumObj->album_sort = $params['album_sort']; - if (!$photoAlbumObj->save()) $this->throwExp(StatusCode::ERR_EXCEPTION, '修改相册信息错误'); - + if (!$photoAlbumObj->save()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '修改相册信息错误'); + } return $this->successByMessage('修改相册信息成功'); } /** - * @Explanation(content="删除相册信息") + * 删除 + * @Author YiYuan + * @Date 2023/12/1 * @param int $id - * @RequestMapping(path="destroy/{id}", methods="delete") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '删除相册')] + #[RequestMapping(path: 'destroy/{id}', methods: array('DELETE'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function destroy(int $id) { if ($id == 0) { $idArr = $this->request->input('id') ?? []; - if (empty($idArr) || !is_array($idArr)) $this->throwExp(StatusCode::ERR_VALIDATION, '参数类型不正确'); - if (!PhotoAlbum::whereIn('id', $idArr)->delete()) $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); - }else { - if (!intval($id)) $this->throwExp(StatusCode::ERR_VALIDATION, '参数错误'); - if (!PhotoAlbum::destroy($id)) $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + if (empty($idArr) || !is_array($idArr)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '参数类型不正确'); + } + if (!PhotoAlbum::whereIn('id', $idArr)->delete()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + } + } else { + if (!intval($id)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '参数错误'); + } + if (!PhotoAlbum::destroy($id)) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + } } - return $this->successByMessage('删除相册成功'); } - } \ No newline at end of file diff --git a/app/Controller/Blog/PhotoController.php b/app/Controller/Blog/PhotoController.php index 1298a5e..17cf0ee 100644 --- a/app/Controller/Blog/PhotoController.php +++ b/app/Controller/Blog/PhotoController.php @@ -1,7 +1,6 @@ photo->newQuery(); $photoAlbum = $this->request->input('photo_album') ?? ''; - if (!empty($photoAlbum)) $photoQuery->where('photo_album', $photoAlbum); - + if (!empty($photoAlbum)) { + $photoQuery->where('photo_album', $photoAlbum); + } $total = $photoQuery->count(); $photoQuery = $this->pagingCondition($photoQuery, $this->request->all()); $photoQuery->with('getPhotoAlbum:id,album_name'); $data = $photoQuery->get(); - - return $this->success([ - 'list' => $data, - 'total' => $total, - ]); + return $this->success(['list' => $data, 'total' => $total]); } /** - * @Explanation(content="添加图片") - * @RequestMapping(path="store", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 添加 + * @Author YiYuan + * @Date 2023/12/1 + * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '添加图片')] + #[RequestMapping(path: 'store', methods: array('POST'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function store() { - $postData = $this->request->all(); - $params = [ - 'photo_url' => $postData['photo_url'] ?? '', - 'photo_album' => $postData['photo_album'] ?? '', - ]; + $params = ['photo_url' => $postData['photo_url'] ?? '', 'photo_album' => $postData['photo_album'] ?? '']; //配置验证 - $rules = [ - 'photo_url' => 'required|array', - 'photo_album' => 'required', - ]; + $rules = ['photo_url' => 'required|array', 'photo_album' => 'required']; //错误信息 - $message = [ - 'photo_url.required' => '[photo_url]缺失', - 'photo_url.array' => '[photo_url] 类型必须为数组', - 'photo_album.required' => '[photo_album]缺失', - ]; + $message = ['photo_url.required' => '[photo_url]缺失', 'photo_url.array' => '[photo_url] 类型必须为数组', 'photo_album.required' => '[photo_album]缺失']; $this->verifyParams($params, $rules, $message); - if (is_array($params['photo_url'])) { foreach ($params['photo_url'] as $key) { - Photo::query()->insert([ - 'photo_url' => $key, - 'photo_album' => $params['photo_album'], - 'created_at' => date('Y-m-d H:i:s'), - 'updated_at' => date('Y-m-d H:i:s'), - ]); + Photo::query()->insert(['photo_url' => $key, 'photo_album' => $params['photo_album'], 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')]); } } return $this->successByMessage('添加照片成功'); } /** - * @Explanation(content="删除图片信息") + * 删除 + * @Author YiYuan + * @Date 2023/12/1 * @param int $id - * @RequestMapping(path="destroy/{id}", methods="delete") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '删除图片')] + #[RequestMapping(path: 'destroy/{id}', methods: array('DELETE'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function destroy(int $id) { if ($id == 0) { $idArr = $this->request->input('id') ?? []; - if (empty($idArr) || !is_array($idArr)) $this->throwExp(StatusCode::ERR_VALIDATION, '参数类型不正确'); - if (!Photo::whereIn('id', $idArr)->delete()) $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); - }else { - if (!intval($id)) $this->throwExp(StatusCode::ERR_VALIDATION, '参数错误'); - if (!Photo::destroy($id)) $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + if (empty($idArr) || !is_array($idArr)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '参数类型不正确'); + } + if (!Photo::whereIn('id', $idArr)->delete()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + } + } else { + if (!$id) { + $this->throwExp(StatusCode::ERR_VALIDATION, '参数错误'); + } + if (!Photo::destroy($id)) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + } } - return $this->successByMessage('删除图片成功'); } -} +} \ No newline at end of file diff --git a/app/Controller/Common/AuthCommonController.php b/app/Controller/Common/AuthCommonController.php index 7746ede..77d4041 100644 --- a/app/Controller/Common/AuthCommonController.php +++ b/app/Controller/Common/AuthCommonController.php @@ -1,59 +1,50 @@ DrawCode(); + $result = $code->DrawCode(getRandStr(4)); $imageBase64Code = $result->getImageBase64(); $code = $result->getImageCode(); - $key = md5_rand(); - $container = ApplicationContext::getContainer(); - $redis = $container->get(\Hyperf\Redis\Redis::class); - $redis->setex($key, 60, $code); - - return $this->success([ - 'code' => $imageBase64Code, - 'code_key' => $key, - ]); + Redis::getInstance()->setex($key, 60, $code); + return $this->success(['code' => $imageBase64Code, 'code_key' => $key]); } - /** * 获取系统配置 - * @RequestMapping(path="sys_config", methods="get") * @return \Psr\Http\Message\ResponseInterface * @throws \Psr\SimpleCache\InvalidArgumentException */ + #[RequestMapping(path: 'sys_config', methods: array('GET'))] public function getSysConfig() { - $configList = GlobalConfig::query()->select('key_name', 'data') - ->where('type', GlobalConfig::TYPE_BY_BOOLEAN) - ->get()->toArray(); - + $configList = GlobalConfig::query()->select('key_name', 'data')->where('type', GlobalConfig::TYPE_BY_BOOLEAN)->get()->toArray(); $result = array_column($configList, 'key_name', 'data'); return $this->success($result); } -} +} \ No newline at end of file diff --git a/app/Controller/Common/CommonController.php b/app/Controller/Common/CommonController.php index 0643a2b..3a2f5c9 100644 --- a/app/Controller/Common/CommonController.php +++ b/app/Controller/Common/CommonController.php @@ -1,36 +1,31 @@ select('key_name', 'data') - ->where('type', GlobalConfig::TYPE_BY_BOOLEAN) - ->get()->toArray(); - + $configList = GlobalConfig::query()->select('key_name', 'data')->where('type', GlobalConfig::TYPE_BY_BOOLEAN)->get()->toArray(); $result = []; foreach ($configList as $item) { $result[$item['key_name']] = boolval($item['data']); } return $this->success($result); } -} +} \ No newline at end of file diff --git a/app/Controller/Common/ExcelExportController.php b/app/Controller/Common/ExcelExportController.php index a11a049..5fc6eb9 100644 --- a/app/Controller/Common/ExcelExportController.php +++ b/app/Controller/Common/ExcelExportController.php @@ -7,58 +7,62 @@ use Hyperf\HttpServer\Annotation\Controller; use Hyperf\HttpServer\Annotation\Middleware; use Hyperf\HttpServer\Annotation\RequestMapping; - - /** * Excel导出控制器 - * @Controller(prefix="excel") */ +#[Controller(prefix: 'excel')] class ExcelExportController extends AbstractController { /** * 获取Excel内容数据 - * @RequestMapping(path="excel_content", methods="post") - * @Middleware(RequestMiddleware::class) + * @Author YiYuan + * @Date 2023/12/1 + * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'excel_content', methods: array('POST'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function getExcelContent() { $requestParams = $this->request->all(); - $data = $requestParams['data'] ?? []; //数据模块 - $percentArr = $requestParams['percent_arr'] ?? []; //是否百分比的字段 - $tableHeader = $requestParams['table_header'] ?? []; //表头字段 - $tableHeaderMean = $requestParams['table_header_mean'] ?? []; //表头字段解释 - $stringArr = $requestParams['string_arr'] ?? []; // 需要以字符形式导出的字段(防止科学计数法格式) - $time = $requestParams['time'] ?? 'time'; //时间字段 - + $data = $requestParams['data'] ?? []; + //数据模块 + $percentArr = $requestParams['percent_arr'] ?? []; + //是否百分比的字段 + $tableHeader = $requestParams['table_header'] ?? []; + //表头字段 + $tableHeaderMean = $requestParams['table_header_mean'] ?? []; + //表头字段解释 + $stringArr = $requestParams['string_arr'] ?? []; + // 需要以字符形式导出的字段(防止科学计数法格式) + $time = $requestParams['time'] ?? 'time'; + //时间字段 $tableContent = ''; $tableContent .= ''; foreach ($tableHeader as $k => $v) { $tableContent .= ''; } $tableContent .= ''; - foreach($data as $k => $v) { + foreach ($data as $k => $v) { $tableContent .= ''; foreach ($tableHeader as $k1 => $v1) { //判断是否为时间戳格式 - if (($v1 == $time || preg_match('/_time/', $v1)) && is_numeric($v[$v1])) { + if (($v1 == $time || str_contains($v1, '_time')) && is_numeric($v[$v1])) { if (in_array($v1, $stringArr)) { - $tableContent .= ''; + $tableContent .= ''; } else { $tableContent .= ''; } - }else { + } else { if (in_array($v1, $stringArr)) { - $tableContent .= ''; + $tableContent .= ''; } else { - $tableContent .= ''; + $tableContent .= ''; } } } $tableContent .= ''; } $tableContent .= '
' . $tableHeaderMean[$v] . '
' . date('Y-m-d H:i:s', $v[$v1]) . '' . date('Y-m-d H:i:s', $v[$v1]) . '' . date('Y-m-d H:i:s', $v[$v1]) . '' . $v[$v1] . ((in_array($v1, $percentArr)) ? '%' : '') . '' . $v[$v1] . (in_array($v1, $percentArr) ? '%' : '') . '' . $v[$v1] . ((in_array($v1, $percentArr)) ? '%' : '') . '' . $v[$v1] . (in_array($v1, $percentArr) ? '%' : '') . '
'; - return $this->success([ - 'excel_content' => $tableContent - ]); + return $this->success(['excel_content' => $tableContent]); } -} +} \ No newline at end of file diff --git a/app/Controller/Common/HomeController.php b/app/Controller/Common/HomeController.php index f2badd5..703f498 100644 --- a/app/Controller/Common/HomeController.php +++ b/app/Controller/Common/HomeController.php @@ -1,7 +1,6 @@ getNoticeInfo(); $operateLogList = $this->getOperateLog(); - - return $this->success([ - 'notice_list' => $noticeList, - 'operate_log' => $operateLogList - ], '获取首页数据成功'); + return $this->success(['notice_list' => $noticeList, 'operate_log' => $operateLogList], '获取首页数据成功'); } /** @@ -47,10 +42,8 @@ private function getNoticeInfo() : array $noticeQuery->where('public_time', '<=', time()); $noticeQuery->where('status', Notice::ON_STATUS); $noticeQuery->orderBy('public_time', 'desc'); - $noticeQuery->select('title', 'content', 'public_time'); $list = $noticeQuery->get()->toArray(); - return $list; } @@ -65,22 +58,18 @@ private function getOperateLog() : array $operateLog->where('uid', conGet('user_info')['id']); $total = $operateLog->count(); $operateLog = $this->pagingCondition($operateLog, $this->request->all()); - $list = $operateLog->get()->toArray(); - - return [ - 'list' => $list, - 'total' => $total - ]; + return ['list' => $list, 'total' => $total]; } /** - * 获取地图数据 - * @RequestMapping(path="/world_map_data", methods="get,post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) + * 获取世界地图 + * @Author YiYuan + * @Date 2023/12/1 + * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: '/world_map_data')] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function getWorldMapData() { return $this->success($this->_getWorldMapData(), '获取地图数据成功'); diff --git a/app/Controller/Common/UploadController.php b/app/Controller/Common/UploadController.php index 3bc7fba..abc3c02 100644 --- a/app/Controller/Common/UploadController.php +++ b/app/Controller/Common/UploadController.php @@ -1,7 +1,6 @@ $this->request->input('savePath'), - 'file' => $this->request->file('file'), + 'file' => $this->request->file('file') ]; - //配置验证 $rules = [ 'savePath' => 'required', - 'file' => 'required |file|image', - ]; + 'file' => 'required |file|image']; $message = [ 'savePath.required' => '[savePath]缺失', 'file.required' => '[file]缺失', 'file.file' => '[file] 参数必须为文件类型', - 'file.image' => '[file] 文件必须是图片(jpeg、png、bmp、gif 或者 svg)', + 'file.image' => '[file] 文件必须是图片(jpeg、png、bmp、gif 或者 svg)' ]; $this->verifyParams($params, $rules, $message); - $uploadResult = UploadService::getInstance()->uploadSinglePic($this->request->file('file'), $params['savePath']); - return $this->success($uploadResult, '上传图片成功'); } /** - * 上传单张图片接口 - * @RequestMapping(path="single_pic_by_base64", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) + * 上传图片(base64) + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface - * @throws \League\Flysystem\FileExistsException */ + #[RequestMapping(path: 'single_pic_by_base64', methods: array('POST'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function uploadSinglePicByBase64() { $params = [ 'savePath' => $this->request->input('savePath'), - 'file' => $this->request->input('file'), + 'file' => $this->request->input('file') ]; - //配置验证 $rules = [ 'savePath' => 'required', - 'file' => 'required ', + 'file' => 'required ' ]; $message = [ 'savePath.required' => '[savePath]缺失', - 'file.required' => '[file]缺失', + 'file.required' => '[file]缺失' ]; $this->verifyParams($params, $rules, $message); - base64DecImg($params['file']); $uploadResult = UploadService::getInstance()->uploadSinglePicByBase64($params['file'], $params['savePath']); return $this->success($uploadResult); } /** - * 上传单张图片根据Blob文件类型 - * @RequestMapping(path="single_pic_by_blob", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) + * 上传图片(blog) + * @Author YiYuan + * @Date 2023/12/1 * @return \Psr\Http\Message\ResponseInterface - * @throws \League\Flysystem\FileExistsException */ + #[RequestMapping(path: 'single_pic_by_blob', methods: array('POST'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function uploadSinglePicByBlob() { $params = [ 'savePath' => $this->request->input('save_path'), - 'file' => $this->request->file('file'), + 'file' => $this->request->file('file') ]; - //配置验证 $rules = [ 'savePath' => 'required', - 'file' => 'required|file', + 'file' => 'required|file' ]; $message = [ 'savePath.required' => '[savePath]缺失', 'file.required' => '[file]缺失', - 'file.file' => '[file] 参数必须为文件类型', + 'file.file' => '[file] 参数必须为文件类型' ]; $this->verifyParams($params, $rules, $message); - $uploadResult = UploadService::getInstance()->uploadSinglePicByBlob($params['file'], $params['savePath']); return $this->success($uploadResult); } diff --git a/app/Controller/IndexController.php b/app/Controller/IndexController.php index 9b97cab..5fa18cc 100644 --- a/app/Controller/IndexController.php +++ b/app/Controller/IndexController.php @@ -1,77 +1,28 @@ queue->push(new EmailNotificationJob([ - 'title' => $params['title'], - 'content' => $params['content'], - ])); - -// $url = 'https://m.bilibili.com/video/BV1Q624y1q7sj'; - - -// $lastString = basename($url); -// $mid = explode('?', $lastString)[0] ?? ''; -// -// $upUser = new UpUser(); -// $upUser->mid = $mid; -// $upUser->timed_status = 1; -// $upUser->save(); -// return $upUser->mid; -// preg_match('/.*?av(\d{0,})\/?/', $url,$m); -// if (!isset($m[1])) { -// return false; -// } -// $vid = $m[1];//获取视频uid -// -// return $vid; - -// $infoUrl = 'https://api.bilibili.com/x/web-interface/archive/stat?aid='.$vid;//拼接得到接口地址 -// $infoRespose = doCurlGetRequest($infoUrl); -// -// $data = $this->bilibili($infoRespose);//获取视频抓取数据 -// $respose = file_get_contents("https://api.bilibili.com/x/web-interface/view?aid=".$vid); -// -// if (empty($respose) || !$respose) return false; -// $resposeData = json_decode($respose,true)['data']; -// -// $data['name'] = $resposeData['title']; -// $data['time'] = date('Y-m-d H:i:s',$resposeData['ctime']); -// $data['author'] = $resposeData['owner']['name']; -// -// return $data; - + { + $user = User::findById(985); + $user->assignRole('tourist_admin'); +// var_dump($user->assignRole('tourist_admin')); + return $this->successByMessage('测试成功'); } - -} +} \ No newline at end of file diff --git a/app/Controller/Laboratory/Bilibili/UpUserController.php b/app/Controller/Laboratory/Bilibili/UpUserController.php index a9c1279..40851d9 100644 --- a/app/Controller/Laboratory/Bilibili/UpUserController.php +++ b/app/Controller/Laboratory/Bilibili/UpUserController.php @@ -1,6 +1,6 @@ request->all()['up_user_info'] ?? []; @@ -72,8 +62,9 @@ public function upUserAdd() } $lastString = basename($upUserUrl); $mid = explode('?', $lastString)[0] ?? ''; - if (empty($mid)) continue; - + if (empty($mid)) { + continue; + } $upUser = new UpUser(); $upUser->mid = $mid; $upUser->timed_status = $timedStatus; @@ -81,162 +72,155 @@ public function upUserAdd() $addMidArr[] = $mid; } //推送一个队列,异步获取Up主信息 - $this->queue->push(new UpUserInfoRecordJob([ - 'up_user_mid' => $addMidArr, - ])); - - if ($isExistEmptyUrl) return $this->successByMessage('录入Up主成功,部分Url条目为空录入失败'); - + $this->queue->push(new UpUserInfoRecordJob(['up_user_mid' => $addMidArr])); + if ($isExistEmptyUrl) { + return $this->successByMessage('录入Up主成功,部分Url条目为空录入失败'); + } return $this->successByMessage('录入Up主成功'); } /** - * 获取Up用户搜索列表 - * @RequestMapping(path="up_user_search", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) + * Up主搜索 + * @Author YiYuan + * @Date 2023/12/4 * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'up_user_search', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function upUserSearchList() { $mid = $this->request->input('mid') ?? ''; $upUserQuery = $this->upUser->newQuery(); if (!empty($mid)) $upUserQuery->where('mid', $mid); - $list = $upUserQuery->limit(10)->orderBy('created_at')->get()->toArray(); foreach ($list as $key => $value) { $list[$key]['name'] = $value['name'] . '(' . $value['mid'] . ')'; } - return $this->success([ - 'list' => $list, - ]); + return $this->success(['list' => $list]); } /** - * 获取Up用户列表 - * @RequestMapping(path="up_user", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * Up主列表 + * @Author YiYuan + * @Date 2023/12/4 * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'up_user', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function upUserList() { $mid = $this->request->input('mid') ?? ''; - $name = $this->request->input('name') ?? ''; - $timedStatus = $this->request->input('time_status') ?? ''; - + $name = $this->request->input('name') ?? ''; + $timedStatus = $this->request->input('time_status') ?? ''; $upUserQuery = $this->upUser->newQuery(); - if (!empty($mid)) $upUserQuery->where('mid', $mid); - if (!empty($name)) $upUserQuery->where('name', 'like', '%' . $name . '%'); - if (strlen($timedStatus) > 0) $upUserQuery->where('timed_status', $timedStatus); - + if (!empty($mid)) { + $upUserQuery->where('mid', $mid); + } + if (!empty($name)) { + $upUserQuery->where('name', 'like', '%' . $name . '%'); + } + if (strlen($timedStatus) > 0) { + $upUserQuery->where('timed_status', $timedStatus); + } $total = $upUserQuery->count(); $this->pagingCondition($upUserQuery, $this->request->all()); $list = $upUserQuery->orderBy('created_at', 'desc')->get()->toArray(); - - return $this->success([ - 'list' => $list, - 'total' => $total - ]); + return $this->success(['list' => $list, 'total' => $total]); } /** - * 获取Up用户列表 - * @RequestMapping(path="sync_video_from_up_user", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 从Up主同步视频 + * @Author YiYuan + * @Date 2023/12/4 * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '从Up主同步视频')] + #[RequestMapping(path: 'sync_video_from_up_user', methods: array('POST'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function syncVideoReportFromUpUser() { $mid = $this->request->input('mid') ?? ''; - if (empty($mid)) $this->throwExp(StatusCode::ERR_VALIDATION, '参数错误'); - + if (empty($mid)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '参数错误'); + } $upUser = $this->upUser->newQuery()->where('mid', $mid)->first(); - if (empty($upUser)) $this->throwExp(StatusCode::ERR_EXCEPTION, '查询不到该Up主'); - + if (empty($upUser)) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '查询不到该Up主'); + } //推送一个队列,同步Up主视频信息 - $this->queue->push(new SyncVideoFromUpUserJob([ - 'mid' => $mid, - ])); - + $this->queue->push(new SyncVideoFromUpUserJob(['mid' => $mid])); return $this->successByMessage('正在同步视频中。。。请稍后转至视频列表查看'); } /** - * up主图表趋势 - * @RequestMapping(path="up_user_chart_trend", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * Up主数据趋势 + * @Author YiYuan + * @Date 2023/12/4 * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'up_user_chart_trend', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function upUserChartTrend() { $mid = $this->request->input('mid') ?? ''; $date = $this->request->input('date') ?? ''; - $upUserReportQuery = $this->upUserReport->newQuery(); - if (empty($mid)) $this->throwExp(StatusCode::ERR_VALIDATION, '请填写搜索UP主mid'); - if (!empty($mid)) $upUserReportQuery->where('mid', $mid); + if (empty($mid)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '请填写搜索UP主mid'); + } + if (!empty($mid)) { + $upUserReportQuery->where('mid', $mid); + } // 处理时间 $date = $date ?? [date('Y-m-d', strtotime('-6 days')), date('Y-m-d', time())]; $beginTime = strtotime($date[0]); $endTime = strtotime($date[1]); $range = getRangeBetweenTime($beginTime, $endTime); - if ($range > 7) $this->throwExp(StatusCode::ERR_EXCEPTION, '时间范围不能超过7天'); + if ($range > 7) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '时间范围不能超过7天'); + } $timestampList = []; for ($i = $beginTime; $i < $endTime; $i = $i + 3600) { $timestampList[] = $i; } $upUserReportQuery->where('time', '>=', $beginTime); $upUserReportQuery->where('time', '<=', $endTime); - $rows = UpUserService::getInstance()->upUserChartTrend($upUserReportQuery, $timestampList); - - return $this->success([ - 'rows' => $rows, - ]); + return $this->success(['rows' => $rows]); } /** - * up主图表趋势 - * @RequestMapping(path="up_user_data_report", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * Up主日常数据报表 + * @Author YiYuan + * @Date 2023/12/4 * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'up_user_data_report', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function upUserDataReport() { $mid = $this->request->input('mid') ?? ''; $date = $this->request->input('date') ?? ''; - $upUserReportQuery = $this->upUserReport->newQuery(); - if (empty($mid)) $this->throwExp(StatusCode::ERR_VALIDATION, '请填写搜索UP主mid'); - if (!empty($mid)) $upUserReportQuery->where('mid', $mid); + if (empty($mid)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '请填写搜索UP主mid'); + } + if (!empty($mid)) { + $upUserReportQuery->where('mid', $mid); + } // 处理时间 $date = empty($date) ? [date('Y-m-d', time()), date('Y-m-d', time())] : $date; $beginTime = strtotime($date[0]); $endTime = strtotime($date[1]) + 86400; - $upUserReportQuery->where('time', '>=', $beginTime); $upUserReportQuery->where('time', '<=', $endTime); - $total = $upUserReportQuery->count(); $upUserReportQuery = $this->pagingCondition($upUserReportQuery, $this->request->all()); - $list = UpUserService::getInstance()->upUserDataReport($upUserReportQuery); - return $this->success([ - 'list' => $list, - 'total' => $total, - ]); + return $this->success(['list' => $list, 'total' => $total]); } -} +} \ No newline at end of file diff --git a/app/Controller/Laboratory/Bilibili/VideoController.php b/app/Controller/Laboratory/Bilibili/VideoController.php index 0e03d9d..de84ca6 100644 --- a/app/Controller/Laboratory/Bilibili/VideoController.php +++ b/app/Controller/Laboratory/Bilibili/VideoController.php @@ -1,6 +1,6 @@ request->all()['video_info'] ?? []; if (empty($videoInfo)) $this->throwExp(StatusCode::ERR_VALIDATION, '视频链接信息不能为空'); - //是否存在空的URL $isExistEmptyUrl = false; $addBVidArr = []; @@ -72,8 +61,9 @@ public function videoAdd() } $lastString = basename($videoUrl); $bvid = explode('?', $lastString)[0] ?? ''; - if (empty($bvid)) continue; - + if (empty($bvid)) { + continue; + } $video = new Video(); $video->bvid = $bvid; $video->timed_status = $timedStatus; @@ -81,146 +71,138 @@ public function videoAdd() $addBVidArr[] = $bvid; } //推送一个队列,异步获取Up主信息 - $this->queue->push(new VideoInfoRecordJob([ - 'video_bvid' => $addBVidArr, - ])); - - if ($isExistEmptyUrl) return $this->successByMessage('录入视频成功,部分Url条目为空录入失败'); - + $this->queue->push(new VideoInfoRecordJob(['video_bvid' => $addBVidArr])); + if ($isExistEmptyUrl) { + return $this->successByMessage('录入视频成功,部分Url条目为空录入失败'); + } return $this->successByMessage('录入视频成功'); } /** - * 获取视频标题搜索列表 - * @RequestMapping(path="video_title_search", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) + * 视频标题搜索 + * @Author YiYuan + * @Date 2023/12/4 * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'video_title_search', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function videoTitleSearch() { $bvid = $this->request->input('bvid') ?? ''; $videoQuery = $this->video->newQuery(); - if (!empty($bvid)) $videoQuery->where('bvid', $bvid); - + if (!empty($bvid)) { + $videoQuery->where('bvid', $bvid); + } $list = $videoQuery->limit(10)->orderBy('public_time', 'desc')->get()->toArray(); foreach ($list as $key => $value) { $list[$key]['title'] = $value['title'] . '(' . $value['bvid'] . ')'; } - return $this->success([ - 'list' => $list, - ]); + return $this->success(['list' => $list]); } /** - * 获取Up用户列表 - * @RequestMapping(path="video", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 视频列表 + * @Author YiYuan + * @Date 2023/12/4 * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'video', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function videoList() { $bvid = $this->request->input('bvid') ?? ''; - $mid = $this->request->input('mid') ?? ''; - $title = $this->request->input('title') ?? ''; + $mid = $this->request->input('mid') ?? ''; + $title = $this->request->input('title') ?? ''; $publicTime = $this->request->input('public_time') ?? ''; - $videoQuery = $this->video->newQuery(); - if (!empty($bvid)) $videoQuery->where('bvid', $mid); - if (!empty($mid)) $videoQuery->where('mid', $mid); - if (!empty($publicTime)) $videoQuery->whereBetween('public_time', [strtotime($publicTime[0]), strtotime($publicTime[1])]); - if (!empty($title)) $videoQuery->where('title', 'like', '%' . $title . '%'); - + if (!empty($bvid)) { + $videoQuery->where('bvid', $mid); + } + if (!empty($mid)) { + $videoQuery->where('mid', $mid); + } + if (!empty($publicTime)) { + $videoQuery->whereBetween('public_time', [strtotime($publicTime[0]), strtotime($publicTime[1])]); + } + if (!empty($title)) { + $videoQuery->where('title', 'like', '%' . $title . '%'); + } $total = $videoQuery->count(); $this->pagingCondition($videoQuery, $this->request->all()); $list = $videoQuery->orderBy('created_at', 'desc')->get()->toArray(); - foreach ($list as $key => $value) { $list[$key]['public_time'] = date('Y-m-d H:i:s', $value['public_time']); $owner = json_decode($value['owner'], true); $list[$key]['name'] = $owner['name']; - $list[$key]['duration'] = floor ($value['duration'] / 60) . '分' . $value['duration'] % 60 . '秒'; + $list[$key]['duration'] = floor($value['duration'] / 60) . '分' . $value['duration'] % 60 . '秒'; } - - return $this->success([ - 'list' => $list, - 'total' => $total - ]); + return $this->success(['list' => $list, 'total' => $total]); } /** - * up主图表趋势 - * @RequestMapping(path="video_chart_trend", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 视频趋势图表 + * @Author YiYuan + * @Date 2023/12/4 * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'video_chart_trend', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function videoChartTrend() { $bvid = $this->request->input('bvid') ?? ''; $date = $this->request->input('date') ?? ''; - $videoReportQuery = $this->videoReport->newQuery(); - if (empty($bvid)) $this->throwExp(StatusCode::ERR_VALIDATION, '请填写搜索视频ID'); + if (empty($bvid)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '请填写搜索视频ID'); + } $videoReportQuery->where('bvid', $bvid); // 处理时间 $date = $date ?? [date('Y-m-d', strtotime('-6 days')), date('Y-m-d', time())]; $beginTime = strtotime($date[0]); $endTime = strtotime($date[1]); $range = getRangeBetweenTime($beginTime, $endTime); - if ($range > 7) $this->throwExp(StatusCode::ERR_EXCEPTION, '时间范围不能超过7天'); + if ($range > 7) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '时间范围不能超过7天'); + } $timestampList = []; for ($i = $beginTime; $i < $endTime; $i = $i + 3600) { $timestampList[] = $i; } $videoReportQuery->where('time', '>=', $beginTime); $videoReportQuery->where('time', '<=', $endTime); - $rows = VideoService::getInstance()->videoChartTrend($videoReportQuery, $timestampList); - - return $this->success([ - 'rows' => $rows, - ]); + return $this->success(['rows' => $rows]); } /** - * up主图表趋势 - * @RequestMapping(path="video_data_report", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * Up视频数据报表 + * @Author YiYuan + * @Date 2023/12/4 * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'video_data_report', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function upUserDataReport() { $bvid = $this->request->input('bvid') ?? ''; $date = $this->request->input('date') ?? ''; - $videoReportQuery = $this->videoReport->newQuery(); - if (empty($bvid)) $this->throwExp(StatusCode::ERR_VALIDATION, '请填写视频ID'); + if (empty($bvid)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '请填写视频ID'); + } $videoReportQuery->where('bvid', $bvid); // 处理时间 $date = empty($date) ? [date('Y-m-d', time()), date('Y-m-d', time())] : $date; $beginTime = strtotime($date[0]); $endTime = strtotime($date[1]) + 86400; - $videoReportQuery->where('time', '>=', $beginTime); $videoReportQuery->where('time', '<=', $endTime); - $total = $videoReportQuery->count(); $videoReportQuery = $this->pagingCondition($videoReportQuery, $this->request->all()); - $list = VideoService::getInstance()->videoDataReport($videoReportQuery); - return $this->success([ - 'list' => $list, - 'total' => $total, - ]); + return $this->success(['list' => $list, 'total' => $total]); } -} +} \ No newline at end of file diff --git a/app/Controller/Laboratory/FriendController.php b/app/Controller/Laboratory/FriendController.php index 8d9db41..4c85fea 100644 --- a/app/Controller/Laboratory/FriendController.php +++ b/app/Controller/Laboratory/FriendController.php @@ -1,6 +1,6 @@ request->query('contact_id') ?? ''; - if (empty($contactId)) $this->throwExp(StatusCode::ERR_VALIDATION, 'ID参数不允许为空'); + if (empty($contactId)) { + $this->throwExp(StatusCode::ERR_VALIDATION, 'ID参数不允许为空'); + } $userInfo = conGet('user_info'); - $messageQuery = FriendChatHistory::query() - ->where(function ($query) use ($userInfo, $contactId) { - $query->where('from_uid', $userInfo['id'])->where('to_uid', $contactId); - if (!empty($this->request->query('date'))) { - $beginTime = $this->request->query('date'); - $endTime = $this->request->query('date') + 86400000; - $query->whereBetween('send_time', [$beginTime, $endTime]); - } - if(!empty($this->request->query('content'))) { - $query->where('content', 'like', '%' . $this->request->query('content') . '%'); - } - })->orWhere(function ($query) use ($userInfo, $contactId) { - $query->where('from_uid', $contactId)->where('to_uid', $userInfo['id']); - if (!empty($this->request->query('date'))) { - $beginTime = $this->request->query('date'); - $endTime = $this->request->query('date') + 86400000; - $query->whereBetween('send_time', [$beginTime, $endTime]); - } - if(!empty($this->request->query('content'))) { - $query->where('content', 'like', '%' . $this->request->query('content') . '%'); - } - }); - + $messageQuery = FriendChatHistory::query()->where(function ($query) use($userInfo, $contactId) { + $query->where('from_uid', $userInfo['id'])->where('to_uid', $contactId); + if (!empty($this->request->query('date'))) { + $beginTime = $this->request->query('date'); + $endTime = $this->request->query('date') + 86400000; + $query->whereBetween('send_time', [$beginTime, $endTime]); + } + if (!empty($this->request->query('content'))) { + $query->where('content', 'like', '%' . $this->request->query('content') . '%'); + } + })->orWhere(function ($query) use($userInfo, $contactId) { + $query->where('from_uid', $contactId)->where('to_uid', $userInfo['id']); + if (!empty($this->request->query('date'))) { + $beginTime = $this->request->query('date'); + $endTime = $this->request->query('date') + 86400000; + $query->whereBetween('send_time', [$beginTime, $endTime]); + } + if (!empty($this->request->query('content'))) { + $query->where('content', 'like', '%' . $this->request->query('content') . '%'); + } + }); $total = $messageQuery->count(); $messageQuery = $this->pagingCondition($messageQuery, $this->request->all()); $messageList = $messageQuery->orderBy('send_time', 'desc')->get()->toArray(); - $list = []; foreach ($messageList as $key => $value) { $sendTime = intval($value['send_time'] / 1000); @@ -69,32 +66,15 @@ public function historyMessage() $user = User::query()->select('id', 'desc', 'avatar')->where('id', $value['from_uid'])->first(); $displayName = $user['desc']; $friendRemark = FriendRelation::query()->where('uid', $value['to_uid'])->where('friend_id', $value['from_uid'])->value('friend_remark'); - if (!empty($friendRemark) && $value['from_uid'] != $userInfo['id']) $displayName = $friendRemark; - - $temp = [ - 'id' => $value['message_id'], - 'status' => $value['status'], - 'type' => $value['type'], - 'fileSize' => $value['file_size'], - 'fileName' => $value['file_name'], - 'fileExt' => $value['file_ext'], - 'sendTime' => date('Y-m-d', $sendTime) == date('Y-m-d') ? date('H:i:s', $sendTime) : date('Y-m-d, H:i:s', $sendTime) , - 'content' => $value['content'], - 'avatar' => $user['avatar'], - 'displayName' => $displayName, - 'fromUser' => [ - 'id' => $user['id'], - 'avatar' => $user['avatar'] ?? '', - 'displayName' => $displayName, - ], - ]; - if ($temp['type'] == FriendChatHistory::FRIEND_CHAT_MESSAGE_TYPE_FORWARD) + if (!empty($friendRemark) && $value['from_uid'] != $userInfo['id']) { + $displayName = $friendRemark; + } + $temp = ['id' => $value['message_id'], 'status' => $value['status'], 'type' => $value['type'], 'fileSize' => $value['file_size'], 'fileName' => $value['file_name'], 'fileExt' => $value['file_ext'], 'sendTime' => date('Y-m-d', $sendTime) == date('Y-m-d') ? date('H:i:s', $sendTime) : date('Y-m-d, H:i:s', $sendTime), 'content' => $value['content'], 'avatar' => $user['avatar'], 'displayName' => $displayName, 'fromUser' => ['id' => $user['id'], 'avatar' => $user['avatar'] ?? '', 'displayName' => $displayName]]; + if ($temp['type'] == FriendChatHistory::FRIEND_CHAT_MESSAGE_TYPE_FORWARD) { $temp['content'] = MessageService::getInstance()->formatForwardMessage($temp['content'], $temp['fromUser']); + } $list[] = $temp; } - return $this->success([ - 'list' => $list, - 'total' => $total - ]); + return $this->success(['list' => $list, 'total' => $total]); } -} +} \ No newline at end of file diff --git a/app/Controller/Laboratory/GroupController.php b/app/Controller/Laboratory/GroupController.php index e052d80..9c81e12 100644 --- a/app/Controller/Laboratory/GroupController.php +++ b/app/Controller/Laboratory/GroupController.php @@ -1,6 +1,6 @@ request->query('contact_id') ?? ''; $uid = conGet('user_info')['id']; $joinGroupTime = GroupRelation::getJoinDateById($uid, $contactId); - if (empty($contactId)) $this->throwExp(StatusCode::ERR_VALIDATION, 'ID参数不允许为空'); - $messageQuery = GroupChatHistory::query() - ->where('to_group_id', $contactId) - ->where('type', '!=', GroupChatHistory::GROUP_CHAT_MESSAGE_TYPE_EVENT) - ->where('created_at', '>=', $joinGroupTime); - + if (empty($contactId)) { + $this->throwExp(StatusCode::ERR_VALIDATION, 'ID参数不允许为空'); + } + $messageQuery = GroupChatHistory::query()->where('to_group_id', $contactId)->where('type', '!=', GroupChatHistory::GROUP_CHAT_MESSAGE_TYPE_EVENT)->where('created_at', '>=', $joinGroupTime); if (!empty($this->request->query('date'))) { $beginTime = $this->request->query('date'); $endTime = $this->request->query('date') + 86400000; $messageQuery->whereBetween('send_time', [$beginTime, $endTime]); } - if(!empty($this->request->query('content'))) { + if (!empty($this->request->query('content'))) { $messageQuery->where('content', 'like', '%' . $this->request->query('content') . '%'); } - $total = $messageQuery->count(); $messageQuery = $this->pagingCondition($messageQuery, $this->request->all()); $messageList = $messageQuery->orderBy('send_time', 'desc')->get()->toArray(); - $list = []; foreach ($messageList as $key => $value) { $sendTime = intval($value['send_time'] / 1000); - $list[] = [ - 'id' => $value['message_id'], - 'status' => $value['status'], - 'type' => $value['type'], - 'fileSize' => $value['file_size'], - 'fileName' => $value['file_name'], - 'sendTime' => date('Y-m-d', $sendTime) == date('Y-m-d') ? date('H:i:s', $sendTime) : date('Y-m-d, H:i:s', $sendTime) , - 'content' => $value['content'], - 'avatar' => User::query()->where('id', $value['from_uid'])->value('avatar'), - 'displayName' => User::query()->where('id', $value['from_uid'])->value('desc'), - ]; + $list[] = ['id' => $value['message_id'], 'status' => $value['status'], 'type' => $value['type'], 'fileSize' => $value['file_size'], 'fileName' => $value['file_name'], 'sendTime' => date('Y-m-d', $sendTime) == date('Y-m-d') ? date('H:i:s', $sendTime) : date('Y-m-d, H:i:s', $sendTime), 'content' => $value['content'], 'avatar' => User::query()->where('id', $value['from_uid'])->value('avatar'), 'displayName' => User::query()->where('id', $value['from_uid'])->value('desc')]; } - return $this->success([ - 'list' => $list, - 'total' => $total - ]); + return $this->success(['list' => $list, 'total' => $total]); } /** - * 获取群文件 - * @RequestMapping(path="group_file", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) + * 组文件 + * @Author YiYuan + * @Date 2023/12/22 + * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'group_file', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function groupFile() { $contactId = $this->request->query('contact_id') ?? ''; - if (empty($contactId)) $this->throwExp(StatusCode::ERR_VALIDATION, '群ID参数不允许为空'); + if (empty($contactId)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '群ID参数不允许为空'); + } $groupFileQuery = GroupChatHistory::query()->where('to_group_id', $contactId)->where('type', GroupChatHistory::GROUP_CHAT_MESSAGE_TYPE_FILE); if (!empty($this->request->query('date'))) { $beginTime = $this->request->query('date'); $endTime = $this->request->query('date') + 86400000; $groupFileQuery->whereBetween('send_time', [$beginTime, $endTime]); } - if(!empty($this->request->query('file_name'))) { + if (!empty($this->request->query('file_name'))) { $groupFileQuery->where('file_name', 'like', '%' . $this->request->query('file_name') . '%'); } - $groupFileQuery = $groupFileQuery->with("getFromUser:id,desc"); $total = $groupFileQuery->count(); $groupFileQuery = $this->pagingCondition($groupFileQuery, $this->request->all()); $groupFileList = $groupFileQuery->orderBy('send_time', 'desc')->get()->toArray(); - - return $this->success([ - 'list' => $groupFileList, - 'total' => $total - ]); + return $this->success(['list' => $groupFileList, 'total' => $total]); } /** - * 获取群照片 - * @RequestMapping(path="group_album", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) + * 组相册 + * @Author YiYuan + * @Date 2023/12/22 + * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'group_album', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function groupAlbum() { $contactId = $this->request->query('contact_id') ?? ''; - if (empty($contactId)) $this->throwExp(StatusCode::ERR_VALIDATION, '群ID参数不允许为空'); + if (empty($contactId)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '群ID参数不允许为空'); + } $groupFileQuery = GroupChatHistory::query()->where('to_group_id', $contactId)->where('type', GroupChatHistory::GROUP_CHAT_MESSAGE_TYPE_IMAGE); if (!empty($this->request->query('date'))) { $beginTime = $this->request->query('date'); $endTime = $this->request->query('date') + 86400000; $groupFileQuery->whereBetween('send_time', [$beginTime, $endTime]); } - if(!empty($this->request->query('file_name'))) { + if (!empty($this->request->query('file_name'))) { $groupFileQuery->where('file_name', 'like', '%' . $this->request->query('file_name') . '%'); } $groupFileQuery = $groupFileQuery->with("getFromUser:id,desc,avatar"); $total = $groupFileQuery->count(); $groupFileQuery = $this->pagingCondition($groupFileQuery, $this->request->all()); $groupFileList = $groupFileQuery->orderBy('send_time', 'desc')->get()->toArray(); - - return $this->success([ - 'list' => $groupFileList, - 'srcList' => array_column($groupFileList, 'content'), - 'total' => $total - ]); + return $this->success(['list' => $groupFileList, 'srcList' => array_column($groupFileList, 'content'), 'total' => $total]); } /** - * 获取群邀请 - * @RequestMapping(path="group_invite", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) + * 组邀请 + * @Author YiYuan + * @Date 2023/12/22 + * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'group_invite', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function groupInvite() { $contactId = $this->request->query('contact_id') ?? ''; - if (empty($contactId)) $this->throwExp(StatusCode::ERR_VALIDATION, '群ID参数不允许为空'); - if (empty($groupInfo = Group::findById($contactId))) $this->throwExp(StatusCode::ERR_EXCEPTION, '该组不存在'); - + if (empty($contactId)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '群ID参数不允许为空'); + } + if (empty($groupInfo = Group::findById($contactId))) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '该组不存在'); + } $groupMemberUidList = GroupRelation::query()->where('group_id', $contactId)->pluck('uid'); $groupMemberList = User::query()->select('id', 'desc', 'avatar')->whereIn('id', $groupMemberUidList)->get()->toArray(); $contactsSource = User::query()->select('id', 'desc', 'avatar')->whereNotIn('id', $groupMemberUidList)->get()->toArray(); - - return $this->success([ - 'group_member_list' => $groupMemberList, - 'contacts_source' => $contactsSource, - ]); + return $this->success(['group_member_list' => $groupMemberList, 'contacts_source' => $contactsSource]); } /** - * 获取群员管理列表 - * @RequestMapping(path="group_member_manage", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) + * 组员管理 + * @Author YiYuan + * @Date 2023/12/22 + * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'group_member_manage', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function groupMemberManage() { $contactId = $this->request->query('contact_id') ?? ''; - if (empty($contactId)) $this->throwExp(StatusCode::ERR_VALIDATION, '群ID参数不允许为空'); - if (empty($groupInfo = Group::findById($contactId))) $this->throwExp(StatusCode::ERR_EXCEPTION, '该组不存在'); - + if (empty($contactId)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '群ID参数不允许为空'); + } + if (empty(Group::findById($contactId))) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '该组不存在'); + } $groupMemberQuery = (new GroupRelation())->setTable('a')->from('ct_group_relation as a')->where('a.group_id', $contactId); $groupMemberQuery = $groupMemberQuery->leftJoin('users as b', 'a.uid', '=', 'b.id'); $groupMemberQuery = $groupMemberQuery->select('a.*', 'b.id', 'b.desc', 'b.avatar'); - - if (!empty($this->request->query('desc'))) $groupMemberQuery->where('b.desc', 'like', '%' . $this->request->query('desc') . '%'); + if (!empty($this->request->query('desc'))) { + $groupMemberQuery->where('b.desc', 'like', '%' . $this->request->query('desc') . '%'); + } $total = $groupMemberQuery->count(); $groupMemberQuery = $this->pagingCondition($groupMemberQuery, $this->request->all()); $groupMemberList = $groupMemberQuery->orderBy('level', 'asc')->get()->toArray(); - - return $this->success([ - 'list' => $groupMemberList, - 'total' => $total, - ]); + return $this->success(['list' => $groupMemberList, 'total' => $total]); } -} +} \ No newline at end of file diff --git a/app/Controller/Laboratory/UploadController.php b/app/Controller/Laboratory/UploadController.php index a7064e7..fa096f1 100644 --- a/app/Controller/Laboratory/UploadController.php +++ b/app/Controller/Laboratory/UploadController.php @@ -1,49 +1,35 @@ $this->request->input('savePath'), - 'file' => $this->request->input('file'), - ]; + $params = ['savePath' => $this->request->input('savePath'), 'file' => $this->request->input('file')]; //配置验证 - $rules = [ - 'savePath' => 'required', - 'file' => 'required ', - ]; - $message = [ - 'savePath.required' => '[savePath]缺失', - 'file.required' => '[file]缺失', - ]; + $rules = ['savePath' => 'required', 'file' => 'required ']; + $message = ['savePath.required' => '[savePath]缺失', 'file.required' => '[file]缺失']; $this->verifyParams($params, $rules, $message); - base64DecImg($params['file']); $uploadResult = UploadService::getInstance()->uploadSinglePicByBase64($params['file'], $params['savePath']); return $this->success($uploadResult); @@ -51,103 +37,57 @@ public function uploadPicByBase64() /** * 上传图片 - * @RequestMapping(path="upload_pic", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) + * @Author YiYuan + * @Date 2023/12/22 * @return \Psr\Http\Message\ResponseInterface - * @throws \League\Flysystem\FileExistsException */ + #[RequestMapping(path: 'upload_pic', methods: array('POST'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function uploadPic() { - $params = [ - 'savePath' => $this->request->input('savePath') ?? '', - 'file' => $this->request->file('file'), - 'messageId' => $this->request->input('messageId') ?? '' - ]; + $params = ['savePath' => $this->request->input('savePath') ?? '', 'file' => $this->request->file('file'), 'messageId' => $this->request->input('messageId') ?? '']; //配置验证 - $rules = [ - 'savePath' => 'required', - 'file' => 'required|file|image', - 'messageId' => 'required ', - ]; - $message = [ - 'savePath.required' => '[savePath]缺失', - 'file.required' => '[file]缺失', - 'file.file' => '[file] 参数必须为文件类型', - 'file.image' => '[file] 文件必须是图片(jpeg、png、bmp、gif 或者 svg)', - 'messageId.required' => '[messageId]缺失', - ]; + $rules = ['savePath' => 'required', 'file' => 'required|file|image', 'messageId' => 'required ']; + $message = ['savePath.required' => '[savePath]缺失', 'file.required' => '[file]缺失', 'file.file' => '[file] 参数必须为文件类型', 'file.image' => '[file] 文件必须是图片(jpeg、png、bmp、gif 或者 svg)', 'messageId.required' => '[messageId]缺失']; $this->verifyParams($params, $rules, $message); - $uploadResult = UploadService::getInstance()->uploadPic($params['file'], $params['savePath'], $params['messageId']); return $this->success($uploadResult); } /** * 上传文件 - * @RequestMapping(path="upload_file", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) + * @Author YiYuan + * @Date 2023/12/22 * @return \Psr\Http\Message\ResponseInterface - * @throws \League\Flysystem\FileExistsException */ + #[RequestMapping(path: 'upload_file', methods: array('POST'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function uploadFile() { - $params = [ - 'savePath' => $this->request->input('savePath') ?? '', - 'file' => $this->request->file('file'), - 'messageId' => $this->request->input('messageId') ?? '' - ]; + $params = ['savePath' => $this->request->input('savePath') ?? '', 'file' => $this->request->file('file'), 'messageId' => $this->request->input('messageId') ?? '']; //配置验证 - $rules = [ - 'savePath' => 'required', - 'file' => 'required|file', - 'messageId' => 'required ', - ]; - $message = [ - 'savePath.required' => '[savePath]缺失', - 'file.required' => '[file]缺失', - 'file.file' => '[file] 参数必须为文件类型', - 'messageId.required' => '[messageId]缺失', - ]; + $rules = ['savePath' => 'required', 'file' => 'required|file', 'messageId' => 'required ']; + $message = ['savePath.required' => '[savePath]缺失', 'file.required' => '[file]缺失', 'file.file' => '[file] 参数必须为文件类型', 'messageId.required' => '[messageId]缺失']; $this->verifyParams($params, $rules, $message); - $uploadResult = UploadService::getInstance()->uploadFile($params['file'], $params['savePath'], $params['messageId']); return $this->success($uploadResult); } /** - * 上传文件 - * @RequestMapping(path="upload_video", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) + * 上传视频 + * @Author YiYuan + * @Date 2023/12/22 * @return \Psr\Http\Message\ResponseInterface - * @throws \League\Flysystem\FileExistsException */ + #[RequestMapping(path: 'upload_video', methods: array('POST'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function uploadVideo() { - $params = [ - 'savePath' => $this->request->input('savePath') ?? '', - 'file' => $this->request->file('file'), - 'messageId' => $this->request->input('messageId') ?? '' - ]; + $params = ['savePath' => $this->request->input('savePath') ?? '', 'file' => $this->request->file('file'), 'messageId' => $this->request->input('messageId') ?? '']; //配置验证 - $rules = [ - 'savePath' => 'required', - 'file' => 'required|file', - 'messageId' => 'required ', - ]; - $message = [ - 'savePath.required' => '[savePath]缺失', - 'file.required' => '[file]缺失', - 'messageId.required' => '[messageId]缺失', - 'file.file' => '[file] 参数必须为文件类型', - ]; + $rules = ['savePath' => 'required', 'file' => 'required|file', 'messageId' => 'required ']; + $message = ['savePath.required' => '[savePath]缺失', 'file.required' => '[file]缺失', 'messageId.required' => '[messageId]缺失', 'file.file' => '[file] 参数必须为文件类型']; $this->verifyParams($params, $rules, $message); - $uploadResult = UploadService::getInstance()->uploadVideo($params['file'], $params['savePath'], $params['messageId']); return $this->success($uploadResult); } diff --git a/app/Controller/Laboratory/Ws/FriendController.php b/app/Controller/Laboratory/Ws/FriendController.php index 6c0366f..43247d6 100644 --- a/app/Controller/Laboratory/Ws/FriendController.php +++ b/app/Controller/Laboratory/Ws/FriendController.php @@ -1,6 +1,6 @@ hget(ChatRedisKey::ONLINE_USER_FD_KEY, (string)$contactData['toContactId']); + $contactId = Redis::getInstance()->hget(ChatRedisKey::ONLINE_USER_FD_KEY, (string) $contactData['toContactId']); $receptionState = empty($contactId) ? FriendChatHistory::RECEPTION_STATE_NO : FriendChatHistory::RECEPTION_STATE_YES; - if (!empty($name = FriendRelation::getFriendRemarkNameById($contactData['fromUser']['id'], $contactData['toContactId']))) $contactData['fromUser']['displayName'] = $name; - + if (!empty($name = FriendRelation::getFriendRemarkNameById($contactData['fromUser']['id'], $contactData['toContactId']))) { + $contactData['fromUser']['displayName'] = $name; + } //添加聊天记录 FriendChatHistory::addMessage($contactData, $receptionState); $contactData['status'] = FriendChatHistory::FRIEND_CHAT_MESSAGE_STATUS_SUCCEED; $contactData['toContactId'] = $contactData['fromUser']['id']; - unset($contactData['fromUser']['unread']); unset($contactData['fromUser']['lastSendTime']); unset($contactData['fromUser']['lastContent']); - return [ - 'message_data' => [ - 'message' => [ - 'id' => $contactData['id'], - 'status' => $contactData['status'], - 'type' => $contactData['type'], - 'sendTime' => $contactData['sendTime'], - 'content' => $contactData['content'], - 'toContactId' => $contactData['fromUser']['id'], - 'fromUser' => $contactData['fromUser'], - 'isGroup' => false, - ], - 'event' => '' - ], - 'fd' => $contactId - ]; + return ['message_data' => ['message' => ['id' => $contactData['id'], 'status' => $contactData['status'], 'type' => $contactData['type'], 'sendTime' => $contactData['sendTime'], 'content' => $contactData['content'], 'toContactId' => $contactData['fromUser']['id'], 'fromUser' => $contactData['fromUser'], 'isGroup' => false], 'event' => ''], 'fd' => $contactId]; } /** * 拉取信息 - * @RequestMapping(path="pull_message",methods="GET") */ + #[RequestMapping(path: 'pull_message', methods: array('GET'))] public function pullMessage() { $chatMessage = MessageParser::decode(conGet('chat_message')); $contactData = $chatMessage['message']; $userFd = Redis::getInstance()->hget(ChatRedisKey::ONLINE_USER_FD_KEY, (string) $contactData['user_id']); - - $messageList = FriendChatHistory::query() - ->where(function ($query) use ($contactData) { - $query->where('from_uid', $contactData['user_id'])->where('to_uid', $contactData['contact_id']); - })->orWhere(function ($query) use ($contactData) { - $query->where('from_uid', $contactData['contact_id'])->where('to_uid', $contactData['user_id']); - })->orderBy('id', 'desc')->limit(300)->get()->toArray(); - + $messageList = FriendChatHistory::query()->where(function ($query) use($contactData) { + $query->where('from_uid', $contactData['user_id'])->where('to_uid', $contactData['contact_id']); + })->orWhere(function ($query) use($contactData) { + $query->where('from_uid', $contactData['contact_id'])->where('to_uid', $contactData['user_id']); + })->orderBy('id', 'desc')->limit(300)->get()->toArray(); $messageList = array_reverse($messageList); - //将消息置为已读 - FriendChatHistory::query() - ->where('to_uid', $contactData['user_id']) - ->where('from_uid', $contactData['contact_id']) - ->update(['reception_state' => FriendChatHistory::RECEPTION_STATE_YES]); + FriendChatHistory::query()->where('to_uid', $contactData['user_id'])->where('from_uid', $contactData['contact_id'])->update(['reception_state' => FriendChatHistory::RECEPTION_STATE_YES]); $list = []; foreach ($messageList as $key => $value) { //获取用户联系人 $userInfo = User::query()->select('id', 'desc', 'avatar')->where('id', $value['from_uid'])->first(); $displayName = $userInfo['desc']; $friendRemark = FriendRelation::query()->where('uid', $value['to_uid'])->where('friend_id', $value['from_uid'])->value('friend_remark'); - if (!empty($friendRemark) && $value['from_uid'] != $contactData['user_id']) $displayName = $friendRemark; - - $temp = [ - 'id' => $value['message_id'], - 'status' => $value['status'], - 'type' => $value['type'], - 'content' => $value['content'], - 'sendTime' => intval($value['send_time']), - 'toContactId' => $value['to_uid'], - 'fileSize' => $value['file_size'], - 'fileName' => $value['file_name'], - 'fileExt' => $value['file_ext'], - 'isGroup' => false, - 'fromUser' => [ - 'id' => $userInfo['id'], - 'avatar' => $userInfo['avatar'] ?? '', - 'displayName' => $displayName, - ], - ]; - if ($temp['type'] == FriendChatHistory::FRIEND_CHAT_MESSAGE_TYPE_FORWARD) + if (!empty($friendRemark) && $value['from_uid'] != $contactData['user_id']) { + $displayName = $friendRemark; + } + $temp = ['id' => $value['message_id'], 'status' => $value['status'], 'type' => $value['type'], 'content' => $value['content'], 'sendTime' => intval($value['send_time']), 'toContactId' => $value['to_uid'], 'fileSize' => $value['file_size'], 'fileName' => $value['file_name'], 'fileExt' => $value['file_ext'], 'isGroup' => false, 'fromUser' => ['id' => $userInfo['id'], 'avatar' => $userInfo['avatar'] ?? '', 'displayName' => $displayName]]; + if ($temp['type'] == FriendChatHistory::FRIEND_CHAT_MESSAGE_TYPE_FORWARD) { $temp['content'] = MessageService::getInstance()->formatForwardMessage($temp['content'], $temp['fromUser']); + } $list[] = $temp; } - return [ - 'message_data' => [ - 'friend_history_message' => $list, - 'event' => WsMessage::MESSAGE_TYPE_PULL_FRIEND_MESSAGE - ], - 'fd' => $userFd, - ]; + return ['message_data' => ['friend_history_message' => $list, 'event' => WsMessage::MESSAGE_TYPE_PULL_FRIEND_MESSAGE], 'fd' => $userFd]; } - /** * 撤回信息 - * @RequestMapping(path="withdraw_message",methods="GET") */ + #[RequestMapping(path: 'withdraw_message', methods: array('GET'))] public function withDrawMessage() { $chatMessage = MessageParser::decode(conGet('chat_message')); $contactData = $chatMessage['message']; - $contactFd = Redis::getInstance()->hget(ChatRedisKey::ONLINE_USER_FD_KEY, (string)$contactData['toContactId']); - - FriendChatHistory::query() - ->where('message_id', $contactData['id']) - ->delete(); - return [ - 'message_data' => [ - 'message' => $contactData, - 'event' => WsMessage::MESSAGE_TYPE_FRIEND_WITHDRAW_MESSAGE - ], - 'fd' => $contactFd, - ]; + $contactFd = Redis::getInstance()->hget(ChatRedisKey::ONLINE_USER_FD_KEY, (string) $contactData['toContactId']); + FriendChatHistory::query()->where('message_id', $contactData['id'])->delete(); + return ['message_data' => ['message' => $contactData, 'event' => WsMessage::MESSAGE_TYPE_FRIEND_WITHDRAW_MESSAGE], 'fd' => $contactFd]; } -} - +} \ No newline at end of file diff --git a/app/Controller/Laboratory/Ws/GroupController.php b/app/Controller/Laboratory/Ws/GroupController.php index 4a420a5..75fb543 100644 --- a/app/Controller/Laboratory/Ws/GroupController.php +++ b/app/Controller/Laboratory/Ws/GroupController.php @@ -1,6 +1,6 @@ getOnlineGroupMemberFd($contactData['toContactId'], $contactData, true); $fdList = array_column($fdList, 'fd'); - //获取不在线用户,并添加到未读历史消息中 $unOnlineUidList = GroupService::getInstance()->getUnOnlineGroupMember($contactData['toContactId']); foreach ($unOnlineUidList as $uid) { @@ -52,84 +49,48 @@ public function sendMessage() unset($contactData['fromUser']['unread']); unset($contactData['fromUser']['lastSendTime']); unset($contactData['fromUser']['lastContent']); - //格式化转发消息类型 - if ($contactData['type'] == GroupChatHistory::GROUP_CHAT_MESSAGE_TYPE_FORWARD) $contactData['content'] = GroupService::getInstance()->formatForwardMessage($contactData['content'], $contactData['fromUser']); - return [ - 'message_data' => [ - 'event' => '', - 'message' => [ - 'id' => $contactData['id'], - 'status' => GroupChatHistory::GROUP_CHAT_MESSAGE_STATUS_SUCCEED, - 'type' => $contactData['type'], - 'sendTime' => $contactData['sendTime'], - 'content' => $contactData['content'], - 'toContactId' =>$contactData['toContactId'], - 'fromUser' => $contactData['fromUser'], - 'isGroup' => true, - ], - ], - 'fd' => $fdList - ]; + if ($contactData['type'] == GroupChatHistory::GROUP_CHAT_MESSAGE_TYPE_FORWARD) { + $contactData['content'] = GroupService::getInstance()->formatForwardMessage($contactData['content'], $contactData['fromUser']); + } + return ['message_data' => ['event' => '', 'message' => ['id' => $contactData['id'], 'status' => GroupChatHistory::GROUP_CHAT_MESSAGE_STATUS_SUCCEED, 'type' => $contactData['type'], 'sendTime' => $contactData['sendTime'], 'content' => $contactData['content'], 'toContactId' => $contactData['toContactId'], 'fromUser' => $contactData['fromUser'], 'isGroup' => true]], 'fd' => $fdList]; } /** * 拉取消息 - * @RequestMapping(path="pull_message",methods="GET") */ + #[RequestMapping(path: 'pull_message', methods: array('GET'))] public function pullMessage() { $chatMessage = MessageParser::decode(conGet('chat_message')); $contactData = $chatMessage['message']; $userFd = Redis::getInstance()->hget(ChatRedisKey::ONLINE_USER_FD_KEY, (string) $contactData['user_id']); - $userJoinGroupDate = GroupRelation::getJoinDateById($contactData['user_id'], $contactData['contact_id']); - $messageList = GroupChatHistory::query()->where('to_group_id', $contactData['contact_id']) - ->where('created_at', '>=', $userJoinGroupDate) - ->orderBy('id', 'desc')->limit(300) - ->get()->toArray(); + $messageList = GroupChatHistory::query()->where('to_group_id', $contactData['contact_id'])->where('created_at', '>=', $userJoinGroupDate)->orderBy('id', 'desc')->limit(300)->get()->toArray(); $messageList = array_reverse($messageList); - $list = []; foreach ($messageList as $key => $value) { - $temp = [ - 'id' => $value['message_id'], - 'status' => $value['status'], - 'type' => $value['type'], - 'sendTime' => intval($value['send_time']), - 'content' => $value['content'], - 'toContactId' => $value['to_group_id'], - 'fileSize' => $value['file_size'], - 'fileName' => $value['file_name'], - 'isGroup' => true, - ]; - if ($value['from_uid'] != 0) $temp['fromUser'] = [ - 'id' => $value['from_uid'], - 'avatar' => User::query()->where('id', $value['from_uid'])->value('avatar') ?? '', - 'displayName' => User::query()->where('id', $value['from_uid'])->value('desc') ?? '', - ]; + $temp = ['id' => $value['message_id'], 'status' => $value['status'], 'type' => $value['type'], 'sendTime' => intval($value['send_time']), 'content' => $value['content'], 'toContactId' => $value['to_group_id'], 'fileSize' => $value['file_size'], 'fileName' => $value['file_name'], 'isGroup' => true]; + if ($value['from_uid'] != 0) { + $temp['fromUser'] = ['id' => $value['from_uid'], 'avatar' => User::query()->where('id', $value['from_uid'])->value('avatar') ?? '', 'displayName' => User::query()->where('id', $value['from_uid'])->value('desc') ?? '']; + } //格式化转发类型的消息类型 - if ($value['type'] == GroupChatHistory::GROUP_CHAT_MESSAGE_TYPE_FORWARD) $temp['content'] = MessageService::getInstance()->formatForwardMessage($value['content'], $temp['fromUser']); + if ($value['type'] == GroupChatHistory::GROUP_CHAT_MESSAGE_TYPE_FORWARD) { + $temp['content'] = MessageService::getInstance()->formatForwardMessage($value['content'], $temp['fromUser']); + } $list[] = $temp; } - return [ - 'message_data' => [ - 'group_history_message' => $list, - 'event' => WsMessage::MESSAGE_TYPE_PULL_GROUP_MESSAGE - ], - 'fd' => $userFd, - ]; + return ['message_data' => ['group_history_message' => $list, 'event' => WsMessage::MESSAGE_TYPE_PULL_GROUP_MESSAGE], 'fd' => $userFd]; } /** * 创建组 - * @RequestMapping(path="create_group",methods="POST") */ + #[RequestMapping(path: 'create_group', methods: array('POST'))] public function createGroup() { $chatMessage = MessageParser::decode(conGet('chat_message')); $contactData = $chatMessage['message']; - $groupInsertData = []; $groupInsertData['group_id'] = getRandStr(16); $groupInsertData['uid'] = $contactData['creator']['id']; @@ -142,7 +103,6 @@ public function createGroup() $groupInsertData['updated_at'] = date('Y-m-d H:i:s'); Group::query()->insert($groupInsertData); GroupRelation::buildRelation($groupInsertData['uid'], $groupInsertData['group_id'], GroupRelation::GROUP_MEMBER_LEVEL_LORD); - if (!empty($contactData['checkedContacts'])) { $contactIdList = array_column($contactData['checkedContacts'], 'id'); if (!empty($contactIdList)) { @@ -171,24 +131,26 @@ public function createGroup() /** * 组员修改群资料操作 - * @RequestMapping(path="edit_group",methods="POST") */ + #[RequestMapping(path: 'edit_group', methods: array('POST'))] public function editGroup() { $chatMessage = MessageParser::decode(conGet('chat_message')); $contactData = $chatMessage['message']; - - if (empty($contactData['group_id'])) return false; + if (empty($contactData['group_id'])) { + return false; + } $groupInfo = Group::findById($contactData['group_id']); $userInfo = User::findById($contactData['uid']); - if (empty($groupInfo)) return false; + if (empty($groupInfo)) { + return false; + } $groupInfo->avatar = $contactData['avatar'] ?? ''; $groupInfo->group_name = $contactData['group_name'] ?? ''; $groupInfo->introduction = $contactData['introduction'] ?? ''; $groupInfo->size = $contactData['size'] ?? 200; $groupInfo->validation = $contactData['validation'] ?? 0; $groupInfo->save(); - $message = []; $content = $userInfo['desc'] . ' 修改了群资料'; $message['id'] = generate_rand_id(); @@ -198,7 +160,6 @@ public function editGroup() $message['toContactId'] = $groupInfo['group_id']; $message['content'] = $content ?? ''; $message['group_info'] = $groupInfo; - //通知群里所有群员修改群资料操作 $this->container->get(GroupWsTask::class)->sendMessage($contactData['group_id'], $message, GroupEvent::EDIT_GROUP_EVENT); return true; @@ -206,17 +167,17 @@ public function editGroup() /** * 邀请组员 - * @RequestMapping(path="invite_group_member",methods="POST") */ + #[RequestMapping(path: 'invite_group_member', methods: array('POST'))] public function inviteGroupMember() { //TODO 需要验证群是否存在,存在可能群员邀请用户时 群主删群操作 $chatMessage = MessageParser::decode(conGet('chat_message')); $contactData = $chatMessage['message']; - $groupInfo = Group::findById($contactData['id'])->toArray(); - if (empty($groupInfo)) return false; - + if (empty($groupInfo)) { + return false; + } if (!empty($contactData['newJoinGroupMember'])) { $contactIdList = array_column($contactData['newJoinGroupMember'], 'id'); if (!empty($contactIdList)) { @@ -228,7 +189,7 @@ public function inviteGroupMember() if (!empty($contactIdList)) { //推送新成员进群通知 $newMemberJoinMessage = []; - $content = join(User::query()->whereIn('id', $contactIdList)->pluck('desc')->toArray(), ' , ') . ' 加入群聊'; + $content = join(' , ', User::query()->whereIn('id', $contactIdList)->pluck('desc')->toArray()) . ' 加入群聊'; $newMemberJoinMessage['id'] = generate_rand_id(); $newMemberJoinMessage['status'] = GroupChatHistory::GROUP_CHAT_MESSAGE_STATUS_SUCCEED; $newMemberJoinMessage['type'] = GroupChatHistory::GROUP_CHAT_MESSAGE_TYPE_EVENT; @@ -245,42 +206,54 @@ public function inviteGroupMember() /** * 组员退群操作 - * @RequestMapping(path="exit_group",methods="POST") */ + #[RequestMapping(path: 'exit_group', methods: array('POST'))] public function exitGroup() { $chatMessage = MessageParser::decode(conGet('chat_message')); $contactData = $chatMessage['message']; - - if (empty($contactData['group_id'])) return false; - if (empty($contactData['uid'])) return false; + if (empty($contactData['group_id'])) { + return false; + } + if (empty($contactData['uid'])) { + return false; + } $groupInfo = Group::findById($contactData['group_id'])->toArray(); $userInfo = User::findById($contactData['uid'])->toArray(); - if (empty($groupInfo)) return false; - if (empty($userInfo)) return false; - + if (empty($groupInfo)) { + return false; + } + if (empty($userInfo)) { + return false; + } //通知用户退群事件 - $this->container->get(GroupWsTask::class)->groupMemberExitEvent($groupInfo, $userInfo, GroupEvent::GROUP_MEMBER_EXIT_EVENT ); + $this->container->get(GroupWsTask::class)->groupMemberExitEvent($groupInfo, $userInfo, GroupEvent::GROUP_MEMBER_EXIT_EVENT); $this->container->get(GroupWsTask::class)->changeGroupAvatar($groupInfo); return true; } /** * 将用户剔除群聊事件 - * @RequestMapping(path="delete_group_member",methods="POST") */ + #[RequestMapping(path: 'delete_group_member', methods: array('POST'))] public function deleteGroupMember() { $chatMessage = MessageParser::decode(conGet('chat_message')); $contactData = $chatMessage['message']; - - if (empty($contactData['group_id'])) return false; - if (empty($contactData['uid'])) return false; + if (empty($contactData['group_id'])) { + return false; + } + if (empty($contactData['uid'])) { + return false; + } $groupInfo = Group::findById($contactData['group_id'])->toArray(); $userInfo = User::findById($contactData['uid'])->toArray(); - if (empty($groupInfo)) return false; - if (empty($userInfo)) return false; - + if (empty($groupInfo)) { + return false; + } + if (empty($userInfo)) { + return false; + } //通知用户退群事件 $this->container->get(GroupWsTask::class)->groupMemberExitEvent($groupInfo, $userInfo, GroupEvent::DELETE_GROUP_MEMBER_EVENT); $this->container->get(GroupWsTask::class)->changeGroupAvatar($groupInfo); @@ -289,20 +262,26 @@ public function deleteGroupMember() /** * 修改用户等级事件 - * @RequestMapping(path="change_group_member_level",methods="POST") */ + #[RequestMapping(path: 'change_group_member_level', methods: array('POST'))] public function changeGroupMemberLevel() { $chatMessage = MessageParser::decode(conGet('chat_message')); $contactData = $chatMessage['message']; - - if (empty($contactData['group_id'])) return false; - if (empty($contactData['uid'])) return false; + if (empty($contactData['group_id'])) { + return false; + } + if (empty($contactData['uid'])) { + return false; + } $groupInfo = Group::findById($contactData['group_id'])->toArray(); $userInfo = User::findById($contactData['uid'])->toArray(); - if (empty($groupInfo)) return false; - if (empty($userInfo)) return false; - + if (empty($groupInfo)) { + return false; + } + if (empty($userInfo)) { + return false; + } $changeLevel = $contactData['level'] == GroupRelation::GROUP_MEMBER_LEVEL_MANAGER ? GroupRelation::GROUP_MEMBER_LEVEL_MEMBER : GroupRelation::GROUP_MEMBER_LEVEL_MANAGER; $this->container->get(GroupWsTask::class)->changeGroupMemberLevel($groupInfo, $userInfo, $changeLevel); return true; @@ -310,24 +289,29 @@ public function changeGroupMemberLevel() /** * 解散群聊 - * @RequestMapping(path="delete_group",methods="POST") */ + #[RequestMapping(path: 'delete_group', methods: array('POST'))] public function deleteGroup() { $chatMessage = MessageParser::decode(conGet('chat_message')); $contactData = $chatMessage['message']; - - if (empty($contactData['group_id'])) return false; - if (empty($contactData['uid'])) return false; + if (empty($contactData['group_id'])) { + return false; + } + if (empty($contactData['uid'])) { + return false; + } $groupInfo = Group::findById($contactData['group_id'])->toArray(); $userInfo = User::findById($contactData['uid'])->toArray(); - - if (empty($groupInfo)) return false; - if (empty($userInfo)) return false; + if (empty($groupInfo)) { + return false; + } + if (empty($userInfo)) { + return false; + } Db::beginTransaction(); $this->container->get(GroupWsTask::class)->deleteGroup($groupInfo, $userInfo); Db::commit(); return true; } -} - +} \ No newline at end of file diff --git a/app/Controller/Laboratory/Ws/MessageController.php b/app/Controller/Laboratory/Ws/MessageController.php index 501750d..934efbd 100644 --- a/app/Controller/Laboratory/Ws/MessageController.php +++ b/app/Controller/Laboratory/Ws/MessageController.php @@ -1,6 +1,6 @@ where('group_id', $item['id'])->first(); - if (empty($groupInfo)) continue; + if (empty($groupInfo)) { + continue; + } $groupInfo = objToArray($groupInfo); $this->container->get(GroupWsTask::class)->mergeForwardMessage($groupInfo, $user, $content); - }else { + } else { $userInfo = User::query()->where('id', $item['id'])->first(); - if (empty($userInfo)) continue; + if (empty($userInfo)) { + continue; + } $userInfo = objToArray($userInfo); $this->container->get(FriendWsTask::class)->mergeForwardMessage($userInfo, $user, $content); } @@ -52,27 +59,34 @@ public function mergeForwardMessage() /** * 转发信息 - * @RequestMapping(path="forward_message",methods="POST") + * @Author YiYuan + * @Date 2023/12/22 + * @return void + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ + #[RequestMapping(path: 'forward_message', methods: array('POST'))] public function forwardMessage() { $chatMessage = MessageParser::decode(conGet('chat_message')); $contactData = $chatMessage['message']; - $user = $contactData['user']; foreach ($contactData['contact'] as $item) { if ($item['is_group'] == 1) { $groupInfo = Group::query()->where('group_id', $item['id'])->first(); - if (empty($groupInfo)) continue; + if (empty($groupInfo)) { + continue; + } $groupInfo = objToArray($groupInfo); $this->container->get(GroupWsTask::class)->forwardMessage($groupInfo, $user, $contactData['message']); - }else { + } else { $userInfo = User::query()->where('id', $item['id'])->first(); - if (empty($userInfo)) continue; + if (empty($userInfo)) { + continue; + } $userInfo = objToArray($userInfo); $this->container->get(FriendWsTask::class)->forwardMessage($userInfo, $user, $contactData['message']); } } } -} - +} \ No newline at end of file diff --git a/app/Controller/Laboratory/Ws/WebsocketController.php b/app/Controller/Laboratory/Ws/WebsocketController.php index 6afe571..589aac8 100644 --- a/app/Controller/Laboratory/Ws/WebsocketController.php +++ b/app/Controller/Laboratory/Ws/WebsocketController.php @@ -1,30 +1,25 @@ data, true); - conSet('chat_message', MessageParser::encode([ - 'message' => $message['message'], - 'file' => $message['file'] ?? '', - ])); - $targetUri = $message['uri'] ?? ''; - $requestMethod = $message['method'] ?? 'GET'; - $dispatcher = $this->container - ->get(DispatcherFactory::class) - ->getDispatcher('ws'); - $dispatched = make(Dispatched::class, [ - $dispatcher->dispatch($requestMethod, $targetUri) - ]); - if ($dispatched->isFound()) { - //路由处理 - $result = call_user_func([ - make($dispatched->handler->callback[0]), - $dispatched->handler->callback[1], - ]); - if ($result !== NULL) { - if (!empty($result['fd'])){ - if (is_array($result['fd'])) { - foreach ($result['fd'] as $fd) { - $server->push((int) $fd, json_encode($result['message_data'])); - } - }else { - $server->push((int) $result['fd'], json_encode($result['message_data'])); + $message = json_decode($frame->data, true); + conSet('chat_message', MessageParser::encode(['message' => $message['message'], 'file' => $message['file'] ?? ''])); + $targetUri = $message['uri'] ?? ''; + $requestMethod = $message['method'] ?? 'GET'; + $dispatcher = $this->container->get(DispatcherFactory::class)->getDispatcher('ws'); + $dispatched = make(Dispatched::class, [$dispatcher->dispatch($requestMethod, $targetUri)]); + if ($dispatched->isFound()) { + //路由处理 + $result = call_user_func([make($dispatched->handler->callback[0]), $dispatched->handler->callback[1]]); + if ($result !== NULL) { + if (!empty($result['fd'])) { + if (is_array($result['fd'])) { + foreach ($result['fd'] as $fd) { + $server->push((int) $fd, json_encode($result['message_data'])); } + } else { + $server->push((int) $result['fd'], json_encode($result['message_data'])); } } } + } } + /** * 用户连接服务器 - * @param \Swoole\Http\Response|WebSocketServer $server - * @param Request $request + * @Author YiYuan + * @Date 2023/12/22 + * @param $server + * @param $request + * @return void + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface + * @throws \RedisException */ - public function onOpen($server, Request $request): void + public function onOpen($server, $request) : void { //是否重连,如果是断线重连择不通知好友新用户上线提示 $isReconnection = conGet('is_reconnection') ?? false; //获取聊天初始化信息 + //TODO 该方法效率有待提高 $initInfo = InitService::getInstance()->initialization(); //获取用户信息 $userInfo = conGet('user_info'); @@ -99,7 +94,6 @@ public function onOpen($server, Request $request): void Redis::getInstance()->hSet(ChatRedisKey::ONLINE_USER_FD_KEY, (string) $initInfo['user_info']['id'], (string) $request->fd); //将FD对应在线用户ID放置Redis中 Redis::getInstance()->hSet(ChatRedisKey::ONLINE_FD_USER_KEY, (string) $request->fd, (string) $initInfo['user_info']['id']); - //连接信息发送 $server->push($request->fd, MessageParser::encode($initInfo)); //通知好友该用户登陆状态 @@ -108,15 +102,20 @@ public function onOpen($server, Request $request): void /** * 用户关闭连接 - * @param \Swoole\Http\Response|WebSocketServer $server + * @Author YiYuan + * @Date 2023/12/22 + * @param $server * @param int $fd * @param int $reactorId + * @return void + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface + * @throws \RedisException */ - public function onClose($server, int $fd, int $reactorId): void + public function onClose($server, int $fd, int $reactorId) : void { $uid = Redis::getInstance()->hGet(ChatRedisKey::ONLINE_FD_USER_KEY, (string) $fd); $userInfo = User::findById($uid)->toArray(); - //删除在线列表中的用户 Redis::getInstance()->hDel(ChatRedisKey::ONLINE_USER_FD_KEY, (string) $userInfo['id']); Redis::getInstance()->hDel(ChatRedisKey::ONLINE_FD_USER_KEY, (string) $fd); diff --git a/app/Controller/Setting/MonitoringController.php b/app/Controller/Setting/MonitoringController.php index 8074741..0124df5 100644 --- a/app/Controller/Setting/MonitoringController.php +++ b/app/Controller/Setting/MonitoringController.php @@ -1,7 +1,6 @@ getCpuInfo(); - $memoryInfo = ServeMonitorService::getInstance()->getMemoryInfo(); - $uptime = ServeMonitorService::getInstance()->getUptime(); - $serveInfo = ServeMonitorService::getInstance()->getServeInfo(); - - return $this->success([ - 'cpu_info' => $cpuInfo, - 'memory_info' => $memoryInfo, - 'uptime' => $uptime, - 'serve_info' => $serveInfo, - ]); + return $this->success(['cpu_info' => $cpuInfo, 'memory_info' => $memoryInfo, 'uptime' => $uptime, 'serve_info' => $serveInfo]); } -} +} \ No newline at end of file diff --git a/app/Controller/Setting/TimedTaskController.php b/app/Controller/Setting/TimedTaskController.php index 001db1c..8b3b950 100644 --- a/app/Controller/Setting/TimedTaskController.php +++ b/app/Controller/Setting/TimedTaskController.php @@ -1,7 +1,6 @@ timedTask->newQuery(); $status = $this->request->input('status') ?? ''; $name = $this->request->input('name') ?? ''; $task = $this->request->input('task') ?? ''; - - if (strlen($status) > 0) $timedTaskQuery->where('status', $status); - if (!empty($name)) $timedTaskQuery->where('name', 'like', '%' . $name . '%'); - if (!empty($task)) $timedTaskQuery->where('task', 'like', '%' . $task . '%'); - + if (strlen($status) > 0) { + $timedTaskQuery->where('status', $status); + } + if (!empty($name)) { + $timedTaskQuery->where('name', 'like', '%' . $name . '%'); + } + if (!empty($task)) { + $timedTaskQuery->where('task', 'like', '%' . $task . '%'); + } $total = $timedTaskQuery->count(); $timedTaskQuery = $this->pagingCondition($timedTaskQuery, $this->request->all()); $data = $timedTaskQuery->get(); - - return $this->success([ - 'list' => $data, - 'total' => $total, - ]); + return $this->success(['list' => $data, 'total' => $total]); } /** - * @Explanation(content="添加定时任务") - * @RequestMapping(path="store", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 添加定时任务 + * @Author YiYuan + * @Date 2023/12/4 + * @return \Psr\Http\Message\ResponseInterface * @throws \Exception */ + #[Explanation(content: '添加定时任务')] + #[RequestMapping(path: 'store', methods: array('POST'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function store() { $postData = $this->request->all(); - $params = [ - 'name' => $postData['name'] ?? '', - 'params' => $postData['params'] ?? '', - 'task' => $postData['task'] ?? '', - 'execute_time' => $postData['execute_time'] ?? '', - 'status' => $postData['status'] ?? '', - 'desc' => $postData['desc'] ?? '', - ]; + $params = ['name' => $postData['name'] ?? '', 'params' => $postData['params'] ?? '', 'task' => $postData['task'] ?? '', 'execute_time' => $postData['execute_time'] ?? '', 'status' => $postData['status'] ?? '', 'desc' => $postData['desc'] ?? '']; //配置验证 - $rules = [ - 'name' => 'required', - 'task' => 'required', - 'execute_time' => 'required', - ]; + $rules = ['name' => 'required', 'task' => 'required', 'execute_time' => 'required']; //错误信息 - $message = [ - 'name.required' => '[name]缺失', - 'task.required' => '[task]缺失', - 'execute_time.required' => '[execute_time]缺失', - ]; + $message = ['name.required' => '[name]缺失', 'task.required' => '[task]缺失', 'execute_time.required' => '[execute_time]缺失']; $this->verifyParams($params, $rules, $message); - $timedTaskQuery = new TimedTask(); $timedTaskQuery->name = $params['name']; $timedTaskQuery->params = json_encode($params['params']); @@ -103,101 +85,87 @@ public function store() $timedTaskQuery->status = $params['status']; $timedTaskQuery->desc = $params['desc']; $timedTaskQuery->times = 0; - $executeTime = $params['execute_time'] ?? ''; $nextExecuteTime = Cron::init($executeTime)->getNextRunDate()->format('Y-m-d H:i'); $timedTaskQuery->next_execute_time = $nextExecuteTime; - - if (!$timedTaskQuery->save()) $this->throwExp(StatusCode::ERR_EXCEPTION, '添加定时任务错误'); - + if (!$timedTaskQuery->save()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '添加定时任务错误'); + } return $this->successByMessage('添加定时任务成功'); } /** - * 获取单个定时任务信息 + * 获取编辑选项 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="edit/{id}", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'edit/{id}', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function edit(int $id) { $timedTaskInfo = TimedTask::findById($id); $timedTaskInfo['params'] = json_decode($timedTaskInfo['params'], true); - if (empty($timedTaskInfo)) $this->throwExp(StatusCode::ERR_USER_ABSENT, '获取定时任务失败'); - - return $this->success([ - 'list' => $timedTaskInfo - ]); + if (empty($timedTaskInfo)) { + $this->throwExp(StatusCode::ERR_USER_ABSENT, '获取定时任务失败'); + } + return $this->success(['list' => $timedTaskInfo]); } /** - * @Explanation(content="修改定时任务状态开关") + * 更新定时任务状态 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="change_status/{id}", methods="put") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) - * @throws \Exception * @return \Psr\Http\Message\ResponseInterface + * @throws \Exception */ - + #[Explanation(content: '更新定时任务状态')] + #[RequestMapping(path: 'change_status/{id}', methods: array('PUT'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function changeStatus(int $id) { $status = $this->request->input('status'); - if ($status != 0 && empty($status)) $this->throwExp(StatusCode::ERR_VALIDATION, '状态参数为空'); + if ($status != 0 && empty($status)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '状态参数为空'); + } $timedTaskInfo = TimedTask::findById($id); - if (empty($timedTaskInfo)) $this->throwExp(StatusCode::ERR_VALIDATION, '查询不到该任务'); - + if (empty($timedTaskInfo)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '查询不到该任务'); + } $executeTime = $timedTaskInfo['execute_time'] ?? ''; $nextExecuteTime = Cron::init($executeTime)->getNextRunDate()->format('Y-m-d H:i'); - //修改状态以及下次执行时间 TimedTask::query()->where('id', $id)->update(['status' => $status, 'next_execute_time' => $nextExecuteTime]); return $this->successByMessage('修改状态成功'); } - /** - * @Explanation(content="修改定时任务信息") + * 编辑 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="update/{id}", methods="put") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) * @return \Psr\Http\Message\ResponseInterface * @throws \Exception */ + #[Explanation(content: '编辑定时任务')] + #[RequestMapping(path: 'update/{id}', methods: array('PUT'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function update(int $id) { - if (empty($id)) $this->throwExp(StatusCode::ERR_VALIDATION, 'ID 不能为空'); + if (empty($id)) { + $this->throwExp(StatusCode::ERR_VALIDATION, 'ID 不能为空'); + } $postData = $this->request->all(); - $params = [ - 'name' => $postData['name'] ?? '', - 'params' => $postData['params'] ?? '', - 'task' => $postData['task'] ?? '', - 'execute_time' => $postData['execute_time'] ?? '', - 'status' => $postData['status'] ?? '', - 'desc' => $postData['desc'] ?? '', - ]; + $params = ['name' => $postData['name'] ?? '', 'params' => $postData['params'] ?? '', 'task' => $postData['task'] ?? '', 'execute_time' => $postData['execute_time'] ?? '', 'status' => $postData['status'] ?? '', 'desc' => $postData['desc'] ?? '']; //配置验证 - $rules = [ - 'name' => 'required', - 'task' => 'required', - 'execute_time' => 'required', - ]; + $rules = ['name' => 'required', 'task' => 'required', 'execute_time' => 'required']; //错误信息 - $message = [ - 'name.required' => '[name]缺失', - 'task.required' => '[task]缺失', - 'execute_time.required' => '[execute_time]缺失', - ]; + $message = ['name.required' => '[name]缺失', 'task.required' => '[task]缺失', 'execute_time.required' => '[execute_time]缺失']; $this->verifyParams($params, $rules, $message); - $timedTaskQuery = TimedTask::findById($id); $timedTaskQuery->name = $params['name']; $timedTaskQuery->params = json_encode($params['params']); @@ -207,33 +175,41 @@ public function update(int $id) $executeTime = $params['execute_time'] ?? ''; $nextExecuteTime = Cron::init($executeTime)->getNextRunDate()->format('Y-m-d H:i'); $timedTaskQuery->next_execute_time = $nextExecuteTime; - - if (!$timedTaskQuery->save()) $this->throwExp(StatusCode::ERR_EXCEPTION, '修改定时任务错误'); + if (!$timedTaskQuery->save()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '修改定时任务错误'); + } return $this->successByMessage('修改定时任务成功'); } /** - * @Explanation(content="删除定时任务") + * 删除 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="destroy/{id}", methods="delete") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '删除定时任务')] + #[RequestMapping(path: 'destroy/{id}', methods: array('DELETE'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function destroy(int $id) { if ($id == 0) { $idArr = $this->request->input('id') ?? []; - if (empty($idArr) || !is_array($idArr)) $this->throwExp(StatusCode::ERR_VALIDATION, '参数类型不正确'); - if (!TimedTask::whereIn('id', $idArr)->delete()) $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); - }else { - if (!intval($id)) $this->throwExp(StatusCode::ERR_VALIDATION, '参数错误'); - if (!TimedTask::destroy($id)) $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + if (empty($idArr) || !is_array($idArr)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '参数类型不正确'); + } + if (!TimedTask::whereIn('id', $idArr)->delete()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + } + } else { + if (!intval($id)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '参数错误'); + } + if (!TimedTask::destroy($id)) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + } } - return $this->successByMessage('删除定时任务成功'); } - } \ No newline at end of file diff --git a/app/Controller/System/AdviceController.php b/app/Controller/System/AdviceController.php index a564bc2..f7fd7fb 100644 --- a/app/Controller/System/AdviceController.php +++ b/app/Controller/System/AdviceController.php @@ -1,7 +1,6 @@ advice->newQuery(); @@ -54,41 +51,29 @@ public function index() return $this->success([ 'list' => $data, - 'total' => $total, + 'total' => $total ]); } /** - * @Explanation(content="添加系统建议") - * @RequestMapping(path="store", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 添加 + * @Author YiYuan + * @Date 2023/12/4 + * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '添加系统建议')] + #[RequestMapping(path: 'store', methods: array('POST'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function store() { $postData = $this->request->all(); - $params = [ - 'title' => $postData['title'] ?? '', - 'type' => $postData['type'] ?? '', - 'content' => $postData['content'] ?? '', - ]; + $params = ['title' => $postData['title'] ?? '', 'type' => $postData['type'] ?? '', 'content' => $postData['content'] ?? '']; //配置验证 - $rules = [ - 'title' => 'required', - 'type' => 'required|integer', - 'content' => 'required', - ]; + $rules = ['title' => 'required', 'type' => 'required|integer', 'content' => 'required']; //错误信息 - $message = [ - 'title.required' => '[title]缺失', - 'type.required' => '[type]缺失', - 'type.integer' => '[type]类型不正确', - 'content.required' => '[content]缺失', - ]; + $message = ['title.required' => '[title]缺失', 'type.required' => '[type]缺失', 'type.integer' => '[type]类型不正确', 'content.required' => '[content]缺失']; $this->verifyParams($params, $rules, $message); - $adviceQuery = new Advice(); $adviceQuery->title = $params['title']; $adviceQuery->type = $params['type']; @@ -96,137 +81,124 @@ public function store() $adviceQuery->reply = ''; $adviceQuery->status = 0; $adviceQuery->user_id = conGet('user_info')['id']; - - if (!$adviceQuery->save()) $this->throwExp(StatusCode::ERR_EXCEPTION, '添加系统建议错误'); - + if (!$adviceQuery->save()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '添加系统建议错误'); + } return $this->successByMessage('添加系统建议成功'); } /** - * 获取单个系统建议信息 + * 获取编辑选项 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="edit/{id}", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'edit/{id}', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function edit(int $id) { $adviceInfo = Advice::findById($id); - if (empty($adviceInfo)) $this->throwExp(StatusCode::ERR_USER_ABSENT, '获取字典信息失败'); - - return $this->success([ - 'list' => $adviceInfo - ]); + if (empty($adviceInfo)) { + $this->throwExp(StatusCode::ERR_USER_ABSENT, '获取字典信息失败'); + } + return $this->success(['list' => $adviceInfo]); } /** - * @Explanation(content="修改系统建议信息") + * 修改 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="update/{id}", methods="put") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '修改系统建议')] + #[RequestMapping(path: 'update/{id}', methods: array('PUT'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function update(int $id) { - if (empty($id)) $this->throwExp(StatusCode::ERR_VALIDATION, 'ID 不能为空'); + if (empty($id)) { + $this->throwExp(StatusCode::ERR_VALIDATION, 'ID 不能为空'); + } $postData = $this->request->all(); - $params = [ - 'title' => $postData['title'] ?? '', - 'type' => $postData['type'] ?? '', - 'content' => $postData['content'] ?? '', - ]; + $params = ['title' => $postData['title'] ?? '', 'type' => $postData['type'] ?? '', 'content' => $postData['content'] ?? '']; //配置验证 - $rules = [ - 'title' => 'required', - 'type' => 'required|integer', - 'content' => 'required', - ]; + $rules = ['title' => 'required', 'type' => 'required|integer', 'content' => 'required']; //错误信息 - $message = [ - 'title.required' => '[title]缺失', - 'type.required' => '[type]缺失', - 'type.integer' => '[type]类型不正确', - 'content.required' => '[content]缺失', - ]; + $message = ['title.required' => '[title]缺失', 'type.required' => '[type]缺失', 'type.integer' => '[type]类型不正确', 'content.required' => '[content]缺失']; $this->verifyParams($params, $rules, $message); - $adviceQuery = Advice::findById($id); $adviceQuery->title = $params['title']; $adviceQuery->type = $params['type']; $adviceQuery->content = $params['content']; - - if (!$adviceQuery->save()) $this->throwExp(StatusCode::ERR_EXCEPTION, '修改系统建议错误'); - + if (!$adviceQuery->save()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '修改系统建议错误'); + } return $this->successByMessage('修改系统建议成功'); } /** - * @Explanation(content="回复建议") + * 回复系统建议 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="reply/{id}", methods="put") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '回复建议')] + #[RequestMapping(path: 'reply/{id}', methods: array('PUT'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function reply(int $id) { - if (empty($id)) $this->throwExp(StatusCode::ERR_VALIDATION, 'ID 不能为空'); + if (empty($id)) { + $this->throwExp(StatusCode::ERR_VALIDATION, 'ID 不能为空'); + } $postData = $this->request->all(); - $params = [ - 'reply' => $postData['reply'] ?? '', - 'status' => $postData['status'] ?? '', - ]; + $params = ['reply' => $postData['reply'] ?? '', 'status' => $postData['status'] ?? '']; //配置验证 - $rules = [ - 'reply' => 'required', - 'status' => 'required|integer', - ]; + $rules = ['reply' => 'required', 'status' => 'required|integer']; //错误信息 - $message = [ - 'reply.required' => '[reply]缺失', - 'status.required' => '[status]缺失', - 'status.integer' => '[status]类型不正确', - ]; + $message = ['reply.required' => '[reply]缺失', 'status.required' => '[status]缺失', 'status.integer' => '[status]类型不正确']; $this->verifyParams($params, $rules, $message); - $adviceQuery = Advice::findById($id); $adviceQuery->reply = $params['reply']; $adviceQuery->status = $params['status']; - - if (!$adviceQuery->save()) $this->throwExp(StatusCode::ERR_EXCEPTION, '回复系统建议错误'); - + if (!$adviceQuery->save()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '回复系统建议错误'); + } return $this->successByMessage('回复系统建议成功'); } /** - * @Explanation(content="删除系统建议") + * 删除 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="destroy/{id}", methods="delete") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '删除系统建议')] + #[RequestMapping(path: 'destroy/{id}', methods: array('DELETE'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function destroy(int $id) { if ($id == 0) { $idArr = $this->request->input('id') ?? []; - if (empty($idArr) || !is_array($idArr)) $this->throwExp(StatusCode::ERR_VALIDATION, '参数类型不正确'); - if (!Advice::whereIn('id', $idArr)->delete()) $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); - }else { - if (!intval($id)) $this->throwExp(StatusCode::ERR_VALIDATION, '参数错误'); - if (!Advice::destroy($id)) $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + if (empty($idArr) || !is_array($idArr)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '参数类型不正确'); + } + if (!Advice::whereIn('id', $idArr)->delete()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + } + } else { + if (!intval($id)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '参数错误'); + } + if (!Advice::destroy($id)) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + } } - return $this->successByMessage('删除系统建议成功'); } - } \ No newline at end of file diff --git a/app/Controller/System/ControlController.php b/app/Controller/System/ControlController.php index 0812e7e..b2b4232 100644 --- a/app/Controller/System/ControlController.php +++ b/app/Controller/System/ControlController.php @@ -1,11 +1,11 @@ globalConfig->query(); $list = $query->where('type', GlobalConfig::TYPE_BY_BOOLEAN)->get()->toArray(); - $result = []; foreach ($list as $key => $value) { - $result[$value['key_name']] = (bool) ($value['data']); + $result[$value['key_name']] = (bool) $value['data']; } - return $this->success([ - 'list' => $result - ]); + return $this->success(['list' => $result]); } /** - * 开关控制 - * @RequestMapping(path="change_control", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 修改控制状态 + * @Author YiYuan + * @Date 2023/12/4 + * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '修改控制状态')] + #[RequestMapping(path: 'change_control', methods: array('POST'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function changeControl() { $requestData = $this->request->all(); $params = [ 'key' => $requestData['key'] ?? '', - 'value' => $requestData['value'] ?? '', + 'value' => $requestData['value'] ?? '' ]; $rules = [ 'key' => 'required', - 'value' => 'required', + 'value' => 'required' ]; $message = [ 'key.required' => 'key 缺失', - 'value.required' => 'value 缺失', + 'value.required' => 'value 缺失' ]; $this->verifyParams($params, $rules, $message); - $configQuery = GlobalConfig::where('key_name', $params['key'])->first(); - $configQuery->data = $params['value']; - if (!$configQuery->save()) $this->throwExp(StatusCode::ERR_EXCEPTION, '修改失败'); - + if (!$configQuery->save()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '修改失败'); + } return $this->successByMessage('修改成功'); } } \ No newline at end of file diff --git a/app/Controller/System/DictDataController.php b/app/Controller/System/DictDataController.php index d240d9b..ade8164 100644 --- a/app/Controller/System/DictDataController.php +++ b/app/Controller/System/DictDataController.php @@ -1,7 +1,6 @@ dictData->newQuery(); $status = $this->request->input('status'); $dictLabel = $this->request->input('dict_label') ?? ''; $dictType = $this->request->input('dict_type') ?? ''; - - if (!empty($dictLabel)) $dictDataQuery->where('dict_label', 'like', '%' . $dictLabel . '%'); - if (!empty($dictType)) $dictDataQuery->where('dict_type', 'like', '%' . $dictType . '%'); - if (strlen($status) > 0) $dictDataQuery->where('status', $status); - + if (!empty($dictLabel)) { + $dictDataQuery->where('dict_label', 'like', '%' . $dictLabel . '%'); + } + if (!empty($dictType)) { + $dictDataQuery->where('dict_type', 'like', '%' . $dictType . '%'); + } + if (strlen($status) > 0) { + $dictDataQuery->where('status', $status); + } $total = $dictDataQuery->count(); $dictDataQuery = $this->pagingCondition($dictDataQuery, $this->request->all()); - $data = $dictDataQuery->get(); + $data = $dictDataQuery->get()->toArray(); return $this->success([ 'list' => $data, - 'total' => $total, + 'total' => $total ]); } + /** - * 根据字典类型获取字典数据 + * 选项 + * @Author YiYuan + * @Date 2023/12/4 * @param string $dictType - * @RequestMapping(path="dict/{dictType}", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'dict/{dictType}', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function getDict(string $dictType) { - if (!is_string($dictType) && empty($dictType)) $this->throwExp(StatusCode::ERR_VALIDATION, '字典类型为空或者参数格式不正确'); - + if (empty($dictType)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '字典类型为空或者参数格式不正确'); + } $list = DictData::query()->where('dict_type', $dictType)->get()->toArray(); foreach ($list as $key => $val) { - if(is_numeric($val['dict_value'])) $list[$key]['dict_value'] = intval($val['dict_value']); + if (is_numeric($val['dict_value'])) { + $list[$key]['dict_value'] = intval($val['dict_value']); + } } return $this->success([ - 'list' => $list, + 'list' => $list ]); } /** - * @Explanation(content="添加字典数据") - * @RequestMapping(path="store", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 添加 + * @Author YiYuan + * @Date 2023/12/4 + * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '添加字典数据')] + #[RequestMapping(path: 'store', methods: array('POST'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function store() { - $postData = $this->request->all(); $params = [ - 'dict_type' => $postData['dict_type'] ?? '', - 'dict_label' => $postData['dict_label'] ?? '', - 'dict_value' => $postData['dict_value'] ?? '', - 'dict_sort' => $postData['dict_sort'] ?? 1, - 'status' => $postData['status'] ?? 1, - 'remark' => $postData['remark'] ?? '', + 'dict_type' => $this->params('dict_type') ?? '', + 'dict_label' => $this->params('dict_label') ?? '', + 'dict_value' => $this->params('dict_value') ?? '', + 'dict_sort' => $this->params('dict_sort') ?? 1, + 'status' => $this->params('status') ?? 1, + 'remark' => $this->params('remark') ?? '' ]; - //配置验证 $rules = [ 'dict_type' => 'required', 'dict_label' => 'required', - 'dict_value' => 'required', + 'dict_value' => 'required' ]; //错误信息 $message = [ 'dict_type.required' => '[dict_type]缺失', 'dict_label.required' => '[dict_label]缺失', - 'dict_value.required' => '[dict_value]缺失', + 'dict_value.required' => '[dict_value]缺失' ]; $this->verifyParams($params, $rules, $message); - $dictDataQuery = new DictData(); $dictDataQuery->dict_type = $params['dict_type']; $dictDataQuery->dict_label = $params['dict_label']; @@ -122,66 +125,63 @@ public function store() $dictDataQuery->remark = $params['remark']; $dictDataQuery->created_at = date('Y-m-d, H:i:s'); $dictDataQuery->updated_at = date('Y-m-d, H:i:s'); - if (!$dictDataQuery->save()) $this->throwExp(StatusCode::ERR_EXCEPTION, '添加字典数据错误'); - + if (!$dictDataQuery->save()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '添加字典数据错误'); + } return $this->successByMessage('添加字典数据成功'); } /** - * 获取单个字典数据信息 + * 获取编辑数据 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="edit/{id}", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'edit/{id}', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function edit(int $id) { $dictDataInfo = DictData::findById($id); - if (empty($dictDataInfo)) $this->throwExp(StatusCode::ERR_USER_ABSENT, '获取字典信息失败'); - - return $this->success([ - 'list' => $dictDataInfo - ]); + if (empty($dictDataInfo)) { + $this->throwExp(StatusCode::ERR_USER_ABSENT, '获取字典信息失败'); + } + return $this->success(['list' => $dictDataInfo]); } /** - * @Explanation(content="修改字典数据信息") + * 修改 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="update/{id}", methods="put") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '修改字典数据')] + #[RequestMapping(path: 'update/{id}', methods: array('PUT'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function update(int $id) { if (empty($id)) $this->throwExp(StatusCode::ERR_VALIDATION, 'ID 不能为空'); - $postData = $this->request->all(); $params = [ - 'dict_type' => $postData['dict_type'] ?? '', - 'dict_label' => $postData['dict_label'] ?? '', - 'dict_value' => $postData['dict_value'] ?? '', - 'dict_sort' => $postData['dict_sort'] ?? 1, - 'status' => $postData['status'] ?? 1, - 'remark' => $postData['remark'] ?? '', + 'dict_type' => $this->params('dict_type') ?? '', + 'dict_label' => $this->params('dict_label') ?? '', + 'dict_value' => $this->params('dict_value') ?? '', + 'dict_sort' => $this->params('dict_sort') ?? 1, + 'status' => $this->params('status') ?? 1, + 'remark' => $this->params('remark') ?? '' ]; - //配置验证 $rules = [ 'dict_type' => 'required', 'dict_label' => 'required', - 'dict_value' => 'required', + 'dict_value' => 'required' ]; - //错误信息 $message = [ 'dict_type.required' => '[dict_type]缺失', 'dict_label.required' => '[dict_label]缺失', - 'dict_value.required' => '[dict_value]缺失', + 'dict_value.required' => '[dict_value]缺失' ]; $this->verifyParams($params, $rules, $message); - $dictDataQuery = DictData::findById($id); $dictDataQuery->dict_type = $params['dict_type']; $dictDataQuery->dict_label = $params['dict_label']; @@ -190,33 +190,42 @@ public function update(int $id) $dictDataQuery->status = $params['status']; $dictDataQuery->remark = $params['remark']; $dictDataQuery->updated_at = date('Y-m-d, H:i:s'); - if (!$dictDataQuery->save()) $this->throwExp(StatusCode::ERR_EXCEPTION, '修改字典数据错误'); - + if (!$dictDataQuery->save()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '修改字典数据错误'); + } return $this->successByMessage('修改字典数据成功'); } + /** - * @Explanation(content="删除字典数据") + * 删除 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="destroy/{id}", methods="delete") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '删除字典数据')] + #[RequestMapping(path: 'destroy/{id}', methods: array('DELETE'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function destroy(int $id) { if ($id == 0) { $idArr = $this->request->input('id') ?? []; - if (empty($idArr) || !is_array($idArr)) $this->throwExp(StatusCode::ERR_VALIDATION, '参数类型不正确'); - if (!DictData::whereIn('dict_code', $idArr)->delete()) $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); - }else { - if (!intval($id)) $this->throwExp(StatusCode::ERR_VALIDATION, '参数错误'); - if (!DictData::destroy($id)) $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + if (empty($idArr) || !is_array($idArr)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '参数类型不正确'); + } + if (!DictData::whereIn('dict_code', $idArr)->delete()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + } + } else { + if (!intval($id)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '参数错误'); + } + if (!DictData::destroy($id)) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + } } - return $this->successByMessage('删除定时任务成功'); } - } \ No newline at end of file diff --git a/app/Controller/System/DictTypeController.php b/app/Controller/System/DictTypeController.php index b5edc34..fd99eea 100644 --- a/app/Controller/System/DictTypeController.php +++ b/app/Controller/System/DictTypeController.php @@ -1,7 +1,6 @@ dictType->newQuery(); $status = $this->request->input('status') ?? ''; $dictName = $this->request->input('dict_name') ?? ''; $dictType = $this->request->input('dict_type') ?? ''; - - if (!empty($dictName)) $dictTypeQuery->where('dict_name', 'like', '%' . $dictName . '%'); - if (!empty($dictType)) $dictTypeQuery->where('dict_type', 'like', '%' . $dictType . '%'); - if (strlen($status) > 0) $dictTypeQuery->where('status', $status); - + if (!empty($dictName)) { + $dictTypeQuery->where('dict_name', 'like', '%' . $dictName . '%'); + } + if (!empty($dictType)) { + $dictTypeQuery->where('dict_type', 'like', '%' . $dictType . '%'); + } + if (strlen($status) > 0) { + $dictTypeQuery->where('status', $status); + } $total = $dictTypeQuery->count(); $dictTypeQuery = $this->pagingCondition($dictTypeQuery, $this->request->all()); - $data = $dictTypeQuery->get(); + $data = $dictTypeQuery->get()->toArray(); return $this->success([ 'list' => $data, - 'total' => $total, + 'total' => $total ]); } /** - * @Explanation(content="添加字典类型") - * @RequestMapping(path="store", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 添加 + * @Author YiYuan + * @Date 2023/12/4 + * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '添加字典类型')] + #[RequestMapping(path: 'store', methods: array('POST'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function store() { - $postData = $this->request->all(); $params = [ - 'dict_name' => $postData['dict_name'] ?? '', - 'dict_type' => $postData['dict_type'] ?? '', - 'status' => $postData['status'] ?? 1, - 'remark' => $postData['remark'] ?? '', + 'dict_name' => $this->params('dict_name') ?? '', + 'dict_type' => $this->params('dict_type') ?? '', + 'status' => $this->params('status') ?? 1, + 'remark' => $this->params('remark') ?? '' ]; - //配置验证 $rules = [ 'dict_name' => 'required|min:2|max:60|', - 'dict_type' => 'required|unique:dict_type', + 'dict_type' => 'required|unique:dict_type' ]; - //错误信息 $message = [ 'dict_name.required' => '[dict_name]缺失', 'dict_name.min' => '[dict_name]最少2位', 'dict_name.max' => '[dict_name]最多60位', 'dict_type.required' => '[dict_type]缺失', - 'dict_type.unique' => '[dict_type]已经存在', + 'dict_type.unique' => '[dict_type]已经存在' ]; $this->verifyParams($params, $rules, $message); - $dictTypeQuery = new DictType(); $dictTypeQuery->dict_name = $params['dict_name']; $dictTypeQuery->dict_type = $params['dict_type']; @@ -98,62 +96,61 @@ public function store() $dictTypeQuery->remark = $params['remark']; $dictTypeQuery->created_at = date('Y-m-d, H:i:s'); $dictTypeQuery->updated_at = date('Y-m-d, H:i:s'); - if (!$dictTypeQuery->save()) $this->throwExp(StatusCode::ERR_EXCEPTION, '添加字典类型错误'); - + if (!$dictTypeQuery->save()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '添加字典类型错误'); + } return $this->successByMessage('添加字典类型成功'); } /** - * 获取单个字典类型信息 + * 获取编辑数据 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="edit/{id}", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'edit/{id}', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function edit(int $id) { $dictTypeInfo = DictType::findById($id); - if (empty($dictTypeInfo)) $this->throwExp(StatusCode::ERR_USER_ABSENT, '获取字典信息失败'); - - return $this->success([ - 'list' => $dictTypeInfo - ]); + if (empty($dictTypeInfo)) { + $this->throwExp(StatusCode::ERR_USER_ABSENT, '获取字典信息失败'); + } + return $this->success(['list' => $dictTypeInfo]); } /** - * @Explanation(content="修改字典类型资料") + * 修改 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="update/{id}", methods="put") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '修改字典类型')] + #[RequestMapping(path: 'update/{id}', methods: array('PUT'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function update(int $id) { if (empty($id)) $this->throwExp(StatusCode::ERR_VALIDATION, 'ID 不能为空'); - $postData = $this->request->all(); $params = [ - 'dict_name' => $postData['dict_name'] ?? '', - 'dict_type' => $postData['dict_type'] ?? '', - 'status' => $postData['status'] ?? 1, - 'remark' => $postData['remark'] ?? '', + 'dict_name' => $this->params('dict_name') ?? '', + 'dict_type' => $this->params('dict_type') ?? '', + 'status' => $this->params('status') ?? 1, + 'remark' => $this->params('remark') ?? '' ]; $rules = [ 'dict_name' => 'required|min:4|max:18|', - 'dict_type' => 'required', + 'dict_type' => 'required' ]; $message = [ 'dict_name.required' => '[dict_name]缺失', 'dict_name.min' => '[dict_name]最少4位', 'dict_name.max' => '[dict_name]最多18位', - 'dict_type.required' => '[dict_type]缺失', + 'dict_type.required' => '[dict_type]缺失' ]; $this->verifyParams($params, $rules, $message); - $dictTypeQuery = DictType::findById($id); $dictTypeQuery->dict_name = $params['dict_name']; $dictTypeQuery->dict_type = $params['dict_type']; @@ -161,32 +158,38 @@ public function update(int $id) $dictTypeQuery->remark = $params['remark']; $dictTypeQuery->updated_at = date('Y-m-d, H:i:s'); if (!$dictTypeQuery->save()) $this->throwExp(StatusCode::ERR_EXCEPTION, '修改字典类型错误'); - return $this->successByMessage('修改字典类型成功'); } /** - * @Explanation(content="删除字典类型") + * 删除 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="destroy/{id}", methods="delete") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '删除字典类型')] + #[RequestMapping(path: 'destroy/{id}', methods: array('DELETE'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function destroy(int $id) { if ($id == 0) { $idArr = $this->request->input('id') ?? []; - if (empty($idArr) || !is_array($idArr)) $this->throwExp(StatusCode::ERR_VALIDATION, '参数类型不正确'); - if (!DictType::whereIn('dict_id', $idArr)->delete()) $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); - }else { - if (!intval($id)) $this->throwExp(StatusCode::ERR_VALIDATION, '参数错误'); - if (!DictType::destroy($id)) $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + if (empty($idArr) || !is_array($idArr)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '参数类型不正确'); + } + if (!DictType::whereIn('dict_id', $idArr)->delete()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + } + } else { + if (!intval($id)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '参数错误'); + } + if (!DictType::destroy($id)) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + } } - - return $this->successByMessage('删除定时任务成功'); + return $this->successByMessage('删除成功'); } - } \ No newline at end of file diff --git a/app/Controller/System/GlobalConfigController.php b/app/Controller/System/GlobalConfigController.php index c615ba8..5b8cf57 100644 --- a/app/Controller/System/GlobalConfigController.php +++ b/app/Controller/System/GlobalConfigController.php @@ -1,7 +1,6 @@ globalConfig->newQuery(); $name = $this->request->input('name') ?? ''; $keyName = $this->request->input('key_name') ?? ''; $type = $this->request->input('type') ?? ''; - - if (!empty($name)) $globalConfigQuery->where('name', 'like', '%'. $name . '%'); - if (!empty($keyName)) $globalConfigQuery->where('key_name', 'like', '%'. $keyName . '%'); - if (!empty($type)) $globalConfigQuery->where('type', $type); - + if (!empty($name)) { + $globalConfigQuery->where('name', 'like', '%' . $name . '%'); + } + if (!empty($keyName)) { + $globalConfigQuery->where('key_name', 'like', '%' . $keyName . '%'); + } + if (!empty($type)) { + $globalConfigQuery->where('type', $type); + } $total = $globalConfigQuery->count(); $globalConfigQuery->orderBy('created_at', 'desc'); $globalConfigQuery = $this->pagingCondition($globalConfigQuery, $this->request->all()); - $data = $globalConfigQuery->get(); - + $data = $globalConfigQuery->get()->toArray(0); return $this->success([ 'list' => $data, - 'total' => $total, + 'total' => $total ]); } /** - * @Explanation(content="添加全局参数") - * @RequestMapping(path="store", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 添加 + * @Author YiYuan + * @Date 2023/12/4 + * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '添加全局参数')] + #[RequestMapping(path: 'store', methods: array('POST'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function store() { - $postData = $this->request->all(); $params = [ - 'name' => $postData['name'] ?? '', - 'key_name' => $postData['key_name'] ?? '', - 'data' => $postData['data'] ?? '', - 'remark' => $postData['remark'] ?? '', - 'type' => $postData['type'] ?? '', + 'name' => $this->params('name') ?? '', + 'key_name' => $this->params('key_name') ?? '', + 'data' => $this->params('data') ?? '', + 'remark' => $this->params('remark') ?? '', + 'type' => $this->params('type') ?? '' ]; - //配置验证 $rules = [ 'name' => 'required', 'key_name' => 'required', - 'type' => 'required', + 'type' => 'required' ]; - //错误信息 $message = [ 'name.required' => '[name]缺失', 'key_name.required' => '[key_name]缺失', - 'type.required' => '[type]缺失', + 'type.required' => '[type]缺失' ]; $this->verifyParams($params, $rules, $message); - $globalConfigQuery = new GlobalConfig(); $globalConfigQuery->name = $params['name']; $globalConfigQuery->key_name = $params['key_name']; $globalConfigQuery->data = $params['data']; $globalConfigQuery->remark = $params['remark']; $globalConfigQuery->type = $params['type']; - - if (!$globalConfigQuery->save()) $this->throwExp(StatusCode::ERR_EXCEPTION, '添加全局参数错误'); - + if (!$globalConfigQuery->save()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '添加全局参数错误'); + } return $this->successByMessage('添加全局参数成功'); } /** - * 获取单个全局参数信息 + * 获取编辑数据 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="edit/{id}", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'edit/{id}', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function edit(int $id) { $globalConfigInfo = GlobalConfig::findById($id); - if (empty($globalConfigInfo)) $this->throwExp(StatusCode::ERR_USER_ABSENT, '获取全局参数失败'); - + if (empty($globalConfigInfo)) { + $this->throwExp(StatusCode::ERR_USER_ABSENT, '获取全局参数失败'); + } if ($globalConfigInfo['type'] == GlobalConfig::TYPE_BY_BOOLEAN) { $globalConfigInfo['data'] = boolval($globalConfigInfo['data']); } - - return $this->success([ - 'list' => $globalConfigInfo - ]); + return $this->success(['list' => $globalConfigInfo]); } /** - * @Explanation(content="修改全局参数信息") + * 修改 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="update/{id}", methods="put") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '修改全局参数')] + #[RequestMapping(path: 'update/{id}', methods: array('PUT'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function update(int $id) { if (empty($id)) $this->throwExp(StatusCode::ERR_VALIDATION, 'ID 不能为空'); - $postData = $this->request->all(); $params = [ - 'name' => $postData['name'] ?? '', - 'key_name' => $postData['key_name'] ?? '', - 'data' => $postData['data'] ?? '', - 'remark' => $postData['remark'] ?? '', - 'type' => $postData['type'] ?? '', - ]; - //配置验证 + 'name' => $this->params('name') ?? '', + 'key_name' => $this->params('key_name') ?? '', + 'data' => $this->params('data') ?? '', + 'remark' => $this->params('remark') ?? '', + 'type' => $this->params('type') ?? '']; $rules = [ 'name' => 'required', - 'key_name' => 'required', - 'type' => 'required', - ]; - //错误信息 + 'key_name' => 'required', 'type' => 'required']; $message = [ 'name.required' => '[name]缺失', 'key_name.required' => '[key_name]缺失', - 'type.required' => '[type]缺失', - ]; + 'type.required' => '[type]缺失']; $this->verifyParams($params, $rules, $message); - $globalConfigQuery = GlobalConfig::findById($id); $globalConfigQuery->name = $params['name']; $globalConfigQuery->key_name = $params['key_name']; $globalConfigQuery->data = $params['data']; $globalConfigQuery->remark = $params['remark']; $globalConfigQuery->type = $params['type']; - - if (!$globalConfigQuery->save()) $this->throwExp(StatusCode::ERR_EXCEPTION, '修改全局参数错误'); - + if (!$globalConfigQuery->save()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '修改全局参数错误'); + } return $this->successByMessage('修改全局参数成功'); } /** - * @Explanation(content="删除全局参数") + * 删除 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="destroy/{id}", methods="delete") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '删除全局参数')] + #[RequestMapping(path: 'destroy/{id}', methods: array('DELETE'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function destroy(int $id) { if ($id == 0) { $idArr = $this->request->input('id') ?? []; - if (empty($idArr) || !is_array($idArr)) $this->throwExp(StatusCode::ERR_VALIDATION, '参数类型不正确'); - if (!GlobalConfig::whereIn('id', $idArr)->delete()) $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); - }else { - if (!intval($id)) $this->throwExp(StatusCode::ERR_VALIDATION, '参数错误'); - if (!GlobalConfig::destroy($id)) $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + if (empty($idArr) || !is_array($idArr)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '参数类型不正确'); + } + if (!GlobalConfig::whereIn('id', $idArr)->delete()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + } + } else { + if (!intval($id)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '参数错误'); + } + if (!GlobalConfig::destroy($id)) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + } } - return $this->successByMessage('删除全局参数成功'); } - } \ No newline at end of file diff --git a/app/Controller/System/HomePageController.php b/app/Controller/System/HomePageController.php deleted file mode 100644 index d7004d0..0000000 --- a/app/Controller/System/HomePageController.php +++ /dev/null @@ -1,29 +0,0 @@ -success(); - } -} diff --git a/app/Controller/System/LoginLogController.php b/app/Controller/System/LoginLogController.php index 0c11583..e1faade 100644 --- a/app/Controller/System/LoginLogController.php +++ b/app/Controller/System/LoginLogController.php @@ -11,58 +11,60 @@ use Hyperf\HttpServer\Annotation\RequestMapping; use App\Middleware\RequestMiddleware; use App\Middleware\PermissionMiddleware; - - /** * 登陆日志 * Class LoginLogController - * @Controller(prefix="setting/log_module/login_log") * @package App\Controller\System * @Author YiYuan-Lin * @Date: 2021/3/1 */ +#[Controller(prefix: 'setting/log_module/login_log')] class LoginLogController extends AbstractController { - /** - * @Inject() - * @var LoginLog - */ - protected $loginLog; + #[Inject] + protected LoginLog $loginLog; /** - * 获取登陆日志列表 - * @RequestMapping(path="list", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 登录日志列表 + * @Author YiYuan + * @Date 2023/12/4 * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'list', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function index() { $beginTime = $this->request->input('login_date')[0] ?? ''; $endTime = $this->request->input('login_date')[1] ?? ''; - $loginIp = $this->request->input('login_ip') ?? '';; + $loginIp = $this->request->input('login_ip') ?? ''; $status = $this->request->input('status') ?? ''; $username = $this->request->input('username') ?? ''; - $loginLogQuery = $this->loginLog->newQuery(); - if (!empty($beginTime) && !empty($endTime)) $loginLogQuery->whereBetween('created_at', [$beginTime, $endTime]); - if (!empty($loginIp)) $loginLogQuery->where('login_ip', 'like', '%' . $loginIp . '%'); - if (!empty($username)) $loginLogQuery->where('username', 'like', '%' . $username . '%'); + if (!empty($beginTime) && !empty($endTime)) { + $loginLogQuery->whereBetween('created_at', [$beginTime, $endTime]); + } + if (!empty($loginIp)) { + $loginLogQuery->where('login_ip', 'like', '%' . $loginIp . '%'); + } + if (!empty($username)) { + $loginLogQuery->where('username', 'like', '%' . $username . '%'); + } if (strlen($status) > 0) { - if ($status == 0) $loginLogQuery->where('response_code', '!=', 200); - if ($status == 1) $loginLogQuery->where('response_code', 200); + if ($status == 0) { + $loginLogQuery->where('response_code', '!=', 200); + } + if ($status == 1) { + $loginLogQuery->where('response_code', 200); + } } $loginLogQuery->orderBy('login_date', 'desc'); - $total = $loginLogQuery->count(); $loginLogQuery = $this->pagingCondition($loginLogQuery, $this->request->all()); $data = $loginLogQuery->get()->toArray(); - return $this->success([ 'list' => $data, - 'total' => $total, + 'total' => $total ]); } } \ No newline at end of file diff --git a/app/Controller/System/NoticeController.php b/app/Controller/System/NoticeController.php index f15e610..a09d7cc 100644 --- a/app/Controller/System/NoticeController.php +++ b/app/Controller/System/NoticeController.php @@ -1,7 +1,6 @@ notice->newQuery(); $status = $this->request->input('status') ?? ''; $title = $this->request->input('title') ?? ''; - - if (strlen($status) > 0) $noticeQuery->where('status', $status); - if (!empty($title)) $noticeQuery->where('title', 'like', '%'. $title . '%'); - + if (strlen($status) > 0) { + $noticeQuery->where('status', $status); + } + if (!empty($title)) { + $noticeQuery->where('title', 'like', '%' . $title . '%'); + } $total = $noticeQuery->count(); $noticeQuery->with('getUserName:id,desc'); $noticeQuery->orderBy('created_at', 'desc'); $noticeQuery = $this->pagingCondition($noticeQuery, $this->request->all()); - $data = $noticeQuery->get(); - + $data = $noticeQuery->get()->toArray(); return $this->success([ 'list' => $data, - 'total' => $total, + 'total' => $total ]); } /** - * @Explanation(content="添加系统通知") - * @RequestMapping(path="store", methods="post") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) + * 添加 + * @Author YiYuan + * @Date 2023/12/4 + * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '添加公告操作')] + #[RequestMapping(path: 'store', methods: array('POST'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function store() { - $postData = $this->request->all(); $params = [ - 'title' => $postData['title'] ?? '', - 'content' => $postData['content'] ?? '', - 'status' => $postData['status'] ?? '', - 'public_time' => $postData['public_time'] ?? '', + 'title' => $this->params('title') ?? '', + 'content' => $this->params('content') ?? '', + 'status' => $this->params('status') ?? '', + 'public_time' => $this->params('public_time') ?? '' ]; - //配置验证 $rules = [ 'title' => 'required', 'status' => 'required|integer', 'content' => 'required', - 'public_time' => 'required', + 'public_time' => 'required' ]; - //错误信息 $message = [ 'title.required' => '[title]缺失', 'status.required' => '[status]缺失', 'status.integer' => '[status]类型不正确', 'content.required' => '[content]缺失', - 'public_time.required' => '[public_time]缺失', + 'public_time.required' => '[public_time]缺失' ]; $this->verifyParams($params, $rules, $message); - $noticeQuery = new Notice(); $noticeQuery->title = $params['title']; $noticeQuery->status = $params['status']; @@ -110,63 +102,59 @@ public function store() $noticeQuery->public_time = strtotime($params['public_time']); $noticeQuery->user_id = conGet('user_info')['id']; $noticeQuery->username = conGet('user_info')['desc']; - - if (!$noticeQuery->save()) $this->throwExp(StatusCode::ERR_EXCEPTION, '添加系统通知错误'); - + if (!$noticeQuery->save()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '添加系统通知错误'); + } //分发队列 - $this->queue->push(new EmailNotificationJob([ - 'title' => $params['title'], - 'content' => $params['content'], - ])); + $this->queue->push(new EmailNotificationJob(['title' => $params['title'], 'content' => $params['content']])); return $this->successByMessage('添加系统通知成功'); } /** - * 获取单个系统通知信息 + * 获取编辑数据 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="edit/{id}", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[RequestMapping(path: 'edit/{id}', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] public function edit(int $id) { $noticeInfo = Notice::findById($id); $noticeInfo->public_time = date('Y-m-d H:i:s', $noticeInfo->public_time); - if (empty($noticeInfo)) $this->throwExp(StatusCode::ERR_USER_ABSENT, '获取字典信息失败'); - - return $this->success([ - 'list' => $noticeInfo - ]); + if (empty($noticeInfo)) { + $this->throwExp(StatusCode::ERR_USER_ABSENT, '获取字典信息失败'); + } + return $this->success(['list' => $noticeInfo]); } /** - * @Explanation(content="修改系统通知信息") + * 修改公告 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="update/{id}", methods="put") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '修改公告操作')] + #[RequestMapping(path: 'update/{id}', methods: array('PUT'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function update(int $id) { if (empty($id)) $this->throwExp(StatusCode::ERR_VALIDATION, 'ID 不能为空'); - $postData = $this->request->all(); $params = [ - 'title' => $postData['title'] ?? '', - 'content' => $postData['content'] ?? '', - 'status' => $postData['status'] ?? '', - 'public_time' => $postData['public_time'] ?? '', + 'title' => $this->params('title') ?? '', + 'content' => $this->params('content') ?? '', + 'status' => $this->params('status') ?? '', + 'public_time' => $this->params('public_time') ?? '' ]; //配置验证 $rules = [ 'title' => 'required', 'status' => 'required|integer', 'content' => 'required', - 'public_time' => 'required', + 'public_time' => 'required' ]; //错误信息 $message = [ @@ -174,43 +162,49 @@ public function update(int $id) 'status.required' => '[status]缺失', 'status.integer' => '[status]类型不正确', 'content.required' => '[content]缺失', - 'public_time.required' => '[public_time]缺失', + 'public_time.required' => '[public_time]缺失' ]; $this->verifyParams($params, $rules, $message); - $noticeQuery = Notice::findById($id); $noticeQuery->title = $params['title']; $noticeQuery->status = $params['status']; $noticeQuery->content = $params['content']; $noticeQuery->public_time = strtotime($params['public_time']); - - if (!$noticeQuery->save()) $this->throwExp(StatusCode::ERR_EXCEPTION, '修改系统通知错误'); - + if (!$noticeQuery->save()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '修改系统通知错误'); + } return $this->successByMessage('修改系统通知成功'); } /** - * @Explanation(content="删除系统通知") + * 删除 + * @Author YiYuan + * @Date 2023/12/4 * @param int $id - * @RequestMapping(path="destroy/{id}", methods="delete") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) * @return \Psr\Http\Message\ResponseInterface */ + #[Explanation(content: '删除公告操作')] + #[RequestMapping(path: 'destroy/{id}', methods: array('DELETE'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function destroy(int $id) { if ($id == 0) { $idArr = $this->request->input('id') ?? []; - if (empty($idArr) || !is_array($idArr)) $this->throwExp(StatusCode::ERR_VALIDATION, '参数类型不正确'); - if (!Notice::whereIn('id', $idArr)->delete()) $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); - }else { - if (!intval($id)) $this->throwExp(StatusCode::ERR_VALIDATION, '参数错误'); - if (!Notice::destroy($id)) $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + if (empty($idArr) || !is_array($idArr)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '参数类型不正确'); + } + if (!Notice::whereIn('id', $idArr)->delete()) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + } + } else { + if (!intval($id)) { + $this->throwExp(StatusCode::ERR_VALIDATION, '参数错误'); + } + if (!Notice::destroy($id)) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + } } - return $this->successByMessage('删除系统通知成功'); } - } \ No newline at end of file diff --git a/app/Controller/System/OperateLogController.php b/app/Controller/System/OperateLogController.php index 62c67d2..196e86f 100644 --- a/app/Controller/System/OperateLogController.php +++ b/app/Controller/System/OperateLogController.php @@ -11,57 +11,61 @@ use Hyperf\HttpServer\Annotation\RequestMapping; use App\Middleware\RequestMiddleware; use App\Middleware\PermissionMiddleware; - +use Psr\Http\Message\ResponseInterface; /** * Class OperateLogController - * @Controller(prefix="setting/log_module/operate_log") * @package App\Controller\System * @Author YiYuan-Lin * @Date: 2020/11/7 */ +#[Controller(prefix: 'setting/log_module/operate_log')] class OperateLogController extends AbstractController { - /** - * @Inject() - * @var OperateLog - */ - protected $operate; + #[Inject] + protected OperateLog $operate; /** - * 获取操作日志列表 - * @RequestMapping(path="list", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) - * @return \Psr\Http\Message\ResponseInterface + * 操作日志列表 + * @Author YiYuan + * @Date 2023/12/4 + * @return ResponseInterface */ + #[RequestMapping(path: 'list', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function index() { $beginTime = $this->request->input('created_at')[0] ?? ''; $endTime = $this->request->input('created_at')[1] ?? ''; - $action = $this->request->input('action') ?? '';; + $action = $this->request->input('action') ?? ''; $operator = $this->request->input('operator') ?? ''; $status = $this->request->input('status') ?? ''; - $operateLogQuery = $this->operate->newQuery(); - if (!empty($beginTime) && !empty($endTime)) $operateLogQuery->whereBetween('created_at', [$beginTime, $endTime]); - if (!empty($action)) $operateLogQuery->where('action', 'like', '%' . $action . '%'); - if (!empty($operate)) $operateLogQuery->where('operate', 'like', '%' . $operator . '%'); + if (!empty($beginTime) && !empty($endTime)) { + $operateLogQuery->whereBetween('created_at', [$beginTime, $endTime]); + } + if (!empty($action)) { + $operateLogQuery->where('action', 'like', '%' . $action . '%'); + } + if (!empty($operate)) { + $operateLogQuery->where('operate', 'like', '%' . $operator . '%'); + } if (strlen($status) > 0) { - if ($status == 0) $operateLogQuery->where('response_code', '!=', 200); - if ($status == 1) $operateLogQuery->where('response_code', 200); + if ($status == 0) { + $operateLogQuery->where('response_code', '!=', 200); + } + if ($status == 1) { + $operateLogQuery->where('response_code', 200); + } } $operateLogQuery->orderBy('created_at', 'desc'); - $total = $operateLogQuery->count(); $operateLogQuery = $this->pagingCondition($operateLogQuery, $this->request->all()); $data = $operateLogQuery->get()->toArray(); - return $this->success([ 'list' => $data, - 'total' => $total, + 'total' => $total ]); } } \ No newline at end of file diff --git a/app/Controller/System/SystemLogController.php b/app/Controller/System/SystemLogController.php index 343f9d8..51fe49a 100644 --- a/app/Controller/System/SystemLogController.php +++ b/app/Controller/System/SystemLogController.php @@ -13,15 +13,15 @@ use Hyperf\HttpServer\Annotation\RequestMapping; use App\Middleware\RequestMiddleware; use App\Middleware\PermissionMiddleware; - +use Psr\Http\Message\ResponseInterface; /** * Class SystemLogController - * @Controller(prefix="setting/log_module/system_log") * @package App\Controller\System * @Author YiYuan-Lin * @Date: 2021/03/04 */ +#[Controller(prefix: 'setting/log_module/system_log')] class SystemLogController extends AbstractController { /** @@ -29,32 +29,31 @@ class SystemLogController extends AbstractController * @var */ protected $log_path; - /** * 错误日志正则匹配表达式 */ - const LOG_ERROR_PATTER = '/^(?.*)\|\|(?\w+)\|\|(?\w+)\|\|(.*?)\:(?.*)/m'; - + const LOG_ERROR_PATTER = '/^(?.*)\\|\\|(?\\w+)\\|\\|(?\\w+)\\|\\|(.*?)\\:(?.*)/m'; /** * SQL查询正则匹配表达式 */ const LOG_SQL_PATTER = ''; /** - * 错误日志 - * @RequestMapping(path="error_log", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) - * @return \Psr\Http\Message\ResponseInterface + * 错误日志列表 + * @Author YiYuan + * @Date 2023/12/4 + * @return void */ + #[RequestMapping(path: 'error_log', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function errorLog() { $logPath = config('log_path') . 'hyperf_error'; $fileList = SystemLogService::getInstance()->scanDirectory($logPath); - if (!$fileList) $this->throwExp(StatusCode::ERR_EXCEPTION, '该项目暂无日志记录文件'); - + if (!$fileList) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '该项目暂无日志记录文件'); + } $list = []; $total = 0; // 获取文件树形列表 @@ -62,31 +61,24 @@ public function errorLog() $total = count($files); // 循环目录查找该目录下的文件 foreach ($files as $key => $value) { - } - } - - - - /** - * 获取系统日志列表 - * @RequestMapping(path="log_path", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) - * @return \Psr\Http\Message\ResponseInterface + * 日志路径 + * @Author YiYuan + * @Date 2023/12/4 + * @return ResponseInterface */ + #[RequestMapping(path: 'log_path', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function getLogPath() { - - $fileList = SystemLogService::getInstance()->scanDirectory($this->log_path); - if (!$fileList) $this->throwExp(StatusCode::ERR_EXCEPTION, '该项目暂无日志记录文件'); - + if (!$fileList) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '该项目暂无日志记录文件'); + } // 获取文件树形列表 $fileTree = []; $dirs = $fileList['dirs']; @@ -98,83 +90,74 @@ public function getLogPath() $pattern = '/' . str_replace(["\\", "/"], "", $value) . '/'; foreach ($files as $k => $v) { $v = str_replace(["\\", "/"], "", $v); - if (preg_match($pattern, $v, $temp)) { - if (!isset($fileTree[$key]['children'])) $fileTree[$key]['children'] = []; - array_unshift($fileTree[$key]['children'], [ - 'type' => 'file', - 'path' => $files[$k], - 'dir' => substr($value, strripos($value, "/") + 1) - ]); + if (!isset($fileTree[$key]['children'])) { + $fileTree[$key]['children'] = []; + } + array_unshift($fileTree[$key]['children'], ['type' => 'file', 'path' => $files[$k], 'dir' => substr($value, strripos($value, "/") + 1)]); unset($files[$k]); - }; + } } } // 如果还有文件未匹配则为一级目录下的文件 if (!empty($files)) { $files = array_reverse($files); foreach ($files as $k => $v) { - array_push($fileTree, [ - 'type' => 'file', - 'path' => $v - ]); + array_push($fileTree, ['type' => 'file', 'path' => $v]); } } - - return $this->success([ - 'list' => $fileTree, - 'total' => count($fileTree), - ]); + return $this->success(['list' => $fileTree, 'total' => count($fileTree)]); } /** - * 获取日志文件内容 - * @RequestMapping(path="log_content", methods="get") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) - * @return \Psr\Http\Message\ResponseInterface + * 获取日志内容 + * @Author YiYuan + * @Date 2023/12/4 + * @return ResponseInterface */ + #[RequestMapping(path: 'log_content', methods: array('GET'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function getLogContent() { $path = $this->request->input('file_path') ?? ''; - if (empty($path)) $this->throwExp(StatusCode::ERR_EXCEPTION, '请选择日志文件'); - + if (empty($path)) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '请选择日志文件'); + } // 按时间降序获取内容 $content = SystemLogService::getInstance()->getLogContent($path, self::LOG_PATTER); - if (!empty($content)) $content=array_reverse($content); + if (!empty($content)) { + $content = array_reverse($content); + } $total = count($content); - // 分页 $curPage = $this->params['cur_page'] ?? 1; $pageSize = $this->params['page_size'] ?? 20; $contents = array_chunk($content, $pageSize); $content = $contents[$curPage - 1]; - - return $this->success([ - 'list' => $content, - 'total' => $total - ]); + return $this->success(['list' => $content, 'total' => $total]); } /** - * @Explanation(content="删除日志") - * @RequestMapping(path="destroy_log", methods="delete") - * @Middlewares({ - * @Middleware(RequestMiddleware::class), - * @Middleware(PermissionMiddleware::class) - * }) - * @return \Psr\Http\Message\ResponseInterface + * 删除日志 + * @Author YiYuan + * @Date 2023/12/4 + * @return ResponseInterface */ + #[Explanation(content: '删错日志操作')] + #[RequestMapping(path: 'destroy_log', methods: array('DELETE'))] + #[Middleware(middleware: 'App\\Middleware\\RequestMiddleware')] + #[Middleware(middleware: 'App\\Middleware\\PermissionMiddleware')] public function deleteLog() { $path = $this->request->input('path') ?? ''; $path = urldecode($path); - - if (!file_exists($path)) $this->throwExp(StatusCode::ERR_EXCEPTION, '文件不存在'); - if (!unlink($path)) $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); - + if (!file_exists($path)) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '文件不存在'); + } + if (!unlink($path)) { + $this->throwExp(StatusCode::ERR_EXCEPTION, '删除失败'); + } return $this->successByMessage('删除文件成功'); } } \ No newline at end of file diff --git a/app/Controller/User/IndexController.php b/app/Controller/User/IndexController.php deleted file mode 100644 index 5fc1993..0000000 --- a/app/Controller/User/IndexController.php +++ /dev/null @@ -1,34 +0,0 @@ -getMessage() . ':: FILE:' . $throwable->getFile() . ':: LINE: ' . $throwable->getLine(); @@ -72,7 +60,6 @@ public function handle(Throwable $throwable, ResponseInterface $response) return $this->error($throwable->getCode(), $throwable->getMessage()); } return $this->error(500, $message); - } public function isValid(Throwable $throwable): bool diff --git a/app/Foundation/Annotation/Explanation.php b/app/Foundation/Annotation/Explanation.php index 1659fd9..b98fbed 100644 --- a/app/Foundation/Annotation/Explanation.php +++ b/app/Foundation/Annotation/Explanation.php @@ -3,6 +3,7 @@ namespace App\Foundation\Annotation; +use Attribute; use Hyperf\Di\Annotation\AbstractAnnotation; use Hyperf\Di\Annotation\AnnotationCollector; @@ -11,11 +12,13 @@ * @Annotation * @Target({"METHOD"}) */ + +#[Attribute(Attribute::TARGET_METHOD)] class Explanation extends AbstractAnnotation { /** * @var string */ - public $content = ''; + public string $content = ''; } diff --git a/app/Foundation/Aspect/OperateLogAspect.php b/app/Foundation/Aspect/OperateLogAspect.php index e396c07..6f588a6 100644 --- a/app/Foundation/Aspect/OperateLogAspect.php +++ b/app/Foundation/Aspect/OperateLogAspect.php @@ -12,22 +12,21 @@ /** * 操作日志类切面(用于记录操作日志) - * @Aspect + * @Author YiYuan + * @Date 2023/12/1 + * Class OperateLogAspect */ +#[Aspect] class OperateLogAspect extends AbstractAspect { - /** - * @Inject() - * @var RequestInterface - */ - protected $request; + #[Inject] + protected RequestInterface $request; // 要切入的类,可以多个,亦可通过 :: 标识到具体的某个方法,通过 * 可以模糊匹配 - public $classes = [ - ]; + public array $classes = []; // 要切入的注解,具体切入的还是使用了这些注解的类,仅可切入类注解和类方法注解 - public $annotations = [ + public array $annotations = [ Explanation::class ]; @@ -39,6 +38,7 @@ class OperateLogAspect extends AbstractAspect */ public function process(ProceedingJoinPoint $proceedingJoinPoint) { + var_dump(1); // 在调用前进行某些处理 $logData = OperateLogService::getInstance()->collectLogInfo(); diff --git a/app/Foundation/Handler/LogFileHandler.php b/app/Foundation/Handler/LogFileHandler.php index 139032c..29a3010 100644 --- a/app/Foundation/Handler/LogFileHandler.php +++ b/app/Foundation/Handler/LogFileHandler.php @@ -6,6 +6,7 @@ use Monolog\Handler\RotatingFileHandler; use Monolog\Logger; +use Monolog\LogRecord; /** * LogFileHandler @@ -28,10 +29,10 @@ class LogFileHandler extends RotatingFileHandler /** * 改写父类方法,增加判断日志输出,框架日志 - * @param array $record + * @param array|LogRecord $record * @return bool */ - public function handle(array $record): bool + public function handle(array|\Monolog\LogRecord $record): bool { if (!$this->isHandling($record)) { return false; @@ -57,10 +58,10 @@ public function handle(array $record): bool /** * 重写该方法,作用改变日志的存储文件的方式。 * 将debug,error,单独存储,其它的按着原来规则 - * @param array $record + * @param array|LogRecord $record * @return bool */ - public function isHandling(array $record) : bool + public function isHandling(array|LogRecord $record) : bool { switch ($record['level']) { case Logger::DEBUG: diff --git a/app/Foundation/Helpers/app.php b/app/Foundation/Helpers/app.php index 9bf9d5f..409f603 100644 --- a/app/Foundation/Helpers/app.php +++ b/app/Foundation/Helpers/app.php @@ -28,7 +28,7 @@ function isStdoutLog(string $level) * @return mixed */ function conSet(string $id, $value) { - return \Hyperf\Utils\Context::set($id, $value); + return \Hyperf\Context\Context::set($id, $value); } } @@ -40,6 +40,6 @@ function conSet(string $id, $value) { * @return mixed */ function conGet(string $id, $default = null) { - return \Hyperf\Utils\Context::get($id, $default); + return \Hyperf\Context\Context::get($id, $default); } } \ No newline at end of file diff --git a/app/Foundation/Helpers/array.php b/app/Foundation/Helpers/array.php index 60ca302..16c4589 100644 --- a/app/Foundation/Helpers/array.php +++ b/app/Foundation/Helpers/array.php @@ -122,4 +122,24 @@ function arrayToTree($data, $pkName='id', $pIdName='parent_id', $childName='chil } return $returnData; } +} + +if (!function_exists('arrayToXml')) { + /** + * 数组转XML + * @param array $data + * @return string + */ + function arrayToXml(array $data){ + $xml = ""; + foreach ($data as $key => $val) { + if (is_array($val)) { + $xml .= "<" . $key . ">" . arrayToXml($val) . ""; + } else { + $xml .= "<" . $key . ">" . $val . ""; + } + } + $xml .= ""; + return $xml; + } } \ No newline at end of file diff --git a/app/Foundation/Helpers/curl.php b/app/Foundation/Helpers/curl.php index dde7951..27796d5 100644 --- a/app/Foundation/Helpers/curl.php +++ b/app/Foundation/Helpers/curl.php @@ -30,40 +30,50 @@ function curl_get($apiUrl = '', $sendData = [], $header = [], $cookie = '') } } -if (!function_exists('fetch_url')) { - function fetch_url($url, $type = 0,$post = '',$other_curl_opt = array(), $try_num = 0, $timeout=10, $http_status=0){ - $curl_opt = array( - CURLOPT_URL => $url, - CURLOPT_AUTOREFERER => TRUE, - CURLOPT_RETURNTRANSFER => TRUE, - CURLOPT_SSL_VERIFYPEER => FALSE, - CURLOPT_SSL_VERIFYHOST => FALSE, - CURLOPT_CONNECTTIMEOUT => 30, //秒 - CURLOPT_TIMEOUT => $timeout, //The maximum number of seconds to allow cURL functions to execute. - ); - if($type == 1){ - $curl_opt[CURLOPT_POST] = TRUE; - $curl_opt[CURLOPT_POSTFIELDS] = $post;//username=abc&passwd=bcd,也可以为数组array('username'=>'abc','passwd'=>'bcd') +if (!function_exists('curl_post')) { + /** + * CURL post请求 + * @param $apiUrl + * @param $sendData + * @param array $header + * @param array $cookIe + * @param bool $isReturnResponse + * @return mixed + * @throws Exception + */ + function curl_post($apiUrl, $sendData, array $header = [], array $cookIe = [], $isReturnResponse = false) + { + $curl = curl_init(); + //判断请求头部,如果为空,默认Json传输 + if (empty($header)){ + $header[] = 'Content-Type:application/json'; + curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($sendData, JSON_UNESCAPED_UNICODE)); + } else { + curl_setopt($curl, CURLOPT_POSTFIELDS, $sendData); } + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST'); + curl_setopt($curl, CURLOPT_URL, $apiUrl); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_MAXREDIRS, 10); + curl_setopt($curl, CURLOPT_TIMEOUT, 0); + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($curl, CURLOPT_HTTPHEADER, $header); + if (!empty($cookIe)) curl_setopt($curl,CURLOPT_COOKIE, $cookIe); - if($other_curl_opt) - foreach ($other_curl_opt as $key => $val) - $curl_opt[$key] = $val; + $response = curl_exec($curl); + if (empty($response)) Throw new Exception(curl_error($curl),\App\Constants\StatusCode::ERR_SERVER); + curl_close($curl); - $ch = curl_init(); //初始化curl会话 - curl_setopt_array($ch, $curl_opt); //以数组的形式为curl设置会话参数 - $contents = curl_exec($ch); //执行curl会话 - if($http_status) $http_status = curl_getinfo($ch,CURLINFO_HTTP_CODE); - $err = curl_error($ch); - curl_close($ch); //关闭curl会话,它唯一的参数是curl_init()函数返回的句柄 - if(!empty($err)){ - return $err; - }else{ - if($http_status){ - return $http_status; - }else{ - return $contents; - } + $result = json_decode($response, true); + if (is_null($result)) { + \App\Foundation\Facades\Log::curlLog()->info($response); + Throw new Exception('接口地址:' . $apiUrl . ' 接口返回结果不是json格式', \App\Constants\StatusCode::ERR_SERVER); } + + if ($isReturnResponse) return $response; + + return $result; } -} +} \ No newline at end of file diff --git a/app/Foundation/Helpers/functions.php b/app/Foundation/Helpers/functions.php index eaf30fc..b0f5dc6 100644 --- a/app/Foundation/Helpers/functions.php +++ b/app/Foundation/Helpers/functions.php @@ -1,4 +1,7 @@ getHeaders()['x-real-ip'][0]; + return $request->getHeaders()['x-real-ip'][0] ?? ''; } } @@ -171,3 +174,59 @@ function is_true($val, $return_null=false){ return ( $boolval===null && !$return_null ? false : $boolval ); } } + +if (!function_exists('getClientIp')) { + /** + * 获取客户端请求的IP + * @return mixed|string + */ + function getClientIp(\Hyperf\HttpServer\Contract\RequestInterface $request){ + $res = $request->getServerParams(); + if(isset($res['http_client_ip'])){ + return $res['http_client_ip']; + }elseif(isset($res['http_x_real_ip'])){ + return $res['http_x_real_ip']; + }elseif(isset($res['http_x_forwarded_for'])){ + //部分CDN会获取多层代理IP,所以转成数组取第一个值 + $arr = explode(',',$res['http_x_forwarded_for']); + return $arr[0]; + }else{ + return $res['remote_addr']; + } + } +} + +if (!function_exists('getRealIp')) { + /** + * 获取客户端真实IP + * @return string + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface + */ + function getRealIp(): string + { + $request = \Hyperf\Context\ApplicationContext::getContainer()->get(RequestInterface::class); + $headers = $request->getHeaders(); + + if(isset($headers['x-forwarded-for'][0]) && !empty($headers['x-forwarded-for'][0])) { + return $headers['x-forwarded-for'][0]; + } elseif (isset($headers['x-real-ip'][0]) && !empty($headers['x-real-ip'][0])) { + return $headers['x-real-ip'][0]; + } + + $serverParams = $request->getServerParams(); + return $serverParams['remote_addr'] ?? ''; + } +} + +if (!function_exists('mic_time')) { + /** + * 获取时间戳(毫秒) + * @return false|string + */ + function mic_time() { + list($msec, $sec) = explode(' ', microtime()); + $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000); + return substr($msectime,0,13); + } +} diff --git a/app/Foundation/Helpers/xor.php b/app/Foundation/Helpers/xor.php new file mode 100644 index 0000000..3b4703f --- /dev/null +++ b/app/Foundation/Helpers/xor.php @@ -0,0 +1,55 @@ +response->json($this->formatResponse($data, $message)); } diff --git a/app/Foundation/Traits/ParamsTrait.php b/app/Foundation/Traits/ParamsTrait.php new file mode 100644 index 0000000..5cc2cb4 --- /dev/null +++ b/app/Foundation/Traits/ParamsTrait.php @@ -0,0 +1,51 @@ +request->all(); + + return $this->request->all()[$queryString] ?? null; + } + + /** + * 获取当前用户 + * Date 2022/10/10 + * Author YiYuan + * @return array + */ + public function user() : array + { + return conGet('user_info') ?? []; + } + + /** + * 获取请求IP + * @Author YiYuan + * @Date 2023/12/4 + * @return string + */ + protected function ip() : string + { + return conGet('request_ip') ?? ''; + } +} diff --git a/app/Foundation/Traits/QueryTrait.php b/app/Foundation/Traits/QueryTrait.php index 783907e..6fa78da 100644 --- a/app/Foundation/Traits/QueryTrait.php +++ b/app/Foundation/Traits/QueryTrait.php @@ -22,8 +22,7 @@ public function pagingCondition($query, $params) $offset = ($cur_page- 1) * $page_size; $limit = $page_size; - $query = $query->offset($offset)->limit($limit); - return $query; + return $query->offset($offset)->limit($limit); } } diff --git a/app/Foundation/Traits/Singleton.php b/app/Foundation/Traits/Singleton.php index 3e3953a..7c00cea 100644 --- a/app/Foundation/Traits/Singleton.php +++ b/app/Foundation/Traits/Singleton.php @@ -8,7 +8,7 @@ namespace App\Foundation\Traits; -use Hyperf\Utils\Context; +use Hyperf\Context\Context; /** * 构建单例基类 diff --git a/app/Foundation/Traits/ValidationTrait.php b/app/Foundation/Traits/ValidationTrait.php index 114496e..1e76e30 100644 --- a/app/Foundation/Traits/ValidationTrait.php +++ b/app/Foundation/Traits/ValidationTrait.php @@ -3,9 +3,6 @@ use App\Constants\StatusCode; use App\Exception\Handler\BusinessException; -use Hyperf\HttpServer\Contract\RequestInterface; -use Hyperf\HttpServer\Contract\ResponseInterface; -use Psr\Container\ContainerInterface; use Hyperf\Di\Annotation\Inject; use Hyperf\Validation\Contract\ValidatorFactoryInterface; @@ -16,29 +13,8 @@ */ trait ValidationTrait { - /** - * @Inject - * @var ContainerInterface - */ - protected $container; - - /** - * @Inject - * @var RequestInterface - */ - protected $request; - - /** - * @Inject - * @var ResponseInterface - */ - protected $response; - - /** - * @Inject() - * @var ValidatorFactoryInterface - */ - protected $validationFactory; + #[Inject] + protected ValidatorFactoryInterface $validationFactory; /** * 验证异常 diff --git a/app/Foundation/Utils/IP.php b/app/Foundation/Utils/IP.php new file mode 100644 index 0000000..53fc931 --- /dev/null +++ b/app/Foundation/Utils/IP.php @@ -0,0 +1,116 @@ +info('获取IP位置失败:' . $e->getMessage()); + return null; + } + } + + /** + * 查询位置 + * @Author YiYuan + * @Date 2023/11/7 + * @param string $ip + * @return string + * @throws \Exception + */ + public static function search(string $ip) : string + { + return self::instance()->search($ip) ?? '未知'; + } + + /** + * 省份 + * @Author YiYuan + * @Date 2023/11/7 + * @param string $ip + * @return mixed|string + * @throws \Exception + */ + public static function province(string $ip) + { + $province = explode('|', self::search($ip))[2] ?? '未知'; + + if (empty($province)) return '未知'; + return $province; + } + + /** + * 国家 + * @Author YiYuan + * @Date 2023/11/7 + * @param string $ip + * @return mixed|string + * @throws \Exception + */ + public static function country(string $ip) + { + return explode('|', self::search($ip))[0] ?? '未知'; + } + + /** + * 城市 + * @Author YiYuan + * @Date 2023/11/7 + * @param string $ip + * @return mixed|string + * @throws \Exception + */ + public static function city(string $ip) + { + $city = explode('|', self::search($ip))[3] ?? '未知'; + + if (empty($city)) return '未知'; + return $city; + } +} \ No newline at end of file diff --git a/app/Foundation/Utils/Rsa.php b/app/Foundation/Utils/Rsa.php new file mode 100644 index 0000000..a266d68 --- /dev/null +++ b/app/Foundation/Utils/Rsa.php @@ -0,0 +1,93 @@ +SmsSdkAppId = getenv("SMS_SDK_APPID") ?? ''; + + $req->SignName = $config['sign_name'] ?? '宾果网络科技'; + + $req->TemplateId = $config['template_id'] ?? ''; + + $req->TemplateParamSet = $config['template_param_set'] ?? []; + + $req->PhoneNumberSet = $config['phone_number_set'] ?? []; + + // 通过client对象调用SendSms方法发起请求。注意请求方法名与请求对象是对应的 + // 返回的resp是一个SendSmsResponse类的实例,与请求对象对应 + $resp = $client->SendSms($req); + $resArr = json_decode($resp->toJsonString(),true); + + if (!empty($resArr) && !empty($resArr['SendStatusSet']) && !empty($resArr['SendStatusSet'][0]) && is_array($resArr['SendStatusSet'][0])){ + if ($resArr['SendStatusSet'][0]['Code'] == 'Ok') return true; + Log::logicalError()->info(json_encode($resArr)); + return false; + } + + return false; + } + catch(TencentCloudSDKException $e) { + Throw new BusinessException(500, $e->getMessage()); + } + } +} + diff --git a/app/Job/Bilibili/SyncVideoFromUpUserJob.php b/app/Job/Bilibili/SyncVideoFromUpUserJob.php index c67919c..4030ec1 100644 --- a/app/Job/Bilibili/SyncVideoFromUpUserJob.php +++ b/app/Job/Bilibili/SyncVideoFromUpUserJob.php @@ -26,7 +26,7 @@ class SyncVideoFromUpUserJob extends Job * 任务执行失败后的重试次数,即最大执行次数为 $maxAttempts+1 次 * @var int */ - protected $maxAttempts = 2; + protected int $maxAttempts = 2; public function __construct($params) { diff --git a/app/Job/Bilibili/UpUserInfoRecordJob.php b/app/Job/Bilibili/UpUserInfoRecordJob.php index 540b72d..4621533 100644 --- a/app/Job/Bilibili/UpUserInfoRecordJob.php +++ b/app/Job/Bilibili/UpUserInfoRecordJob.php @@ -24,7 +24,7 @@ class UpUserInfoRecordJob extends Job * 任务执行失败后的重试次数,即最大执行次数为 $maxAttempts+1 次 * @var int */ - protected $maxAttempts = 2; + protected int $maxAttempts = 2; public function __construct($params) { diff --git a/app/Job/Bilibili/VideoInfoRecordJob.php b/app/Job/Bilibili/VideoInfoRecordJob.php index 6597210..9782685 100644 --- a/app/Job/Bilibili/VideoInfoRecordJob.php +++ b/app/Job/Bilibili/VideoInfoRecordJob.php @@ -25,7 +25,7 @@ class VideoInfoRecordJob extends Job * 任务执行失败后的重试次数,即最大执行次数为 $maxAttempts+1 次 * @var int */ - protected $maxAttempts = 2; + protected int $maxAttempts = 2; public function __construct($params) { diff --git a/app/Job/EmailNotificationJob.php b/app/Job/EmailNotificationJob.php index 36eca39..14d3591 100644 --- a/app/Job/EmailNotificationJob.php +++ b/app/Job/EmailNotificationJob.php @@ -25,7 +25,7 @@ class EmailNotificationJob extends Job * * @var int */ - protected $maxAttempts = 2; + protected int $maxAttempts = 2; public function __construct($params) { diff --git a/app/Listener/DbQueryExecutedListener.php b/app/Listener/DbQueryExecutedListener.php index 8e6522f..6122285 100644 --- a/app/Listener/DbQueryExecutedListener.php +++ b/app/Listener/DbQueryExecutedListener.php @@ -44,9 +44,9 @@ public function listen(): array } /** - * @param QueryExecuted $event + * @param object $event */ - public function process(object $event) + public function process(object $event) : void { if ($event instanceof QueryExecuted) { $sql = $event->sql; diff --git a/app/Mail/VersionUpdate.php b/app/Mail/VersionUpdate.php deleted file mode 100644 index 4e9e110..0000000 --- a/app/Mail/VersionUpdate.php +++ /dev/null @@ -1,38 +0,0 @@ -Hi,你好 林益远,请点击下面的链接激活你的账号

- 立即激活 -ht; - return $this->subject('ZONGSCAN-账号注册激活链接')->htmlBody($html1); - } -} diff --git a/app/Middleware/CheckMaintainMiddleware.php b/app/Middleware/CheckMaintainMiddleware.php index de49e06..7c4b602 100644 --- a/app/Middleware/CheckMaintainMiddleware.php +++ b/app/Middleware/CheckMaintainMiddleware.php @@ -9,7 +9,7 @@ use App\Model\System\GlobalConfig; use App\Service\Auth\UserService; use Hyperf\Di\Annotation\Inject; -use Hyperf\Utils\Context; +use Hyperf\Context\Context; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; @@ -26,7 +26,7 @@ class CheckMaintainMiddleware implements MiddlewareInterface { public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { - $writeRoute = ['/common/sys_config', '/common/auth/verification_code', '/auth/login', '/auth/register', '/test', ]; + $writeRoute = ['/common/sys_config', '/common/auth/verification_code', '/auth/login', '/auth/register', '/test']; if (in_array($request->getUri()->getPath(), $writeRoute)) return $handler->handle($request); //获取当前用户 diff --git a/app/Middleware/CorsMiddleware.php b/app/Middleware/CorsMiddleware.php index 5be9958..43681c1 100644 --- a/app/Middleware/CorsMiddleware.php +++ b/app/Middleware/CorsMiddleware.php @@ -4,7 +4,7 @@ namespace App\Middleware; -use Hyperf\Utils\Context; +use Hyperf\Context\Context; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; diff --git a/app/Middleware/PermissionMiddleware.php b/app/Middleware/PermissionMiddleware.php index 4ad7f58..1411b4b 100644 --- a/app/Middleware/PermissionMiddleware.php +++ b/app/Middleware/PermissionMiddleware.php @@ -11,7 +11,7 @@ use Hyperf\HttpServer\Contract\RequestInterface; use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse; use Hyperf\HttpServer\Router\Dispatched; -use Hyperf\Utils\Context; +use Hyperf\Context\Context; use Phper666\JWTAuth\JWT; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseInterface; @@ -24,22 +24,22 @@ class PermissionMiddleware implements MiddlewareInterface /** * @var ContainerInterface */ - protected $container; + protected ContainerInterface $container; /** * @var RequestInterface */ - protected $request; + protected RequestInterface $request; /** * @var HttpResponse */ - protected $response; + protected HttpResponse $response; /** * @var JWT */ - protected $jwt; + protected JWT $jwt; public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request, JWT $jwt) { diff --git a/app/Middleware/RequestMiddleware.php b/app/Middleware/RequestMiddleware.php index 7cda289..68440f0 100644 --- a/app/Middleware/RequestMiddleware.php +++ b/app/Middleware/RequestMiddleware.php @@ -9,7 +9,7 @@ use App\Foundation\Facades\Log; use App\Service\Auth\UserService; use Hyperf\HttpServer\Contract\RequestInterface; -use Hyperf\Utils\Context; +use Hyperf\Context\Context; use Phper666\JWTAuth\Exception\TokenValidException; use Phper666\JWTAuth\Exception\JWTException; use Phper666\JWTAuth\JWT; @@ -22,21 +22,17 @@ class RequestMiddleware implements MiddlewareInterface { - /** - * @var ContainerInterface - */ - protected $container; + protected ContainerInterface $container; - /** - * @var RequestInterface - */ - protected $request; + protected RequestInterface $request; + + protected JWT $jwt; /** - * @var JWT + * @param ContainerInterface $container + * @param RequestInterface $request + * @param JWT $jwt */ - protected $jwt; - public function __construct(ContainerInterface $container, RequestInterface $request, JWT $jwt) { $this->container = $container; @@ -57,13 +53,18 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface $requireParams = $this->request->all(); //记录请求参数日志记录 if (config('request_log')) Log::requestLog()->info('请求参数:' . json_encode($requireParams)); + + conSet('request_ip', getRealIp()); + conSet('server_params', $this->request->getServerParams()); + conSet('request_start_time', getMillisecond()); + try { $isValidToken = false; // 根据具体业务判断逻辑走向,这里假设用户携带的token有效 $token = $request->getHeaderLine('Authorization') ?? ''; if (strlen($token) > 0) { $token = JWTUtil::handleToken($token); - if ($token !== false && $this->jwt->checkToken($token)) $isValidToken = true; + if ($token !== false && $this->jwt->verifyToken($token)) $isValidToken = true; //如果校验成功 if ($isValidToken) { @@ -78,12 +79,10 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface //我们在这里需要做的是刷新该用户的 token 并将它添加到响应头中 try { // 刷新用户的 token - $token = $request->getHeaderLine('Authorization') ?? ''; - $token = JWTUtil::handleToken($token); - $tokenData = $this->jwt->getParserData($token); - + $tokenData = JWTUtil::getParserData($this->request); + $tokenData = objToArray($tokenData); //判断token是否在缓存时间内,如果是刷新token - if (time()-$tokenData['exp'] < intval(config('jwt.ttl_cache'))) { + if (time() - strtotime($tokenData['exp']['date']) < intval(env('JWT_TTL_CACHE', 86400))) { $token = $this->jwt->refreshToken(); //从协程获取全局的Response 对象, 并将刷新TOKEN写进去头部返回给前端供前端刷新token $response = conGet(ResponseInterface::class); diff --git a/app/Middleware/WsMiddleware.php b/app/Middleware/WsMiddleware.php index ae5ef9a..874e452 100644 --- a/app/Middleware/WsMiddleware.php +++ b/app/Middleware/WsMiddleware.php @@ -5,10 +5,12 @@ namespace App\Middleware; use App\Model\Auth\User; +use Hyperf\Di\Annotation\Inject; use Hyperf\HttpServer\Contract\RequestInterface; -use Hyperf\Utils\Context; +use Hyperf\Context\Context; use Hyperf\WebSocketServer\Security; use Phper666\JWTAuth\JWT; +use Phper666\JWTAuth\Util\JWTUtil; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; @@ -30,20 +32,14 @@ class WsMiddleware implements MiddlewareInterface private const HANDLE_BAD_REQUEST_CODE = 400; - /** - * @var ContainerInterface - */ - protected $container; + #[Inject] + protected JWT $jwt; - /** - * @var RequestInterface - */ - protected $request; + #[Inject] + protected ContainerInterface $container; - /** - * @var JWT - */ - protected $jwt; + #[Inject] + protected RequestInterface $request; public function __construct(ContainerInterface $container, RequestInterface $request, JWT $jwt) { @@ -62,29 +58,29 @@ public function __construct(ContainerInterface $container, RequestInterface $req */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { - $isValidToken = false; - $response = Context::get(ResponseInterface::class); - $request = Context::get(ServerRequestInterface::class); - $token = $request->getHeaderLine(Security::SEC_WEBSOCKET_PROTOCOL) ?? ''; + $isValidToken = false; + $response = Context::get(ResponseInterface::class); + $request = Context::get(ServerRequestInterface::class); + $token = $request->getHeaderLine(Security::SEC_WEBSOCKET_PROTOCOL) ?? ''; - try { - if (strlen($token) > 0 && $this->jwt->checkToken($token)) $isValidToken = true; - } catch (Throwable $e) { - return $response - ->withStatus(self::HANDLE_BAD_REQUEST_CODE); - } + try { + if (strlen($token) > 0 && $this->jwt->verifyToken($token)) $isValidToken = true; + } catch (Throwable $e) { + return $response + ->withStatus(self::HANDLE_BAD_REQUEST_CODE); + } - if ($isValidToken) { - $jwtData = $this->jwt->getParserData($token); - $userInfo = User::query()->where(['id' => $jwtData['uid']])->first(); - $userInfo = objToArray($userInfo); - conSet('user_info', $userInfo); - if (!empty($request->getQueryParams()['is_reconnection'])) { - conSet('is_reconnection', true); - } - return $handler->handle($request); + if ($isValidToken) { + $jwtData = $this->jwt->getClaimsByToken($token); + $userInfo = User::query()->where(['id' => $jwtData['uid']])->first(); + $userInfo = objToArray($userInfo); + conSet('user_info', $userInfo); + if (!empty($request->getQueryParams()['is_reconnection'])) { + conSet('is_reconnection', true); } + return $handler->handle($request); + } - return $response->withStatus(self::HANDLE_FAIL_CODE); + return $response->withStatus(self::HANDLE_FAIL_CODE); } } \ No newline at end of file diff --git a/app/Model/Auth/Permission.php b/app/Model/Auth/Permission.php index e01ad24..d4ae46b 100644 --- a/app/Model/Auth/Permission.php +++ b/app/Model/Auth/Permission.php @@ -1,5 +1,6 @@ first(); } - } \ No newline at end of file diff --git a/app/Model/Auth/User.php b/app/Model/Auth/User.php index cb7218d..d1f83b4 100644 --- a/app/Model/Auth/User.php +++ b/app/Model/Auth/User.php @@ -11,44 +11,38 @@ use Hyperf\Database\Model\Events\Created; use Hyperf\Database\Model\Events\Deleted; use Hyperf\Di\Annotation\Inject; +use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; +use Psr\Container\NotFoundExceptionInterface; class User extends Model { - /** - * @Inject() - * @var ContainerInterface - */ - protected $container; + #[Inject] + protected ContainerInterface $container; use HasRoles; + /** * The table associated with the model. - * - * @var string */ - protected $table = 'users'; + protected ?string $table = 'users'; /** * The connection name for the model. - * - * @var string */ - protected $connection = 'default'; + protected ?string $connection = 'default'; /** * The attributes that are mass assignable. - * - * @var array */ - protected $fillable = []; + protected array $fillable = []; /** * The attributes that should be cast to native types. * * @var array */ - protected $casts = []; + protected array $casts = []; /** * 定义状态枚举 @@ -80,6 +74,8 @@ static function getOneByUid($id) /** * 监听用户添加事件 * @param Created $event + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ public function created(Created $event) { @@ -101,6 +97,8 @@ public function created(Created $event) /** * 监听用户删除事件 * @param Deleted $event + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ public function deleted(Deleted $event) { diff --git a/app/Model/Blog/Photo.php b/app/Model/Blog/Photo.php index 559a644..af313fe 100644 --- a/app/Model/Blog/Photo.php +++ b/app/Model/Blog/Photo.php @@ -1,11 +1,9 @@ belongsTo("App\Model\Blog\PhotoAlbum", 'photo_album', 'id'); + return $this->belongsTo("App\\Model\\Blog\\PhotoAlbum", 'photo_album', 'id'); } } \ No newline at end of file diff --git a/app/Model/Blog/PhotoAlbum.php b/app/Model/Blog/PhotoAlbum.php index 86af00b..551bbfc 100644 --- a/app/Model/Blog/PhotoAlbum.php +++ b/app/Model/Blog/PhotoAlbum.php @@ -1,11 +1,9 @@ message_id = $message['id']; $model->type = $message['type']; @@ -96,28 +86,25 @@ static function addMessage(array $message, int $receptionState = 0) $model->from_uid = $message['fromUser']['id'] ?? 0; $model->reception_state = $receptionState; $model->save(); - //添加消息到好友容器中 //self::addMessageToContainer($message['id']); - return true; } - /** * 将消息添加到个人消息容器中 * @param $messageId * @return bool */ -// static function addMessageToContainer(string $messageId) -// { -// if (empty($messageId)) return false; -// -// $messageInfo = static::query()->where('message_id', $messageId)->first(); -// if (!empty($messageId)) { -// Redis::getInstance()->hset(self::FRIEND_MESSAGE_CONTAINER_REDIS_KEY . $messageInfo['from_uid'], $messageId, json_encode($messageInfo)); -// Redis::getInstance()->hset(self::FRIEND_MESSAGE_CONTAINER_REDIS_KEY . $messageInfo['to_uid'], $messageId, json_encode($messageInfo)); -// } -// -// return true; -// } + // static function addMessageToContainer(string $messageId) + // { + // if (empty($messageId)) return false; + // + // $messageInfo = static::query()->where('message_id', $messageId)->first(); + // if (!empty($messageId)) { + // Redis::getInstance()->hset(self::FRIEND_MESSAGE_CONTAINER_REDIS_KEY . $messageInfo['from_uid'], $messageId, json_encode($messageInfo)); + // Redis::getInstance()->hset(self::FRIEND_MESSAGE_CONTAINER_REDIS_KEY . $messageInfo['to_uid'], $messageId, json_encode($messageInfo)); + // } + // + // return true; + // } } \ No newline at end of file diff --git a/app/Model/Laboratory/FriendGroup.php b/app/Model/Laboratory/FriendGroup.php index 67c1431..2710b69 100644 --- a/app/Model/Laboratory/FriendGroup.php +++ b/app/Model/Laboratory/FriendGroup.php @@ -1,11 +1,9 @@ belongsTo('App\Model\Auth\User', 'friend_id', 'id'); + public function getUser() + { + return $this->belongsTo('App\\Model\\Auth\\User', 'friend_id', 'id'); } - /** * 获取好友关系的好友备注 * @param int 发送方 $fromUid @@ -67,8 +60,9 @@ public function getUser() { */ public static function getFriendRemarkNameById(int $fromUid, int $toUid) { - if (empty($fromUid) || empty($toUid)) return ''; - + if (empty($fromUid) || empty($toUid)) { + return ''; + } return static::query()->where('uid', $toUid)->where('friend_id', $fromUid)->value('friend_remark'); } } \ No newline at end of file diff --git a/app/Model/Laboratory/Group.php b/app/Model/Laboratory/Group.php index 34c6b09..a7b3196 100644 --- a/app/Model/Laboratory/Group.php +++ b/app/Model/Laboratory/Group.php @@ -1,12 +1,10 @@ message_id = $message['id']; $model->type = $message['type']; @@ -82,16 +75,14 @@ static function addMessage(array $message, int $receptionState = 0) $model->to_group_id = $message['toContactId']; $model->from_uid = $message['fromUser']['id'] ?? 0; $model->reception_state = $receptionState; - return $model->save(); } - /** * 获取相册名 * @return \Hyperf\Database\Model\Relations\BelongsTo */ public function getFromUser() { - return $this->belongsTo("App\Model\Auth\User", 'from_uid', 'id'); + return $this->belongsTo("App\\Model\\Auth\\User", 'from_uid', 'id'); } } \ No newline at end of file diff --git a/app/Model/Laboratory/GroupRelation.php b/app/Model/Laboratory/GroupRelation.php index a972858..0361b71 100644 --- a/app/Model/Laboratory/GroupRelation.php +++ b/app/Model/Laboratory/GroupRelation.php @@ -1,12 +1,10 @@ uid = $uid; $model->group_id = $groupId; $model->is_up = 0; @@ -69,16 +62,14 @@ public static function buildRelation(int $uid, string $groupId, int $level = sel $model->level = $level; return $model->save(); } - /** * 获取用户信息 * @return \Hyperf\Database\Model\Relations\BelongsTo */ public function getUserInfo() { - return $this->belongsTo("App\Model\Auth\User", 'uid', 'id'); + return $this->belongsTo("App\\Model\\Auth\\User", 'uid', 'id'); } - /** * 根据用户ID获取群聊等级 * @param int $uid @@ -87,10 +78,11 @@ public function getUserInfo() */ public static function getLevelById(int $uid, string $groupId) { - if (empty($uid) || empty($groupId)) return false; + if (empty($uid) || empty($groupId)) { + return false; + } return static::query()->where('uid', $uid)->where('group_id', $groupId)->value('level'); } - /** * 根据ID获取用户加入组别的时间 * @param int $uid @@ -99,8 +91,6 @@ public static function getLevelById(int $uid, string $groupId) */ public static function getJoinDateById(int $uid, string $groupId) { - return static::query()->where('uid', $uid) - ->where('group_id', $groupId) - ->value('created_at'); + return static::query()->where('uid', $uid)->where('group_id', $groupId)->value('created_at'); } } \ No newline at end of file diff --git a/app/Model/Laboratory/UserApplication.php b/app/Model/Laboratory/UserApplication.php index fa24751..13d2735 100644 --- a/app/Model/Laboratory/UserApplication.php +++ b/app/Model/Laboratory/UserApplication.php @@ -1,11 +1,9 @@ find($id); } - /** * 添加数据 * @param array $data * @return bool */ - static function add(array $data = []) : bool + static function add(array $data = []) : bool { - if (empty($data)) return false; - $model = new static; - + if (empty($data)) { + return false; + } + $model = new static(); foreach ($data as $key => $value) { $model->{$key} = $value; } - - if (!$model->save()) return false; + if (!$model->save()) { + return false; + } return true; } -} +} \ No newline at end of file diff --git a/app/Model/Setting/TimedTask.php b/app/Model/Setting/TimedTask.php index 15b3579..a137d15 100644 --- a/app/Model/Setting/TimedTask.php +++ b/app/Model/Setting/TimedTask.php @@ -1,12 +1,10 @@ getNextRunDate()->format('Y-m-d H:i'); - - if (self::query()->where('id', $id)->update(['next_execute_time' => $nextExecuteTime, 'times' => $self['times'] + 1])) return true; - + if (self::query()->where('id', $id)->update(['next_execute_time' => $nextExecuteTime, 'times' => $self['times'] + 1])) { + return true; + } return false; } - } \ No newline at end of file diff --git a/app/Model/Setting/TimedTaskLog.php b/app/Model/Setting/TimedTaskLog.php index 0864f8e..9d924e4 100644 --- a/app/Model/Setting/TimedTaskLog.php +++ b/app/Model/Setting/TimedTaskLog.php @@ -1,12 +1,10 @@ belongsTo('App\Model\Auth\User', 'user_id', 'id'); + public function getUserName() + { + return $this->belongsTo('App\\Model\\Auth\\User', 'user_id', 'id'); } } \ No newline at end of file diff --git a/app/Model/System/DictData.php b/app/Model/System/DictData.php index fd826c9..e7aec78 100644 --- a/app/Model/System/DictData.php +++ b/app/Model/System/DictData.php @@ -1,11 +1,9 @@ where('key_name', $keyName)->first(); } } \ No newline at end of file diff --git a/app/Model/System/LoginLog.php b/app/Model/System/LoginLog.php index 4b39627..fca3dbd 100644 --- a/app/Model/System/LoginLog.php +++ b/app/Model/System/LoginLog.php @@ -1,11 +1,9 @@ belongsTo('App\Model\Auth\User', 'user_id', 'id'); + public function getUserName() + { + return $this->belongsTo('App\\Model\\Auth\\User', 'user_id', 'id'); } } \ No newline at end of file diff --git a/app/Model/System/OperateLog.php b/app/Model/System/OperateLog.php index 1ab3e43..8c33c7a 100644 --- a/app/Model/System/OperateLog.php +++ b/app/Model/System/OperateLog.php @@ -1,11 +1,9 @@ $user->id, //如果使用单点登录,必须存在配置文件中的sso_key的值,一般设置为用户的id 'username' => $user->username, ]; - $token = $this->jwt->getToken($userData); + $token = $this->jwt->getToken('default', $userData)->toString(); //更新用户信息 $user->last_login = time(); - $user->last_ip = getClientIp($this->request); + $user->last_ip = getRealIp(); $user->save(); $responseData = $this->respondWithToken($token); @@ -77,7 +79,10 @@ public function login(array $params) : array /** * 处理注册逻辑 * @param array $params - * @return array + * @return bool + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws \RedisException */ public function register(array $params) : bool { @@ -176,11 +181,10 @@ public function getRouters() :array 'icon' => $value['icon'], 'title' => $value['display_name'], ], - 'children' => [] ]; $routers[$value['id']]['children'] = $this->dealRouteChildren($value['children']); }else { - array_push($routers['default']['children'], [ + $routers['default']['children'][] = [ 'name' => $value['name'], 'path' => $value['url'], 'hidden' => $value['hidden'], @@ -190,7 +194,7 @@ public function getRouters() :array 'icon' => $value['icon'], 'title' => $value['display_name'], ], - ]); + ]; } } return array_values($routers); @@ -229,17 +233,16 @@ private function dealRouteChildren(array $children) : array /** * 处理TOKEN数据 - * @param $token + * @param string $token * @return array */ protected function respondWithToken(string $token) : array { - $data = [ + return [ 'access_token' => $token, 'token_type' => 'bearer', - 'expires_in' => $this->jwt->getTTL(), + 'expires_in' => $this->jwt->getTTL($token), ]; - return $data; } /** @@ -276,6 +279,4 @@ protected function getMenuList(object $user) : array 'permission_info' => $permission, ]; } - - } diff --git a/app/Service/Auth/UserService.php b/app/Service/Auth/UserService.php index 74e6939..3d32112 100644 --- a/app/Service/Auth/UserService.php +++ b/app/Service/Auth/UserService.php @@ -7,8 +7,9 @@ use App\Model\Auth\User; use Hyperf\Di\Annotation\Inject; use Hyperf\Utils\ApplicationContext; -use Hyperf\Utils\Context; +use Hyperf\Context\Context; use Phper666\JWTAuth\JWT; +use Phper666\JWTAuth\Util\JWTUtil; /** * 用户服务基础类 @@ -21,11 +22,8 @@ class UserService extends BaseService { use Singleton; - /** - * @Inject() - * @var JWT - */ - private $jwt; + #[Inject] + private JWT $jwt; /** * 根据Token获取用户的信息 @@ -33,11 +31,8 @@ class UserService extends BaseService */ public function getUserInfoByToken() : object { - //获取Token解析的数据 - $parserData = $this->jwt->getParserData(); - $userId = $parserData['uid']; + $parserData = JWTUtil::getParserData($this->request); - $userInfo = User::getOneByUid($userId); - return $userInfo; + return User::getOneByUid($parserData['uid']); } } diff --git a/app/Service/BaseService.php b/app/Service/BaseService.php index 8828384..68e98bd 100644 --- a/app/Service/BaseService.php +++ b/app/Service/BaseService.php @@ -2,9 +2,11 @@ namespace App\Service; use App\Exception\Handler\BusinessException; +use App\Foundation\Traits\ApiTrait; use Hyperf\Di\Annotation\Inject; use Hyperf\HttpServer\Contract\RequestInterface; use Hyperf\HttpServer\Contract\ResponseInterface; +use PHPUnit\Framework\MockObject\Api; /** * Class BaseService @@ -15,24 +17,14 @@ */ abstract class BaseService { - /** - * @Inject - * @var RequestInterface - */ - protected $request; - - /** - * @Inject() - * @var ResponseInterface - */ - protected $response; + use ApiTrait; /** * 抛出异常 * @param int $code * @param string $message */ - public function throwExp($code = 0, $message = '') + public function throwExp(int $code = 0, string $message = '') { if (empty($code)) $code = 500; Throw new BusinessException($code, $message); @@ -43,7 +35,7 @@ public function throwExp($code = 0, $message = '') * @param string $data * @return mixed */ - public function toArray($data = '') + public function toArray(string $data = '') { return json_decode(json_encode($data), true); } diff --git a/app/Service/Common/UploadService.php b/app/Service/Common/UploadService.php index 2c82003..6914f9f 100644 --- a/app/Service/Common/UploadService.php +++ b/app/Service/Common/UploadService.php @@ -6,17 +6,13 @@ use App\Service\BaseService; use Hyperf\Di\Annotation\Inject; use League\Flysystem\Filesystem; -use phpDocumentor\Reflection\Types\Resource_; class UploadService extends BaseService { use Singleton; - /** - * @Inject() - * @var Filesystem - */ - private $filesystem; + #[Inject] + private Filesystem $filesystem; /** * 上传图片 diff --git a/app/Service/IndexService.php b/app/Service/IndexService.php index 874821a..dcc9b14 100644 --- a/app/Service/IndexService.php +++ b/app/Service/IndexService.php @@ -5,7 +5,7 @@ use App\Foundation\Traits\Singleton; use App\Service\BaseService; use Hyperf\DbConnection\Db; -use Hyperf\Utils\Context; +use Hyperf\Context\Context; class IndexService { diff --git a/app/Service/Laboratory/FriendService.php b/app/Service/Laboratory/Ws/FriendService.php similarity index 88% rename from app/Service/Laboratory/FriendService.php rename to app/Service/Laboratory/Ws/FriendService.php index 69453e8..fa842d2 100644 --- a/app/Service/Laboratory/FriendService.php +++ b/app/Service/Laboratory/Ws/FriendService.php @@ -1,9 +1,8 @@ $fd) { if ($isExcludeSelf && $uid == $userInfo['id']) continue; - array_push($fdList, [ + $fdList[] = [ 'uid' => $uid, 'fd' => $fd - ]); + ]; } return $fdList; diff --git a/app/Service/Laboratory/GroupService.php b/app/Service/Laboratory/Ws/GroupService.php similarity index 91% rename from app/Service/Laboratory/GroupService.php rename to app/Service/Laboratory/Ws/GroupService.php index 7c6fc23..6444200 100644 --- a/app/Service/Laboratory/GroupService.php +++ b/app/Service/Laboratory/Ws/GroupService.php @@ -1,10 +1,8 @@ hget(ChatRedisKey::ONLINE_USER_FD_KEY, (string) $uid))) array_push($fdList, [ + if (!empty($fd = Redis::getInstance()->hget(ChatRedisKey::ONLINE_USER_FD_KEY, (string) $uid))) $fdList[] = [ 'uid' => $uid, 'fd' => $fd - ]); + ]; } return $fdList; } diff --git a/app/Service/Laboratory/InitService.php b/app/Service/Laboratory/Ws/InitService.php similarity index 99% rename from app/Service/Laboratory/InitService.php rename to app/Service/Laboratory/Ws/InitService.php index c71f5f9..86c0064 100644 --- a/app/Service/Laboratory/InitService.php +++ b/app/Service/Laboratory/Ws/InitService.php @@ -1,5 +1,5 @@ request->all(); //获取登陆信息 - $loginIp = getClientIp($this->request) ?? ''; - $ipAddress = FreeApi::getResult($loginIp); - $province = empty($ipAddress['province']) ? '' : $ipAddress['province']; - $city = empty($ipAddress['city']) ? '' : $ipAddress['city']; + $loginIp = getRealIp(); + $province = IP::province($loginIp); + $city = IP::city($loginIp); $loginAddress = $province . $city; $browser = get_browser_os(); $os = get_os(); @@ -44,5 +44,4 @@ public function collectLoginLogInfo() : array 'login_date' => $loginTime, ]; } - } diff --git a/app/Service/System/SystemLogService.php b/app/Service/System/SystemLogService.php index 04b6367..046e069 100644 --- a/app/Service/System/SystemLogService.php +++ b/app/Service/System/SystemLogService.php @@ -68,7 +68,6 @@ public function getLogContent($filePath, $pattern) { $content = $this->filesystem->sharedGet($filePath); preg_match_all($pattern, $content, $matches, PREG_SET_ORDER, 0); - var_dump($matches); $logs = []; foreach ($matches as $match) { diff --git a/app/Task/Laboratory/FriendWsTask.php b/app/Task/Laboratory/FriendWsTask.php index 8102c74..ca6a4b0 100644 --- a/app/Task/Laboratory/FriendWsTask.php +++ b/app/Task/Laboratory/FriendWsTask.php @@ -10,10 +10,11 @@ use App\Model\Laboratory\FriendRelation; use App\Model\Laboratory\GroupChatHistory; use App\Pool\Redis; -use App\Service\Laboratory\FriendService; -use App\Service\Laboratory\MessageService; +use App\Service\Laboratory\Ws\FriendService; +use App\Service\Laboratory\Ws\MessageService; use Hyperf\Database\Model\Model; use Hyperf\Di\Annotation\Inject; +use Hyperf\WebSocketServer\Sender; /** * 好友消息传递异步任务 @@ -24,11 +25,8 @@ */ class FriendWsTask { - /** - * @Inject() - * @var \Hyperf\WebSocketServer\Sender - */ - private $sender; + #[Inject] + private Sender $sender; /** * 通知用户上线下线 @@ -91,7 +89,7 @@ function mergeForwardMessage(array $userInfo, array $user, string $content) //添加消息记录 FriendChatHistory::addMessage($message, $receptionState); - if ($message['type'] == FriendChatHistory::FRIEND_CHAT_MESSAGE_TYPE_FORWARD) $message['content'] = MessageService::getInstance()->formatForwardMessage($message['content'], $message['fromUser']); + $message['content'] = MessageService::getInstance()->formatForwardMessage($message['content'], $message['fromUser']); $sendMessage = [ 'message' => $message, @@ -112,7 +110,7 @@ function forwardMessage(array $userInfo, array $user, array $content) { if (is_array($content)) { foreach ($content as $item) { - $messageSource = $item['is_group'] == true ? GroupChatHistory::query()->where('message_id', $item['id'])->first() : FriendChatHistory::query()->where('message_id', $item['id'])->first(); + $messageSource = $item['is_group'] ? GroupChatHistory::query()->where('message_id', $item['id'])->first() : FriendChatHistory::query()->where('message_id', $item['id'])->first(); $messageSource = objToArray($messageSource); if (empty($messageSource)) continue; //添加聊天记录 diff --git a/app/Task/Laboratory/GroupWsTask.php b/app/Task/Laboratory/GroupWsTask.php index 6071360..af5461d 100644 --- a/app/Task/Laboratory/GroupWsTask.php +++ b/app/Task/Laboratory/GroupWsTask.php @@ -12,11 +12,12 @@ use App\Model\Laboratory\GroupChatHistory; use App\Model\Laboratory\GroupRelation; use App\Pool\Redis; -use App\Service\Laboratory\GroupService; -use App\Service\Laboratory\MessageService; +use App\Service\Laboratory\Ws\GroupService; +use App\Service\Laboratory\Ws\MessageService; use Hyperf\DbConnection\Db; use Hyperf\Di\Annotation\Inject; use Hyperf\Task\Annotation\Task; +use Hyperf\WebSocketServer\Sender; /** * 组消息传递异步任务 @@ -27,11 +28,8 @@ */ class GroupWsTask { - /** - * @Inject() - * @var \Hyperf\WebSocketServer\Sender - */ - private $sender; + #[Inject] + private Sender $sender; /** * @Task() @@ -279,7 +277,7 @@ public function changeGroupAvatar(array $groupInfo) { if (empty($groupInfo)) return false; //如果不是默认头像则不替换 - if (!strstr($groupInfo['avatar'], 'composite_avatar')) return false; + if (!str_contains($groupInfo['avatar'], 'composite_avatar')) return false; $message = []; $message['id'] = generate_rand_id(); $message['status'] = GroupChatHistory::GROUP_CHAT_MESSAGE_STATUS_SUCCEED; @@ -336,9 +334,9 @@ function mergeForwardMessage(array $groupInfo, array $user, string $content) */ function forwardMessage(array $groupInfo, array $user, array $content) { - if (is_array($content)) { + if (!empty($content)) { foreach ($content as $item) { - $messageSource = $item['is_group'] == true ? GroupChatHistory::query()->where('message_id', $item['id'])->first() : FriendChatHistory::query()->where('message_id', $item['id'])->first(); + $messageSource = $item['is_group'] ? GroupChatHistory::query()->where('message_id', $item['id'])->first() : FriendChatHistory::query()->where('message_id', $item['id'])->first(); $messageSource = objToArray($messageSource); if (empty($messageSource)) continue; //添加聊天记录 diff --git a/composer.json b/composer.json index f0c5ef0..786b88e 100644 --- a/composer.json +++ b/composer.json @@ -12,41 +12,47 @@ "description": "A coroutine framework that focuses on hyperspeed and flexible, specifically use for build microservices and middlewares.", "license": "Apache-2.0", "require": { - "php": ">=7.2", + "php": ">=8.0", "ext-swoole": ">=4.5", - "hyperf/cache": "2.1.*", - "hyperf/command": "2.1.*", - "hyperf/view": "2.1.*", - "hyperf/config": "2.1.*", - "hyperf/db-connection": "2.1.*", - "hyperf/framework": "2.1.*", - "hyperf/guzzle": "2.1.*", - "hyperf/http-server": "2.1.*", - "hyperf/logger": "2.1.*", - "hyperf/memory": "2.1.*", - "hyperf/async-queue": "2.1.*", - "hyperf/task": "2.1.*", - "hyperf/crontab": "2.1.*", - "hyperf/process": "2.1.*", - "hyperf/redis": "2.1.*", - "hyperf/database": "2.1.*", - "hyperf/websocket-server": "2.1.*", - "hyperf/constants": "2.1.*", - "donjan-deng/hyperf-permission": "^2.0", - "phper666/jwt-auth": "~3.0.0", + "hyperf/cache": "3.0.*", + "hyperf/command": "3.0.*", + "hyperf/view": "3.0.*", + "hyperf/config": "3.0.*", + "hyperf/db-connection": "3.0.*", + "hyperf/framework": "3.0.*", + "hyperf/guzzle": "3.0.*", + "hyperf/http-server": "3.0.*", + "hyperf/logger": "3.0.*", + "hyperf/memory": "3.0.*", + "hyperf/async-queue": "3.0.*", + "hyperf/task": "3.0.*", + "hyperf/crontab": "3.0.*", + "hyperf/process": "3.0.*", + "hyperf/redis": "3.0.*", + "hyperf/database": "3.0.*", + "hyperf/websocket-server": "3.0.*", + "hyperf/constants": "3.0.*", + "phper666/jwt-auth": "~4.0.10", "easyswoole/verifycode": "3.x", - "hyperf/filesystem": "2.1.*", + "hyperf/filesystem": "3.0.*", "xxtime/flysystem-aliyun-oss": "^1.5", "dragonmantank/cron-expression": "^3.1", - "doctrine/dbal": "^3.0" + "doctrine/dbal": "^3.0", + "hyperf/code-generator": "^0.3.3", + "mogody/hyperf-permission": "^3.0", + "hyperf/validation": "^3.0", + "hyperf/flysystem-oss": "*", + "chinayin/ip2region": "^2.0", + "qcloud_sts/qcloud-sts-sdk": "3.0.8", + "tencentcloud/tencentcloud-sdk-php": "^3.0" }, "require-dev": { "swoole/ide-helper": "^4.5", "friendsofphp/php-cs-fixer": "^2.14", "mockery/mockery": "^1.0", "phpstan/phpstan": "^0.12", - "hyperf/devtool": "2.1.*", - "hyperf/testing": "2.1.*" + "hyperf/devtool": "3.0.*", + "hyperf/testing": "3.0.*" }, "suggest": { "ext-openssl": "Required to use HTTPS.", diff --git a/config/autoload/asset/ip2region.xdb b/config/autoload/asset/ip2region.xdb new file mode 100644 index 0000000..31f96a1 Binary files /dev/null and b/config/autoload/asset/ip2region.xdb differ diff --git a/config/autoload/jwt.php b/config/autoload/jwt.php index 49a9b18..1a25008 100644 --- a/config/autoload/jwt.php +++ b/config/autoload/jwt.php @@ -1,7 +1,22 @@ [ + ["**", "/**"], + ], + 'login_type' => env('JWT_LOGIN_TYPE', 'mpop'), // 登录方式,sso为单点登录,mpop为多点登录 /** @@ -9,59 +24,40 @@ */ 'sso_key' => 'uid', - 'secret' => env('JWT_SECRET', 'phper666'), // 非对称加密使用字符串,请使用自己加密的字符串 + /** + * 只能用于Hmac包下的加密非对称算法,其它的都会使用公私钥 + */ + 'secret' => env('JWT_SECRET', 'phper666'), /** * JWT 权限keys * 对称算法: HS256, HS384 & HS512 使用 `JWT_SECRET`. - * 非对称算法: RS256, RS384 & RS512 / ES256, ES384 & ES512 使用下面的公钥私钥. + * 非对称算法: RS256, RS384 & RS512 / ES256, ES384 & ES512 使用下面的公钥私钥,需要自己去生成. */ 'keys' => [ 'public' => env('JWT_PUBLIC_KEY'), // 公钥,例如:'file:///path/to/public/key' 'private' => env('JWT_PRIVATE_KEY'), // 私钥,例如:'file:///path/to/private/key' + + /** + * 你的私钥的密码。不需要密码可以不用设置 + */ + 'passphrase' => env('JWT_PASSPHRASE'), ], 'ttl' => env('JWT_TTL', 7200), // token过期时间,单位为秒 - - 'ttl_cache' => env('JWT_TTL_CACHE', 7200), //token 缓存时间 单位为秒 - - 'alg' => env('JWT_ALG', 'HS256'), // jwt的hearder加密算法 - - /** - * 支持的算法 - */ - 'supported_algs' => [ - 'HS256' => 'Lcobucci\JWT\Signer\Hmac\Sha256', - 'HS384' => 'Lcobucci\JWT\Signer\Hmac\Sha384', - 'HS512' => 'Lcobucci\JWT\Signer\Hmac\Sha512', - 'ES256' => 'Lcobucci\JWT\Signer\Ecdsa\Sha256', - 'ES384' => 'Lcobucci\JWT\Signer\Ecdsa\Sha384', - 'ES512' => 'Lcobucci\JWT\Signer\Ecdsa\Sha512', - 'RS256' => 'Lcobucci\JWT\Signer\Rsa\Sha256', - 'RS384' => 'Lcobucci\JWT\Signer\Rsa\Sha384', - 'RS512' => 'Lcobucci\JWT\Signer\Rsa\Sha512', - ], + 'ttl_cache' => 10000000, // token过期时间,单位为秒 /** - * 对称算法名称 + * 支持的对称算法:HS256、HS384、HS512 + * 支持的非对称算法:RS256、RS384、RS512、ES256、ES384、ES512 */ - 'symmetry_algs' => [ - 'HS256', - 'HS384', - 'HS512' - ], + 'alg' => env('JWT_ALG', 'HS256'), // jwt的hearder加密算法 /** - * 非对称算法名称 + * jwt使用到的缓存前缀 + * 建议使用独立的redis做缓存,这样比较好做分布式 */ - 'asymmetric_algs' => [ - 'RS256', - 'RS384', - 'RS512', - 'ES256', - 'ES384', - 'ES512', - ], + 'cache_prefix' => 'phper666:jwt', /** * 是否开启黑名单,单点登录和多点登录的注销、刷新使原token失效,必须要开启黑名单,目前黑名单缓存只支持hyperf缓存驱动 @@ -71,14 +67,12 @@ /** * 黑名单的宽限时间 单位为:秒,注意:如果使用单点登录,该宽限时间无效 */ - 'blacklist_grace_period' => env('JWT_TTL', 0), + 'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 0), /** - * 黑名单缓存token时间,注意:该时间一定要设置比token过期时间要大一点,默认为1天,最好设置跟过期时间一样 + * 签发者 */ - 'blacklist_cache_ttl' => env('JWT_TTL', 86400), - - 'blacklist_prefix' => 'hyperf-api', // 黑名单缓存的前缀 + 'issued_by' => 'phper666/jwt', /** * 区分不同场景的token,比如你一个项目可能会有多种类型的应用接口鉴权,下面自行定义,我只是举例子 @@ -89,29 +83,22 @@ */ 'scene' => [ 'default' => [], - 'application1' => [ - 'secret' => 'application1', // 非对称加密使用字符串,请使用自己加密的字符串 + 'application' => [ + 'secret' => 'application', // 非对称加密使用字符串,请使用自己加密的字符串 'login_type' => 'sso', // 登录方式,sso为单点登录,mpop为多点登录 'sso_key' => 'uid', 'ttl' => 7200, // token过期时间,单位为秒 - 'blacklist_cache_ttl' => env('JWT_TTL', 7200), // 黑名单缓存token时间,注意:该时间一定要设置比token过期时间要大一点,默认为100秒,最好设置跟过期时间一样 ], - 'application2' => [ - 'secret' => 'application2', // 非对称加密使用字符串,请使用自己加密的字符串 + 'application1' => [ + 'secret' => 'application1', // 非对称加密使用字符串,请使用自己加密的字符串 'login_type' => 'sso', // 登录方式,sso为单点登录,mpop为多点登录 'sso_key' => 'uid', 'ttl' => 7200, // token过期时间,单位为秒 - 'blacklist_cache_ttl' => env('JWT_TTL', 7200), // 黑名单缓存token时间,注意:该时间一定要设置比token过期时间要大一点,默认为100秒,最好设置跟过期时间一样 ], - 'application3' => [ - 'secret' => 'application3', // 非对称加密使用字符串,请使用自己加密的字符串 + 'application2' => [ + 'secret' => 'application2', // 非对称加密使用字符串,请使用自己加密的字符串 'login_type' => 'mppo', // 登录方式,sso为单点登录,mpop为多点登录 'ttl' => 7200, // token过期时间,单位为秒 - 'blacklist_cache_ttl' => env('JWT_TTL', 7200), // 黑名单缓存token时间,注意:该时间一定要设置比token过期时间要大一点,默认为100秒,最好设置跟过期时间一样 ] - ], - 'model' => [ // TODO 支持直接获取某模型的数据 - 'class' => '', - 'pk' => 'uid' ] -]; +]; \ No newline at end of file diff --git a/config/autoload/permissionData.php b/config/autoload/permissionData.php index 88c0aa2..3bf37c3 100644 --- a/config/autoload/permissionData.php +++ b/config/autoload/permissionData.php @@ -1600,6 +1600,5 @@ "created_at" => "2021-8-24 15:07:32", "updated_at" => "2021-8-24 15:07:32" ] - ] ]; \ No newline at end of file diff --git a/config/autoload/server.php b/config/autoload/server.php index ed1d8b7..a7ec7e0 100644 --- a/config/autoload/server.php +++ b/config/autoload/server.php @@ -9,8 +9,9 @@ * @contact group@hyperf.io * @license https://github.com/hyperf/hyperf/blob/master/LICENSE */ +use Hyperf\Server\Event; use Hyperf\Server\Server; -use Hyperf\Server\SwooleEvent; +use Swoole\Constant; return [ 'mode' => SWOOLE_PROCESS, @@ -22,7 +23,11 @@ 'port' => 9501, 'sock_type' => SWOOLE_SOCK_TCP, 'callbacks' => [ - SwooleEvent::ON_REQUEST => [Hyperf\HttpServer\Server::class, 'onRequest'], + Event::ON_REQUEST => [Hyperf\HttpServer\Server::class, 'onRequest'], + ], + 'options' => [ + // Whether to enable request lifecycle event + 'enable_request_lifecycle' => false, ], ], [ @@ -32,35 +37,36 @@ 'port' => 9502, 'sock_type' => SWOOLE_SOCK_TCP, 'callbacks' => [ - SwooleEvent::ON_HAND_SHAKE => [Hyperf\WebSocketServer\Server::class, 'onHandShake'], - SwooleEvent::ON_MESSAGE => [Hyperf\WebSocketServer\Server::class, 'onMessage'], - SwooleEvent::ON_CLOSE => [Hyperf\WebSocketServer\Server::class, 'onClose'], + Event::ON_HAND_SHAKE => [Hyperf\WebSocketServer\Server::class, 'onHandShake'], + Event::ON_MESSAGE => [Hyperf\WebSocketServer\Server::class, 'onMessage'], + Event::ON_CLOSE => [Hyperf\WebSocketServer\Server::class, 'onClose'], + ], + 'options' => [ + // Whether to enable request lifecycle event + 'enable_request_lifecycle' => false, ], ], + ], 'settings' => [ - 'enable_coroutine' => true, - 'worker_num' => swoole_cpu_num(), - 'pid_file' => BASE_PATH . '/runtime/hyperf.pid', - 'open_tcp_nodelay' => true, - 'max_coroutine' => 100000, - 'open_http2_protocol' => true, - 'max_request' => 100000, - 'socket_buffer_size' => 100 * 1024 * 1024, - 'buffer_output_size' => 100 * 1024 * 1024, - 'package_max_length' => 100 * 1024 * 1024, - // Task Worker 数量,根据您的服务器配置而配置适当的数量 - 'task_worker_num' => 8, - // 因为 `Task` 主要处理无法协程化的方法,所以这里推荐设为 `false`,避免协程下出现数据混淆的情况 - 'task_enable_coroutine' => false, + Constant::OPTION_ENABLE_COROUTINE => true, + Constant::OPTION_WORKER_NUM => swoole_cpu_num(), + Constant::OPTION_PID_FILE => BASE_PATH . '/runtime/hyperf.pid', + Constant::OPTION_OPEN_TCP_NODELAY => true, + Constant::OPTION_MAX_COROUTINE => 100000, + Constant::OPTION_OPEN_HTTP2_PROTOCOL => true, + Constant::OPTION_MAX_REQUEST => 100000, + Constant::OPTION_SOCKET_BUFFER_SIZE => 2 * 1024 * 1024, + Constant::OPTION_BUFFER_OUTPUT_SIZE => 2 * 1024 * 1024, + Constant::OPTION_TASK_WORKER_NUM => 8, + Constant::OPTION_TASK_ENABLE_COROUTINE => false, ], 'callbacks' => [ - SwooleEvent::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'], - SwooleEvent::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'], - SwooleEvent::ON_WORKER_EXIT => [Hyperf\Framework\Bootstrap\WorkerExitCallback::class, 'onWorkerExit'], - + Event::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'], + Event::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'], + Event::ON_WORKER_EXIT => [Hyperf\Framework\Bootstrap\WorkerExitCallback::class, 'onWorkerExit'], // Task callbacks - SwooleEvent::ON_TASK => [Hyperf\Framework\Bootstrap\TaskCallback::class, 'onTask'], - SwooleEvent::ON_FINISH => [Hyperf\Framework\Bootstrap\FinishCallback::class, 'onFinish'], + Event::ON_TASK => [Hyperf\Framework\Bootstrap\TaskCallback::class, 'onTask'], + Event::ON_FINISH => [Hyperf\Framework\Bootstrap\FinishCallback::class, 'onFinish'], ], -]; +]; \ No newline at end of file diff --git a/config/config.php b/config/config.php index 37ebe67..fa34982 100644 --- a/config/config.php +++ b/config/config.php @@ -28,7 +28,7 @@ 'log_level' => [ LogLevel::ALERT, LogLevel::CRITICAL, - //LogLevel::DEBUG, + LogLevel::DEBUG, LogLevel::EMERGENCY, LogLevel::ERROR, LogLevel::INFO, diff --git a/watch b/watch index 981aedd..271763b 100644 --- a/watch +++ b/watch @@ -80,7 +80,7 @@ function killOldProcess() { // pid存在则关闭存在的进程 if (file_exists(PID_FILE_PATH) && $pid = @file_get_contents(PID_FILE_PATH)) { - if (!@posix_kill($pid)) forceKill(); + if (!@posix_kill($pid, SIGTERM)) forceKill(); } else forceKill(); } @@ -221,7 +221,7 @@ function delDir($path) class Filter extends RecursiveFilterIterator { - public function accept() + public function accept() : bool { if ($this->current()->isDir()) { if (preg_match('/^\./', $this->current()->getFilename())) {