79 lines
2.4 KiB
PHP
79 lines
2.4 KiB
PHP
<?php
|
|
|
|
class TimeTrackingAPI
|
|
{
|
|
private string $baseUrl;
|
|
private string $token;
|
|
private string $apiSite;
|
|
|
|
public function __construct(string $baseUrl, string $token, string $apiSite = '')
|
|
{
|
|
$this->baseUrl = rtrim($baseUrl, '/');
|
|
$this->token = $token;
|
|
$this->apiSite = trim($apiSite, '/');
|
|
}
|
|
|
|
private function request(string $method, string $endpoint, array $headers = [], ?array $body = null): array
|
|
{
|
|
$url = "{$this->baseUrl}/{$this->apiSite}/{$endpoint}";
|
|
$ch = curl_init($url);
|
|
|
|
$defaultHeaders = [
|
|
"Authorization: {$this->token}",
|
|
];
|
|
if ($body !== null) {
|
|
$defaultHeaders[] = 'Content-Type: application/json';
|
|
$body = json_encode($body);
|
|
}
|
|
|
|
curl_setopt_array($ch, [
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_CUSTOMREQUEST => strtoupper($method),
|
|
CURLOPT_HTTPHEADER => array_merge($defaultHeaders, $headers),
|
|
CURLOPT_POSTFIELDS => $body,
|
|
]);
|
|
|
|
$response = curl_exec($ch);
|
|
if (curl_errno($ch)) {
|
|
throw new RuntimeException('cURL Error: ' . curl_error($ch));
|
|
}
|
|
|
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
curl_close($ch);
|
|
|
|
$data = json_decode($response, true);
|
|
if ($httpCode >= 400) {
|
|
throw new RuntimeException("API request failed with status $httpCode: " . ($data['Message'] ?? $response));
|
|
}
|
|
|
|
return $data;
|
|
}
|
|
|
|
public function getExportDefinitions(): array
|
|
{
|
|
return $this->request('GET', 'api/export/');
|
|
}
|
|
|
|
public function getOrganizationUnits(): array
|
|
{
|
|
return $this->request('GET', 'api/organization/');
|
|
}
|
|
|
|
public function requestExport(string $exportDefinitionId, string $organizationUnitId, string $dateFrom, string $dateUntil): string
|
|
{
|
|
$body = [
|
|
'ExportDefinition' => $exportDefinitionId,
|
|
'organizationUnit' => $organizationUnitId,
|
|
'DateFrom' => $dateFrom,
|
|
'DateUntil' => $dateUntil,
|
|
];
|
|
$response = $this->request('POST', 'api/export', [], $body);
|
|
return $response['Result'] ?? throw new RuntimeException('Unexpected response: ' . json_encode($response));
|
|
}
|
|
|
|
public function getExportData(string $guid): array
|
|
{
|
|
return $this->request('GET', "api/export/{$guid}");
|
|
}
|
|
}
|