| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- <?php
- declare(strict_types=1);
- namespace app\miniapi\http;
- use app\miniapi\exception\ApiException;
- use app\miniapi\support\PhoneNumber;
- final class Fields
- {
- public static function phone(array $data, string $key = 'phone'): string
- {
- $value = self::text($data, $key, 30);
- try {
- return PhoneNumber::normalize($value);
- } catch (\InvalidArgumentException) {
- throw new ApiException(42201, '请填写完整有效的联系电话', 422, [$key => '须为7至15位数字,可含前置+、空格、横线和成对括号']);
- }
- }
- public static function text(array $data, string $key, int $max = 120, bool $required = true): string
- {
- $value = $data[$key] ?? '';
- if (!is_string($value) || str_contains($value, "\0") || mb_strlen(trim($value)) > $max || ($required && trim($value) === '')) {
- throw new ApiException(42201, '参数校验失败', 422, [$key => '文本不能为空或超出长度']);
- }
- return trim($value);
- }
- public static function id(array $data, string $key): int
- {
- return Input::integer($data[$key] ?? null, $key, 1, 2147483647);
- }
- public static function only(array $data, array $keys): void
- {
- if (array_diff(array_keys($data), $keys)) {
- throw new ApiException(42201, '包含不支持的字段', 422);
- }
- }
- public static function choice(array $data, string $key, array $choices, string $default = ''): string
- {
- $value = $data[$key] ?? $default;
- if (!is_string($value) || !in_array($value, $choices, true)) {
- throw new ApiException(42201, '参数校验失败', 422, [$key => '选项无效']);
- }
- return $value;
- }
- public static function location(array $data): array
- {
- $result = [];
- foreach ([
- 'latitude' => 90,
- 'longitude' => 180,
- ] as $key => $max) {
- $value = $data[$key] ?? null;
- if ((!is_int($value) && !is_float($value)) || !is_finite((float) $value) || abs($value) > $max) {
- throw new ApiException(42201, '定位参数无效', 422, [$key => '须为有效数值']);
- }
- $result[$key] = round((float) $value, 6);
- }
- return $result;
- }
- }
|