Fields.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\miniapi\http;
  4. use app\miniapi\exception\ApiException;
  5. use app\miniapi\support\PhoneNumber;
  6. final class Fields
  7. {
  8. public static function phone(array $data, string $key = 'phone'): string
  9. {
  10. $value = self::text($data, $key, 30);
  11. try {
  12. return PhoneNumber::normalize($value);
  13. } catch (\InvalidArgumentException) {
  14. throw new ApiException(42201, '请填写完整有效的联系电话', 422, [$key => '须为7至15位数字,可含前置+、空格、横线和成对括号']);
  15. }
  16. }
  17. public static function text(array $data, string $key, int $max = 120, bool $required = true): string
  18. {
  19. $value = $data[$key] ?? '';
  20. if (!is_string($value) || str_contains($value, "\0") || mb_strlen(trim($value)) > $max || ($required && trim($value) === '')) {
  21. throw new ApiException(42201, '参数校验失败', 422, [$key => '文本不能为空或超出长度']);
  22. }
  23. return trim($value);
  24. }
  25. public static function id(array $data, string $key): int
  26. {
  27. return Input::integer($data[$key] ?? null, $key, 1, 2147483647);
  28. }
  29. public static function only(array $data, array $keys): void
  30. {
  31. if (array_diff(array_keys($data), $keys)) {
  32. throw new ApiException(42201, '包含不支持的字段', 422);
  33. }
  34. }
  35. public static function choice(array $data, string $key, array $choices, string $default = ''): string
  36. {
  37. $value = $data[$key] ?? $default;
  38. if (!is_string($value) || !in_array($value, $choices, true)) {
  39. throw new ApiException(42201, '参数校验失败', 422, [$key => '选项无效']);
  40. }
  41. return $value;
  42. }
  43. public static function location(array $data): array
  44. {
  45. $result = [];
  46. foreach ([
  47. 'latitude' => 90,
  48. 'longitude' => 180,
  49. ] as $key => $max) {
  50. $value = $data[$key] ?? null;
  51. if ((!is_int($value) && !is_float($value)) || !is_finite((float) $value) || abs($value) > $max) {
  52. throw new ApiException(42201, '定位参数无效', 422, [$key => '须为有效数值']);
  53. }
  54. $result[$key] = round((float) $value, 6);
  55. }
  56. return $result;
  57. }
  58. }