ZipCodeCoordinatesService.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Http\Client\Pool;
  4. use Illuminate\Http\Client\Response;
  5. use Illuminate\Support\Facades\Cache;
  6. use Illuminate\Support\Facades\Http;
  7. use Throwable;
  8. class ZipCodeCoordinatesService
  9. {
  10. private array $resolvedZipCodes = [];
  11. public function resolve(?float $latitude, ?float $longitude, ?string $zipCode): ?array
  12. {
  13. if ($latitude !== null && $longitude !== null) {
  14. return compact('latitude', 'longitude');
  15. }
  16. return $this->findByZipCode($zipCode);
  17. }
  18. public function calculateDistance(
  19. ?float $originLatitude,
  20. ?float $originLongitude,
  21. ?string $originZipCode,
  22. ?float $targetLatitude,
  23. ?float $targetLongitude,
  24. ?string $targetZipCode,
  25. ): ?float {
  26. $origin = $this->resolve($originLatitude, $originLongitude, $originZipCode);
  27. $target = $this->resolve($targetLatitude, $targetLongitude, $targetZipCode);
  28. return DistanceService::calculate(
  29. $origin['latitude'] ?? null,
  30. $origin['longitude'] ?? null,
  31. $target['latitude'] ?? null,
  32. $target['longitude'] ?? null,
  33. );
  34. }
  35. public function findByZipCode(?string $zipCode): ?array
  36. {
  37. $zipCode = $this->normalize($zipCode);
  38. if ($zipCode === null) {
  39. return null;
  40. }
  41. if (array_key_exists($zipCode, $this->resolvedZipCodes)) {
  42. return $this->resolvedZipCodes[$zipCode];
  43. }
  44. if ($this->restoreFromCache($zipCode)) {
  45. return $this->resolvedZipCodes[$zipCode];
  46. }
  47. $coordinates = $this->requestCoordinates($zipCode);
  48. $this->remember($zipCode, $coordinates);
  49. return $coordinates;
  50. }
  51. public function preload(iterable $zipCodes): void
  52. {
  53. $pending = [];
  54. foreach ($zipCodes as $zipCode) {
  55. $zipCode = $this->normalize($zipCode);
  56. if (
  57. $zipCode === null
  58. || array_key_exists($zipCode, $this->resolvedZipCodes)
  59. || $this->restoreFromCache($zipCode)
  60. ) {
  61. continue;
  62. }
  63. $pending[$zipCode] = $zipCode;
  64. }
  65. if ($pending === []) {
  66. return;
  67. }
  68. try {
  69. $baseUrl = rtrim((string) config('services.brasil_api.base_url'), '/');
  70. $responses = Http::pool(fn (Pool $pool) => array_map(
  71. fn (string $zipCode) => $pool
  72. ->as($zipCode)
  73. ->acceptJson()
  74. ->connectTimeout((int) config('services.brasil_api.connect_timeout', 2))
  75. ->timeout((int) config('services.brasil_api.timeout', 3))
  76. ->get("{$baseUrl}/api/cep/v2/{$zipCode}"),
  77. $pending,
  78. ));
  79. } catch (Throwable) {
  80. $responses = [];
  81. }
  82. foreach ($pending as $zipCode) {
  83. $response = $responses[$zipCode] ?? null;
  84. $coordinates = $response instanceof Response
  85. ? $this->coordinatesFromResponse($response)
  86. : null;
  87. $this->remember($zipCode, $coordinates);
  88. }
  89. }
  90. private function normalize(?string $zipCode): ?string
  91. {
  92. $zipCode = preg_replace('/\D/', '', $zipCode ?? '');
  93. return strlen($zipCode) === 8 ? $zipCode : null;
  94. }
  95. private function restoreFromCache(string $zipCode): bool
  96. {
  97. $cached = Cache::get("zip-code-coordinates:{$zipCode}");
  98. if (! is_array($cached) || ! array_key_exists('found', $cached)) {
  99. return false;
  100. }
  101. $this->resolvedZipCodes[$zipCode] = $cached['found']
  102. ? $cached['coordinates']
  103. : null;
  104. return true;
  105. }
  106. private function remember(string $zipCode, ?array $coordinates): void
  107. {
  108. $this->resolvedZipCodes[$zipCode] = $coordinates;
  109. Cache::put(
  110. "zip-code-coordinates:{$zipCode}",
  111. [
  112. 'found' => $coordinates !== null,
  113. 'coordinates' => $coordinates,
  114. ],
  115. now()->addSeconds(
  116. $coordinates !== null
  117. ? (int) config('services.brasil_api.cep_cache_ttl', 2592000)
  118. : (int) config('services.brasil_api.cep_failure_cache_ttl', 600)
  119. )
  120. );
  121. }
  122. private function requestCoordinates(string $zipCode): ?array
  123. {
  124. try {
  125. $response = Http::baseUrl(rtrim((string) config('services.brasil_api.base_url'), '/'))
  126. ->acceptJson()
  127. ->connectTimeout((int) config('services.brasil_api.connect_timeout', 2))
  128. ->timeout((int) config('services.brasil_api.timeout', 3))
  129. ->get("api/cep/v2/{$zipCode}");
  130. return $this->coordinatesFromResponse($response);
  131. } catch (Throwable) {
  132. return null;
  133. }
  134. }
  135. private function coordinatesFromResponse(Response $response): ?array
  136. {
  137. if (! $response->successful()) {
  138. return null;
  139. }
  140. $latitude = $response->json('location.coordinates.latitude');
  141. $longitude = $response->json('location.coordinates.longitude');
  142. if (! is_numeric($latitude) || ! is_numeric($longitude)) {
  143. return null;
  144. }
  145. $latitude = (float) $latitude;
  146. $longitude = (float) $longitude;
  147. if ($latitude < -90 || $latitude > 90 || $longitude < -180 || $longitude > 180) {
  148. return null;
  149. }
  150. return compact('latitude', 'longitude');
  151. }
  152. }