| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- <?php
- declare(strict_types=1);
- namespace app\miniapi\http;
- use Webman\Http\Request;
- use app\miniapi\exception\ApiException;
- final class Input
- {
- /** JSON object only: never merge URL parameters into a command body. */
- public static function json(Request $request): array
- {
- if (strtolower(trim(explode(';', (string) $request->header('content-type', ''))[0])) !== 'application/json') {
- throw new ApiException(41501, '请使用 application/json 提交参数', 415);
- }
- $raw = $request->rawBody();
- if (strlen($raw) > self::bodyLimit($request)) {
- throw new ApiException(41301, '请求内容过大', 413);
- }
- try {
- $value = json_decode($raw, false, 64, JSON_THROW_ON_ERROR);
- } catch (\JsonException) {
- throw new ApiException(40001, 'JSON格式不正确', 400);
- }
- if (!$value instanceof \stdClass) {
- throw new ApiException(40001, '请求内容必须为JSON对象', 400);
- }
- // Validate the root as an object, then convert nested objects for service validators.
- return json_decode($raw, true, 64, JSON_THROW_ON_ERROR);
- }
- public static function bodyLimit(Request $request): int
- {
- return preg_match('#^/api/mini/v1/drivers/\d+/tasks/\d+/photos$#D', $request->path())
- ? (int) config('mini_api.max_photo_body_bytes', 3000000) : (int) config('mini_api.max_body_bytes', 65536);
- }
- public static function integer(mixed $value, string $field, int $min, int $max): int
- {
- if ((!is_int($value) && !is_string($value)) || filter_var($value, FILTER_VALIDATE_INT) === false || (int) $value < $min || (int) $value > $max) {
- throw new ApiException(42201, '参数校验失败', 422, [$field => "必须为{$min}至{$max}之间的整数"]);
- }
- return (int) $value;
- }
- }
|