DSB-PlugIn/AddOn/Datenexport_Zeiterfassung/TimeTrackingAPI.php

91 lines
2.7 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?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|string
{
$url = "api/export/{$guid}";
$response = $this->rawRequest('GET', $url);
// Versuche, JSON zu dekodieren
$decoded = json_decode($response, true);
if (json_last_error() === JSON_ERROR_NONE) {
return $decoded;
}
// Kein JSON gib den Rohinhalt zurück (CSV, Text etc.)
return $response;
}
}