Drupal 9 DELETE API如何确保student_no始终为整数?
解决方案
要确保响应中的student_no始终为数字类型,同时符合API仅返回200、404、405的契约要求,最佳方案是先校验输入有效性,再安全转换类型,具体实现如下:
1. 输入有效性校验
在函数开头先验证传入的student_no是否为有效的正整数(学号应为正整数,排除0、负数及非数字字符串),避免直接强制转换导致的不合理值(如非数字转0)。
可以使用两种方式校验:
// 方式1:用ctype_digit校验字符串是否全为数字字符,同时排除0 if (!ctype_digit($student_no) || (int)$student_no <= 0) { $response_code = 404; $response = [ "code" => $response_code, "message" => "Student does not exist", "student_no" => (int)$student_no // 统一转为数字类型返回 ]; return new JsonResponse($response, $response_code, $headers); } // 方式2:用filter_var更灵活地校验整数范围 $valid_student_no = filter_var($student_no, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); if ($valid_student_no === false) { $response_code = 404; $response = [ "code" => $response_code, "message" => "Student does not exist", "student_no" => (int)$student_no ]; return new JsonResponse($response, $response_code, $headers); } $student_no = $valid_student_no;
2. 安全转换为整数
校验通过后,将student_no强制转换为整数,确保后续查询及响应中的值均为数字类型:
$student_no = (int)$student_no;
3. 修改后的完整函数
public function delete($student_no) { // 校验student_no是否为有效正整数 if (!ctype_digit($student_no) || (int)$student_no <= 0) { $response_code = 404; $response = [ "code" => $response_code, "message" => "Student does not exist", "student_no" => (int)$student_no ]; return new JsonResponse($response, $response_code, $headers); } // 转换为整数类型 $student_no = (int)$student_no; $node_array = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['student_no' => $student_no]); $node = reset($node_array); if ($node && ($node->bundle() == 'student')) { try { $node->delete(); $response_code = 200; $response = [ "code" => $response_code, "message" => 'deleted', "student_no" => $student_no ]; return new JsonResponse($response, $response_code, $headers); } catch (ClientException | RequestException | TransferException | BadResponseException $exception) { \Drupal::service('myapi.log_service')->api_log("Student Delete API Exception: {$exception}"); $response_code = 405; $message = json_decode((string) (($exception->getResponse()) ? $exception->getResponse()->getBody() : '')); $response = [ "code" => $response_code, "message" => 'Failed to delete student', "student_no" => $student_no ]; return new JsonResponse($response, $response_code, $headers); } } else { $response_code = 404; $response = [ "code" => $response_code, "message" => "Student does not exist", "student_no" => $student_no ]; return new JsonResponse($response, $response_code, $headers); } }
方案优势
- 符合API契约:提前拦截无效输入,返回约定的404状态码,避免触发500内部错误
- 类型统一:响应中的
student_no始终为数字类型,满足格式要求 - 严谨性高:排除非数字、0、负数等不合理学号,避免无效查询或误操作
- 兼容性好:适配Drupal路由参数传递逻辑,无需依赖严格类型模式
内容的提问来源于stack exchange,提问作者irohit786
相关产品推荐
相关产品推荐

