ringfinger/backend/classes/api/ApiResponse.php

78 lines
1.6 KiB
PHP

<?php
declare(strict_types=1);
class ApiResponse implements JsonSerializable
{
public const STATUS_OK = 200;
public const STATUS_FORBIDDEN = 403;
public const STATUS_UNAUTHORIZED = 401;
public const STATUS_BAD_REQUEST = 400;
public const STATUS_NOT_FOUND = 404;
public const STATUS_SERVER_ERROR = 500;
public const MIME_TYPE_PLAINTEXT = 'text/plain';
public const MIME_TYPE_JSON = 'application/json';
public const MIME_TYPE_SVG = 'image/svg+xml';
protected int $status = ServerStatus::OK;
protected string $mimeType = MimeType::PLAINTEXT;
protected array $parameters = [];
public function __construct(int $status = ServerStatus::OK)
{
$this->setStatus($status);
}
public function setParameter(string $key, $value): void
{
$this->parameters[$key] = $value;
}
public function setStatus(int $status): void
{
$this->status = $status;
}
public function setMessage(string $message): void
{
$this->setParameter('message', $message);
}
public function setMimeType(string $mimeType): void
{
$this->mimeType = $mimeType;
}
public function setBody(JsonSerializable $data): void
{
$this->parameters = $data->jsonSerialize();
}
public function SetMessageIdNotFound(string $instanceName): void
{
$this->setMessage(sprintf('Die für %s angeforderte ID existiert nicht!', $instanceName));
}
public function getStatus(): int
{
return $this->status;
}
public function getMimeType(): string
{
return $this->mimeType;
}
public function jsonSerialize()
{
return $this->parameters;
}
public function respond(): void
{
http_response_code($this->status);
header('Content-Type: ' . $this->mimeType);
}
}