ZipCodeCoordinatesService.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. data_get($origin, 'latitude'),
  33. data_get($origin, 'longitude'),
  34. data_get($target, 'latitude'),
  35. data_get($target, 'longitude'),
  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 data_get($this->resolvedZipCodes, $zipCode);
  47. }
  48. if ($this->restoreFromCache($zipCode)) {
  49. return data_get($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. try {
  82. Log::channel('google_geocoding')->info('Requisição em lote ao Google Geocoding', [
  83. 'request_count' => count($pending),
  84. 'zip_codes_sample' => array_slice(array_values($pending), 0, 20),
  85. ]);
  86. $baseUrl = rtrim((string) config('services.google_geocoding.base_url'), '/');
  87. $responses = Http::pool(fn (Pool $pool) => array_map(
  88. fn (string $zipCode) => $pool
  89. ->as($zipCode)
  90. ->acceptJson()
  91. ->connectTimeout((int) config('services.google_geocoding.connect_timeout', 2))
  92. ->timeout((int) config('services.google_geocoding.timeout', 5))
  93. ->withOptions($this->curlForceIpv4Options())
  94. ->get("{$baseUrl}/maps/api/geocode/json", $this->googleQuery($zipCode)),
  95. $pending,
  96. ));
  97. } catch (Throwable) {
  98. $responses = [];
  99. }
  100. foreach ($pending as $zipCode) {
  101. $response = data_get($responses, $zipCode);
  102. $coordinates = $response instanceof Response
  103. ? $this->coordinatesFromResponse($response)
  104. : null;
  105. $this->remember($zipCode, $coordinates);
  106. }
  107. }
  108. //
  109. private function coordinatesFromResponse(Response $response): ?array
  110. {
  111. if (! $response->successful()) {
  112. return null;
  113. }
  114. if ($response->json('status') !== 'OK') {
  115. return null;
  116. }
  117. $latitude = $response->json('results.0.geometry.location.lat');
  118. $longitude = $response->json('results.0.geometry.location.lng');
  119. if (! is_numeric($latitude) || ! is_numeric($longitude)) {
  120. return null;
  121. }
  122. $latitude = (float) $latitude;
  123. $longitude = (float) $longitude;
  124. if ($latitude < -90 || $latitude > 90 || $longitude < -180 || $longitude > 180) {
  125. return null;
  126. }
  127. return compact('latitude', 'longitude');
  128. }
  129. private function curlForceIpv4Options(): array
  130. {
  131. if (! defined('CURLOPT_IPRESOLVE') || ! defined('CURL_IPRESOLVE_V4')) {
  132. return [];
  133. }
  134. return [
  135. 'curl' => [
  136. CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
  137. ],
  138. ];
  139. }
  140. private function googleGeocodingIsConfigured(): bool
  141. {
  142. return trim((string) config('services.google_geocoding.api_key')) !== '';
  143. }
  144. private function googleQuery(string $zipCode): array
  145. {
  146. return [
  147. 'components' => "postal_code:{$zipCode}|country:BR",
  148. 'language' => 'pt-BR',
  149. 'region' => 'br',
  150. 'key' => (string) config('services.google_geocoding.api_key'),
  151. ];
  152. }
  153. private function normalize(?string $zipCode): ?string
  154. {
  155. $zipCode = preg_replace('/\D/', '', $zipCode ?? '');
  156. return strlen($zipCode) === 8 ? $zipCode : null;
  157. }
  158. private function persistProviderCoordinates(string $zipCode, array $coordinates): void
  159. {
  160. $formattedZipCode = substr($zipCode, 0, 5).'-'.substr($zipCode, 5);
  161. Address::query()
  162. ->where('source', 'provider')
  163. ->whereIn('zip_code', [$zipCode, $formattedZipCode])
  164. ->where(function ($query) {
  165. $query->whereNull('latitude')->orWhereNull('longitude');
  166. })
  167. ->update([
  168. 'latitude' => data_get($coordinates, 'latitude'),
  169. 'longitude' => data_get($coordinates, 'longitude'),
  170. ]);
  171. }
  172. private function remember(string $zipCode, ?array $coordinates): void
  173. {
  174. $this->resolvedZipCodes[$zipCode] = $coordinates;
  175. if ($coordinates === null) {
  176. return;
  177. }
  178. Cache::put(
  179. "zip-code-coordinates:{$zipCode}",
  180. [
  181. 'found' => $coordinates !== null,
  182. 'coordinates' => $coordinates,
  183. ],
  184. now()->addSeconds(
  185. (int) config('services.google_geocoding.cache_ttl', 2592000)
  186. )
  187. );
  188. $this->persistProviderCoordinates($zipCode, $coordinates);
  189. }
  190. private function requestCoordinates(string $zipCode): ?array
  191. {
  192. try {
  193. Log::channel('google_geocoding')->info('Requisição ao Google Geocoding', [
  194. 'zip_code' => $zipCode,
  195. ]);
  196. $baseUrl = rtrim((string) config('services.google_geocoding.base_url'), '/');
  197. $response = Http::acceptJson()
  198. ->withOptions($this->curlForceIpv4Options())
  199. ->connectTimeout((int) config('services.google_geocoding.connect_timeout', 2))
  200. ->timeout((int) config('services.google_geocoding.timeout', 5))
  201. ->get("{$baseUrl}/maps/api/geocode/json", $this->googleQuery($zipCode));
  202. return $this->coordinatesFromResponse($response);
  203. } catch (Throwable) {
  204. return null;
  205. }
  206. }
  207. private function restoreFromCache(string $zipCode): bool
  208. {
  209. $cacheKey = "zip-code-coordinates:{$zipCode}";
  210. $cached = Cache::get($cacheKey);
  211. if (! is_array($cached) || ! array_key_exists('found', $cached)) {
  212. return false;
  213. }
  214. if (! data_get($cached, 'found')) {
  215. Cache::forget($cacheKey);
  216. return false;
  217. }
  218. $this->resolvedZipCodes[$zipCode] = data_get($cached, 'found')
  219. ? data_get($cached, 'coordinates')
  220. : null;
  221. return true;
  222. }
  223. }