scopeService = $scopeService; } /** * 处理请求(模板方法) * * @param array $data 请求数据 * @param array $context 上下文信息 * @return JsonResponse */ public function handle(array $data, array $context = []): JsonResponse { try { // 验证权限 $app = $this->getApp($context); if (!$app) { return $this->errorResponse('应用信息不存在', null, 404); } if (!$this->validatePermissions($app->scopes ?? [], $context)) { return $this->errorResponse('权限不足', null, 403); } // 调用具体的业务处理方法 return $this->process($data, $context); } catch (\Exception $e) { return $this->errorResponse('请求处理失败', ['error' => $e->getMessage()], 500); } } /** * 具体的业务处理方法(由子类实现) * * @param array $data 请求数据 * @param array $context 上下文信息 * @return JsonResponse */ abstract protected function process(array $data, array $context = []): JsonResponse; /** * 验证权限 * * @param array $scopes 应用权限范围 * @param array $context 上下文信息 * @return bool */ public function validatePermissions(array $scopes, array $context = []): bool { $requiredScopes = $this->getRequiredScopes(); foreach ($requiredScopes as $requiredScope) { if (!in_array($requiredScope->value, $scopes)) { return false; } } return true; } /** * 成功响应 * * @param string $message * @param mixed $data * @param int $code * @return JsonResponse */ protected function successResponse(string $message, $data = null, int $code = 200): JsonResponse { $response = [ 'success' => true, 'message' => $message, ]; if ($data !== null) { $response['data'] = $data; } return response()->json($response, $code); } /** * 错误响应 * * @param string $message * @param mixed $errors * @param int $code * @return JsonResponse */ protected function errorResponse(string $message, $errors = null, int $code = 400): JsonResponse { $response = [ 'success' => false, 'message' => $message, ]; if ($errors !== null) { $response['errors'] = $errors; } return response()->json($response, $code); } /** * 验证请求数据 * * @param array $data * @param array $rules * @return array|null 返回错误信息,null表示验证通过 */ protected function validateData(array $data, array $rules): ?array { $validator = validator($data, $rules); if ($validator->fails()) { return $validator->errors()->toArray(); } return null; } /** * 获取用户ID * * @param array $context * @return int */ protected function getUserId(array $context): int { return $context['user_id'] ?? 0; } /** * 获取应用信息 * * @param array $context * @return \App\Module\OpenAPI\Models\OpenApiApp|null */ protected function getApp(array $context): ?\App\Module\OpenAPI\Models\OpenApiApp { return $context['app'] ?? null; } /** * 记录操作日志 * * @param string $action * @param array $data * @param array $context * @return void */ protected function logAction(string $action, array $data, array $context): void { // 这里可以实现日志记录逻辑 // 例如记录到数据库或日志文件 } }