UserProfileHandler.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace App\Module\OpenAPI\Handlers\User;
  3. use App\Module\OpenAPI\Handlers\BaseHandler;
  4. use App\Module\OpenAPI\Services\ScopeService;
  5. use Illuminate\Http\JsonResponse;
  6. /**
  7. * 用户信息Handler
  8. *
  9. * 处理获取用户信息的业务逻辑
  10. */
  11. class UserProfileHandler extends BaseHandler
  12. {
  13. public function __construct(ScopeService $scopeService)
  14. {
  15. parent::__construct($scopeService);
  16. }
  17. /**
  18. * 获取所需的权限范围
  19. *
  20. * @return array
  21. */
  22. public function getRequiredScopes(): array
  23. {
  24. return ['USER_READ'];
  25. }
  26. /**
  27. * 处理获取用户信息请求
  28. *
  29. * @param array $data 请求数据
  30. * @param array $context 上下文信息
  31. * @return JsonResponse
  32. */
  33. public function handle(array $data, array $context = []): JsonResponse
  34. {
  35. try {
  36. // 验证权限
  37. $app = $this->getApp($context);
  38. if (!$app) {
  39. return $this->errorResponse('应用信息不存在', null, 404);
  40. }
  41. if (!$this->validatePermissions($app->scopes ?? [], $context)) {
  42. return $this->errorResponse('权限不足', null, 403);
  43. }
  44. // 获取用户ID
  45. $userId = $data['user_id'] ?? $this->getUserId($context);
  46. if (!$userId) {
  47. return $this->errorResponse('用户ID不能为空', null, 400);
  48. }
  49. // 调用User模块服务获取用户信息
  50. $userInfo = $this->getUserInfo($userId);
  51. if (!$userInfo) {
  52. return $this->errorResponse('用户不存在', null, 404);
  53. }
  54. // 记录操作日志
  55. $this->logAction('user.profile.get', ['user_id' => $userId], $context);
  56. return $this->successResponse('获取用户信息成功', $userInfo);
  57. } catch (\Exception $e) {
  58. return $this->errorResponse('获取用户信息失败', ['error' => $e->getMessage()], 500);
  59. }
  60. }
  61. /**
  62. * 获取用户信息
  63. *
  64. * 这里应该调用User模块的实际服务
  65. *
  66. * @param int $userId
  67. * @return array|null
  68. */
  69. protected function getUserInfo(int $userId): ?array
  70. {
  71. // TODO: 这里应该调用User模块的服务
  72. // 例如: return app(UserService::class)->getUserById($userId);
  73. // 暂时返回示例数据
  74. if ($userId > 0) {
  75. return [
  76. 'id' => $userId,
  77. 'name' => "用户{$userId}",
  78. 'email' => "user{$userId}@example.com",
  79. 'avatar' => "https://example.com/avatar/{$userId}.jpg",
  80. 'level' => rand(1, 100),
  81. 'exp' => rand(0, 10000),
  82. 'created_at' => now()->subDays(rand(1, 365))->toISOString(),
  83. 'last_login_at' => now()->subHours(rand(1, 24))->toISOString(),
  84. ];
  85. }
  86. return null;
  87. }
  88. }