records('D087', ['place' => 'XA-NO']) as $r) echo $r['place']['name'], "\n"; * $t = $dl->analytics('XA', ['D087:count', 'pop'], ['level' => 'state', 'pc' => 1]); */ namespace Datlase; final class Error extends \RuntimeException {} final class Client { public function __construct(private string $token, private string $base = 'https://datlase.com/api/v1', private int $retries = 3) { $this->base = rtrim($base, '/'); } public function request(string $method, string $path, array $params = [], ?array $body = null): array { $params = array_filter(array_map(fn($v) => is_array($v) ? implode(',', $v) : $v, $params), fn($v) => $v !== null && $v !== ''); $url = $this->base . $path . ($params ? '?' . http_build_query($params) : ''); for ($attempt = 0; ; $attempt++) { $ch = curl_init($url); curl_setopt_array($ch, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 60, CURLOPT_HEADER => true, CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $this->token, 'Accept: application/json', 'Content-Type: application/json', 'User-Agent: datlase-php/1.0.0'], CURLOPT_POSTFIELDS => $body === null ? null : json_encode($body, JSON_UNESCAPED_UNICODE)]); $raw = curl_exec($ch); $code = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE); $hs = (int)curl_getinfo($ch, CURLINFO_HEADER_SIZE); curl_close($ch); $resp = $raw === false ? '' : substr($raw, $hs); if ($code >= 200 && $code < 300) return json_decode($resp, true) ?? []; if (($code === 429 || $code >= 500 || $raw === false) && $attempt < $this->retries) { sleep($code === 429 ? 5 : 2 ** $attempt); continue; } throw new Error($code . ': ' . (json_decode($resp, true)['error'] ?? $resp)); } } public function paginate(string $path, array $params = [], ?int $limit = null): \Generator { $n = 0; while (true) { $page = $this->request('GET', $path, $params); foreach ($page['data'] ?? [] as $row) { yield $row; if ($limit && ++$n >= $limit) return; } if (empty($page['next_cursor'])) return; $params['cursor'] = $page['next_cursor']; } } public function datasets(array $f = []): array { return $this->request('GET', '/datasets', $f)['data']; } public function dataset(string $id): array { return $this->request('GET', "/datasets/$id"); } public function records(string $id, array $f = [], ?int $limit = null): \Generator { return $this->paginate("/datasets/$id/records", ['limit' => 500] + $f, $limit); } public function places(string $q): array { return $this->request('GET', '/places', ['q' => $q])['data']; } public function metrics(): array { return $this->request('GET', '/analytics/metrics')['data']; } public function analytics(string $scope, array $metrics, array $o = []): array { return $this->request('GET', '/analytics', ['scope' => $scope, 'metrics' => $metrics] + $o); } public function series(string $scope, string $metric, array $o = []): array { return $this->request('GET', '/analytics/series', ['scope' => $scope, 'metrics' => $metric] + $o); } public function alerts(): array { return $this->request('GET', '/alerts')['data']; } public function createAlert(array $a): array { return $this->request('POST', '/alerts', [], $a); } public function webhooks(): array { return $this->request('GET', '/webhooks')['data']; } public function createWebhook(string $url, ?string $datasets = null, ?string $places = null): array { return $this->request('POST', '/webhooks', [], ['url' => $url, 'datasets' => $datasets, 'places' => $places]); } public function deleteWebhook(int $id): array { return $this->request('DELETE', "/webhooks/$id"); } public function template(string $id): array { return $this->request('GET', "/templates/$id"); } public function submit(string $id, array $records, string $mode = 'append', bool $publish = true, int $chunk = 5000): array { $out = []; foreach (array_chunk($records, $chunk) as $i => $part) $out[] = $this->request('POST', "/datasets/$id/records", [], ['records' => $part, 'mode' => $i === 0 ? $mode : 'append', 'publish' => $publish]); return $out; } public function submission(int $n): array { return $this->request('GET', "/submissions/$n"); } public static function verifyWebhook(string $secret, string $timestamp, string $body, string $signature, int $tolerance = 300): bool { return abs(time() - (int)$timestamp) <= $tolerance && hash_equals('sha256=' . hash_hmac('sha256', $timestamp . '.' . $body, $secret), $signature); } }