| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192 |
- <?php
- namespace App\Services;
- use Illuminate\Http\Client\Pool;
- use Illuminate\Http\Client\Response;
- use Illuminate\Support\Facades\Cache;
- use Illuminate\Support\Facades\Http;
- use Throwable;
- class ZipCodeCoordinatesService
- {
- private array $resolvedZipCodes = [];
- public function resolve(?float $latitude, ?float $longitude, ?string $zipCode): ?array
- {
- if ($latitude !== null && $longitude !== null) {
- return compact('latitude', 'longitude');
- }
- return $this->findByZipCode($zipCode);
- }
- public function calculateDistance(
- ?float $originLatitude,
- ?float $originLongitude,
- ?string $originZipCode,
- ?float $targetLatitude,
- ?float $targetLongitude,
- ?string $targetZipCode,
- ): ?float {
- $origin = $this->resolve($originLatitude, $originLongitude, $originZipCode);
- $target = $this->resolve($targetLatitude, $targetLongitude, $targetZipCode);
- return DistanceService::calculate(
- $origin['latitude'] ?? null,
- $origin['longitude'] ?? null,
- $target['latitude'] ?? null,
- $target['longitude'] ?? null,
- );
- }
- public function findByZipCode(?string $zipCode): ?array
- {
- $zipCode = $this->normalize($zipCode);
- if ($zipCode === null) {
- return null;
- }
- if (array_key_exists($zipCode, $this->resolvedZipCodes)) {
- return $this->resolvedZipCodes[$zipCode];
- }
- if ($this->restoreFromCache($zipCode)) {
- return $this->resolvedZipCodes[$zipCode];
- }
- $coordinates = $this->requestCoordinates($zipCode);
- $this->remember($zipCode, $coordinates);
- return $coordinates;
- }
- public function preload(iterable $zipCodes): void
- {
- $pending = [];
- foreach ($zipCodes as $zipCode) {
- $zipCode = $this->normalize($zipCode);
- if (
- $zipCode === null
- || array_key_exists($zipCode, $this->resolvedZipCodes)
- || $this->restoreFromCache($zipCode)
- ) {
- continue;
- }
- $pending[$zipCode] = $zipCode;
- }
- if ($pending === []) {
- return;
- }
- try {
- $baseUrl = rtrim((string) config('services.brasil_api.base_url'), '/');
- $responses = Http::pool(fn (Pool $pool) => array_map(
- fn (string $zipCode) => $pool
- ->as($zipCode)
- ->acceptJson()
- ->connectTimeout((int) config('services.brasil_api.connect_timeout', 2))
- ->timeout((int) config('services.brasil_api.timeout', 3))
- ->get("{$baseUrl}/api/cep/v2/{$zipCode}"),
- $pending,
- ));
- } catch (Throwable) {
- $responses = [];
- }
- foreach ($pending as $zipCode) {
- $response = $responses[$zipCode] ?? null;
- $coordinates = $response instanceof Response
- ? $this->coordinatesFromResponse($response)
- : null;
- $this->remember($zipCode, $coordinates);
- }
- }
- private function normalize(?string $zipCode): ?string
- {
- $zipCode = preg_replace('/\D/', '', $zipCode ?? '');
- return strlen($zipCode) === 8 ? $zipCode : null;
- }
- private function restoreFromCache(string $zipCode): bool
- {
- $cached = Cache::get("zip-code-coordinates:{$zipCode}");
- if (! is_array($cached) || ! array_key_exists('found', $cached)) {
- return false;
- }
- $this->resolvedZipCodes[$zipCode] = $cached['found']
- ? $cached['coordinates']
- : null;
- return true;
- }
- private function remember(string $zipCode, ?array $coordinates): void
- {
- $this->resolvedZipCodes[$zipCode] = $coordinates;
- Cache::put(
- "zip-code-coordinates:{$zipCode}",
- [
- 'found' => $coordinates !== null,
- 'coordinates' => $coordinates,
- ],
- now()->addSeconds(
- $coordinates !== null
- ? (int) config('services.brasil_api.cep_cache_ttl', 2592000)
- : (int) config('services.brasil_api.cep_failure_cache_ttl', 600)
- )
- );
- }
- private function requestCoordinates(string $zipCode): ?array
- {
- try {
- $response = Http::baseUrl(rtrim((string) config('services.brasil_api.base_url'), '/'))
- ->acceptJson()
- ->connectTimeout((int) config('services.brasil_api.connect_timeout', 2))
- ->timeout((int) config('services.brasil_api.timeout', 3))
- ->get("api/cep/v2/{$zipCode}");
- return $this->coordinatesFromResponse($response);
- } catch (Throwable) {
- return null;
- }
- }
- private function coordinatesFromResponse(Response $response): ?array
- {
- if (! $response->successful()) {
- return null;
- }
- $latitude = $response->json('location.coordinates.latitude');
- $longitude = $response->json('location.coordinates.longitude');
- if (! is_numeric($latitude) || ! is_numeric($longitude)) {
- return null;
- }
- $latitude = (float) $latitude;
- $longitude = (float) $longitude;
- if ($latitude < -90 || $latitude > 90 || $longitude < -180 || $longitude > 180) {
- return null;
- }
- return compact('latitude', 'longitude');
- }
- }
|