LocationValidationTrait.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Traits;
  3. use App\Enums\TechnicianLocationType;
  4. trait LocationValidationTrait
  5. {
  6. /**
  7. * 验证位置类型
  8. * 检查位置类型是否为有效值
  9. *
  10. * @param int|null $type 位置类型
  11. * @param int $code HTTP状态码
  12. * @param string $message 错误消息
  13. * @return void
  14. */
  15. protected function validateLocationType(?int $type, int $code = 422, string $message = '无效的位置类型'): void
  16. {
  17. abort_if(
  18. !in_array($type, [TechnicianLocationType::CURRENT->value, TechnicianLocationType::COMMON->value]),
  19. $code,
  20. $message
  21. );
  22. }
  23. /**
  24. * 验证经纬度
  25. * 检查经纬度的有效性
  26. *
  27. * @param float $latitude 纬度
  28. * @param float $longitude 经度
  29. * @param int $code HTTP状态码
  30. * @param string $latMessage 纬度错误消息
  31. * @param string $lngMessage 经度错误消息
  32. * @throws \Exception 当经纬度无效时抛出异常
  33. */
  34. protected function validateCoordinates(
  35. $latitude,
  36. $longitude,
  37. int $code = 422,
  38. string $latMessage = '无效的纬度坐标',
  39. string $lngMessage = '无效的经度坐标'
  40. ): void {
  41. // 验证纬度 (-90° to 90°)
  42. abort_if(
  43. !is_numeric($latitude) || !($latitude >= -90 && $latitude <= 90),
  44. $code,
  45. $latMessage
  46. );
  47. // 验证经度 (-180° to 180°)
  48. abort_if(
  49. !is_numeric($longitude) || !($longitude >= -180 && $longitude <= 180),
  50. $code,
  51. $lngMessage
  52. );
  53. }
  54. /**
  55. * 获取有效的位置类型列表
  56. *
  57. * @return array 位置类型列表
  58. */
  59. protected function getValidLocationTypes(): array
  60. {
  61. return [
  62. TechnicianLocationType::CURRENT->value,
  63. TechnicianLocationType::COMMON->value
  64. ];
  65. }
  66. /**
  67. * 检查是否为有效的位置类型
  68. *
  69. * @param int|null $type 位置类型
  70. * @return bool
  71. */
  72. protected function isValidLocationType(?int $type): bool
  73. {
  74. return in_array($type, $this->getValidLocationTypes());
  75. }
  76. }