File manager - Edit - /var/www/html/observa/app/Services/ObservatorioApi.php
Back
<?php namespace App\Services; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; /** * Cliente da API pública do Observatório (hospedada em angra.rj.gov.br). * * Encapsula as chamadas HTTP e aplica um cache curto para evitar * requisições repetidas. Em caso de falha, retorna estruturas vazias * para que as páginas continuem renderizando. */ class ObservatorioApi { private string $baseUrl; private int $ttl; private int $timeout; public function __construct() { $this->baseUrl = rtrim((string) config('observatorio.api_url'), '/'); $this->ttl = (int) config('observatorio.cache_ttl', 120); $this->timeout = (int) config('observatorio.timeout', 10); } /** @return array<int, array<string, mixed>> */ public function temas(): array { return $this->get('observatorio/temas')['data'] ?? []; } /** @return array<string, mixed>|null */ public function tema(int $id): ?array { return $this->get("observatorio/temas/{$id}")['data'] ?? null; } /** @return array<string, mixed>|null */ public function indicador(int $id): ?array { return $this->get("observatorio/indicadores/{$id}")['data'] ?? null; } /** @return array<int, array<string, mixed>> */ public function destaques(): array { return $this->get('observatorio/destaques')['data'] ?? []; } /** @return array<int, array<string, mixed>> */ public function mapaTemas(): array { return $this->get('observatorio/mapa-temas')['data'] ?? []; } /** @return array<string, mixed>|null */ public function mapaTema(int $id): ?array { return $this->get("observatorio/mapa-temas/{$id}")['data'] ?? null; } /** * Executa um GET com cache e tratamento de erro. * * @return array<string, mixed> */ private function get(string $path): array { if ($this->ttl <= 0) { return $this->fetch($path); } $cacheKey = 'observatorio_api:' . md5($path); return Cache::remember($cacheKey, $this->ttl, fn () => $this->fetch($path)); } /** * @return array<string, mixed> */ private function fetch(string $path): array { try { $response = Http::timeout($this->timeout) ->acceptJson() ->get("{$this->baseUrl}/{$path}"); if ($response->successful()) { return $response->json() ?? []; } Log::warning('Observatório API respondeu com erro', [ 'path' => $path, 'status' => $response->status(), ]); } catch (\Throwable $e) { Log::error('Falha ao consultar a API do Observatório', [ 'path' => $path, 'message' => $e->getMessage(), ]); } return []; } }
| ver. 1.4 |
Github
|
.
| PHP 8.3.28 | Generation time: 0.02 |
proxy
|
phpinfo
|
Settings