ZipCodeCoordinatesService.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Address;
  4. use Illuminate\Http\Client\Pool;
  5. use Illuminate\Http\Client\Response;
  6. use Illuminate\Support\Facades\Cache;
  7. use Illuminate\Support\Facades\Http;
  8. use Illuminate\Support\Facades\Log;
  9. use Throwable;
  10. class ZipCodeCoordinatesService
  11. {
  12. private array $resolvedZipCodes = [];
  13. public function resolve(?float $latitude, ?float $longitude, ?string $zipCode): ?array
  14. {
  15. if ($latitude !== null && $longitude !== null) {
  16. return compact('latitude', 'longitude');
  17. }
  18. return $this->findByZipCode($zipCode);
  19. }
  20. //
  21. public function calculateDistance(
  22. ?float $originLatitude,
  23. ?float $originLongitude,
  24. ?string $originZipCode,
  25. ?float $targetLatitude,
  26. ?float $targetLongitude,
  27. ?string $targetZipCode,
  28. ): ?float {
  29. $origin = $this->resolve($originLatitude, $originLongitude, $originZipCode);
  30. $target = $this->resolve($targetLatitude, $targetLongitude, $targetZipCode);
  31. $distance = DistanceService::calculate(
  32. $origin['latitude'] ?? null,
  33. $origin['longitude'] ?? null,
  34. $target['latitude'] ?? null,
  35. $target['longitude'] ?? null,
  36. );
  37. return $distance;
  38. }
  39. public function findByZipCode(?string $zipCode): ?array
  40. {
  41. $zipCode = $this->normalize($zipCode);
  42. if ($zipCode === null) {
  43. return null;
  44. }
  45. if (array_key_exists($zipCode, $this->resolvedZipCodes)) {
  46. return $this->resolvedZipCodes[$zipCode];
  47. }
  48. if ($this->restoreFromCache($zipCode)) {
  49. return $this->resolvedZipCodes[$zipCode];
  50. }
  51. if (! $this->googleGeocodingIsConfigured()) {
  52. return $this->resolvedZipCodes[$zipCode] = null;
  53. }
  54. $coordinates = $this->requestCoordinates($zipCode);
  55. $this->remember($zipCode, $coordinates);
  56. return $coordinates;
  57. }
  58. public function preload(iterable $zipCodes): void
  59. {
  60. $pending = [];
  61. foreach ($zipCodes as $zipCode) {
  62. $zipCode = $this->normalize($zipCode);
  63. if (
  64. $zipCode === null
  65. || array_key_exists($zipCode, $this->resolvedZipCodes)
  66. || $this->restoreFromCache($zipCode)
  67. ) {
  68. continue;
  69. }
  70. $pending[$zipCode] = $zipCode;
  71. }
  72. if ($pending === []) {
  73. return;
  74. }
  75. if (! $this->googleGeocodingIsConfigured()) {
  76. foreach ($pending as $zipCode) {
  77. $this->resolvedZipCodes[$zipCode] = null;
  78. }
  79. return;
  80. }
  81. Log::channel('google_geocoding')->info('ZipCodeCoordinates Google Geocoding lookup required', [
  82. 'mode' => 'preload',
  83. 'pending_count' => count($pending),
  84. 'zip_codes_sample' => array_slice(array_values($pending), 0, 20),
  85. 'connect_timeout' => (int) config('services.google_geocoding.connect_timeout', 2),
  86. 'timeout' => (int) config('services.google_geocoding.timeout', 5),
  87. 'ip_resolve' => 'ipv4',
  88. ]);
  89. try {
  90. $baseUrl = rtrim((string) config('services.google_geocoding.base_url'), '/');
  91. $startedAt = microtime(true);
  92. $responses = Http::pool(fn (Pool $pool) => array_map(
  93. fn (string $zipCode) => $pool
  94. ->as($zipCode)
  95. ->acceptJson()
  96. ->connectTimeout((int) config('services.google_geocoding.connect_timeout', 2))
  97. ->timeout((int) config('services.google_geocoding.timeout', 5))
  98. ->withOptions($this->curlForceIpv4Options())
  99. ->get("{$baseUrl}/maps/api/geocode/json", $this->googleQuery($zipCode)),
  100. $pending,
  101. ));
  102. } catch (Throwable $exception) {
  103. Log::channel('google_geocoding')->warning('ZipCodeCoordinates Google Geocoding preload failed', [
  104. 'pending_count' => count($pending),
  105. 'elapsed_ms' => isset($startedAt) ? round((microtime(true) - $startedAt) * 1000, 2) : null,
  106. 'error' => $exception->getMessage(),
  107. ]);
  108. $responses = [];
  109. }
  110. foreach ($pending as $zipCode) {
  111. $response = $responses[$zipCode] ?? null;
  112. $coordinates = $response instanceof Response
  113. ? $this->coordinatesFromResponse($response)
  114. : null;
  115. $this->remember($zipCode, $coordinates);
  116. }
  117. }
  118. //
  119. private function coordinatesFromResponse(Response $response): ?array
  120. {
  121. if (! $response->successful()) {
  122. return null;
  123. }
  124. if ($response->json('status') !== 'OK') {
  125. return null;
  126. }
  127. $latitude = $response->json('results.0.geometry.location.lat');
  128. $longitude = $response->json('results.0.geometry.location.lng');
  129. if (! is_numeric($latitude) || ! is_numeric($longitude)) {
  130. return null;
  131. }
  132. $latitude = (float) $latitude;
  133. $longitude = (float) $longitude;
  134. if ($latitude < -90 || $latitude > 90 || $longitude < -180 || $longitude > 180) {
  135. return null;
  136. }
  137. return compact('latitude', 'longitude');
  138. }
  139. private function curlForceIpv4Options(): array
  140. {
  141. if (! defined('CURLOPT_IPRESOLVE') || ! defined('CURL_IPRESOLVE_V4')) {
  142. return [];
  143. }
  144. return [
  145. 'curl' => [
  146. CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
  147. ],
  148. ];
  149. }
  150. private function googleGeocodingIsConfigured(): bool
  151. {
  152. return trim((string) config('services.google_geocoding.api_key')) !== '';
  153. }
  154. private function googleQuery(string $zipCode): array
  155. {
  156. return [
  157. 'components' => "postal_code:{$zipCode}|country:BR",
  158. 'language' => 'pt-BR',
  159. 'region' => 'br',
  160. 'key' => (string) config('services.google_geocoding.api_key'),
  161. ];
  162. }
  163. private function normalize(?string $zipCode): ?string
  164. {
  165. $zipCode = preg_replace('/\D/', '', $zipCode ?? '');
  166. return strlen($zipCode) === 8 ? $zipCode : null;
  167. }
  168. private function persistProviderCoordinates(string $zipCode, array $coordinates): void
  169. {
  170. $formattedZipCode = substr($zipCode, 0, 5).'-'.substr($zipCode, 5);
  171. Address::query()
  172. ->where('source', 'provider')
  173. ->whereIn('zip_code', [$zipCode, $formattedZipCode])
  174. ->where(function ($query) {
  175. $query->whereNull('latitude')->orWhereNull('longitude');
  176. })
  177. ->update([
  178. 'latitude' => $coordinates['latitude'],
  179. 'longitude' => $coordinates['longitude'],
  180. ]);
  181. }
  182. private function remember(string $zipCode, ?array $coordinates): void
  183. {
  184. $this->resolvedZipCodes[$zipCode] = $coordinates;
  185. if ($coordinates === null) {
  186. return;
  187. }
  188. Cache::put(
  189. "zip-code-coordinates:{$zipCode}",
  190. [
  191. 'found' => $coordinates !== null,
  192. 'coordinates' => $coordinates,
  193. ],
  194. now()->addSeconds(
  195. (int) config('services.google_geocoding.cache_ttl', 2592000)
  196. )
  197. );
  198. $this->persistProviderCoordinates($zipCode, $coordinates);
  199. }
  200. private function requestCoordinates(string $zipCode): ?array
  201. {
  202. $startedAt = microtime(true);
  203. try {
  204. Log::channel('google_geocoding')->info('ZipCodeCoordinates calling Google Geocoding', [
  205. 'zip_code' => $zipCode,
  206. 'base_url' => rtrim((string) config('services.google_geocoding.base_url'), '/'),
  207. 'connect_timeout' => (int) config('services.google_geocoding.connect_timeout', 2),
  208. 'timeout' => (int) config('services.google_geocoding.timeout', 5),
  209. 'ip_resolve' => 'ipv4',
  210. ]);
  211. $baseUrl = rtrim((string) config('services.google_geocoding.base_url'), '/');
  212. $response = Http::acceptJson()
  213. ->withOptions($this->curlForceIpv4Options())
  214. ->connectTimeout((int) config('services.google_geocoding.connect_timeout', 2))
  215. ->timeout((int) config('services.google_geocoding.timeout', 5))
  216. ->get("{$baseUrl}/maps/api/geocode/json", $this->googleQuery($zipCode));
  217. return $this->coordinatesFromResponse($response);
  218. } catch (Throwable $exception) {
  219. Log::channel('google_geocoding')->warning('ZipCodeCoordinates Google Geocoding request failed', [
  220. 'zip_code' => $zipCode,
  221. 'elapsed_ms' => round((microtime(true) - $startedAt) * 1000, 2),
  222. 'error' => $exception->getMessage(),
  223. ]);
  224. return null;
  225. }
  226. }
  227. private function restoreFromCache(string $zipCode): bool
  228. {
  229. $cacheKey = "zip-code-coordinates:{$zipCode}";
  230. $cached = Cache::get($cacheKey);
  231. if (! is_array($cached) || ! array_key_exists('found', $cached)) {
  232. return false;
  233. }
  234. if (! $cached['found']) {
  235. Cache::forget($cacheKey);
  236. return false;
  237. }
  238. $this->resolvedZipCodes[$zipCode] = $cached['found']
  239. ? $cached['coordinates']
  240. : null;
  241. return true;
  242. }
  243. }