2020-08-17 23:46:58 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
class ApiResponse implements JsonSerializable
|
|
|
|
{
|
2020-08-23 12:37:39 +02:00
|
|
|
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;
|
2020-08-17 23:46:58 +02:00
|
|
|
|
2020-08-23 12:37:39 +02:00
|
|
|
public const MIME_TYPE_PLAINTEXT = 'text/plain';
|
|
|
|
public const MIME_TYPE_JSON = 'application/json';
|
|
|
|
public const MIME_TYPE_SVG = 'image/svg+xml';
|
2020-08-17 23:46:58 +02:00
|
|
|
|
2020-08-23 12:37:39 +02:00
|
|
|
protected int $status = ServerStatus::OK;
|
|
|
|
protected string $mimeType = MimeType::PLAINTEXT;
|
|
|
|
protected array $parameters = [];
|
2020-08-17 23:46:58 +02:00
|
|
|
|
2020-08-23 12:37:39 +02:00
|
|
|
public function __construct(int $status = ServerStatus::OK)
|
|
|
|
{
|
|
|
|
$this->setStatus($status);
|
|
|
|
}
|
2020-08-17 23:46:58 +02:00
|
|
|
|
2020-08-23 12:37:39 +02:00
|
|
|
public function setParameter(string $key, $value): void
|
|
|
|
{
|
|
|
|
$this->parameters[$key] = $value;
|
|
|
|
}
|
2020-08-17 23:46:58 +02:00
|
|
|
|
2020-08-23 12:37:39 +02:00
|
|
|
public function setStatus(int $status): void
|
|
|
|
{
|
|
|
|
$this->status = $status;
|
|
|
|
}
|
2020-08-17 23:46:58 +02:00
|
|
|
|
2020-08-23 12:37:39 +02:00
|
|
|
public function setMessage(string $message): void
|
|
|
|
{
|
|
|
|
$this->setParameter('message', $message);
|
|
|
|
}
|
2020-08-17 23:46:58 +02:00
|
|
|
|
2020-08-23 12:37:39 +02:00
|
|
|
public function setMimeType(string $mimeType): void
|
|
|
|
{
|
|
|
|
$this->mimeType = $mimeType;
|
|
|
|
}
|
2020-08-17 23:46:58 +02:00
|
|
|
|
2020-08-23 12:37:39 +02:00
|
|
|
public function setBody(JsonSerializable $data): void
|
|
|
|
{
|
|
|
|
$this->parameters = $data->jsonSerialize();
|
|
|
|
}
|
2020-08-17 23:46:58 +02:00
|
|
|
|
2020-08-23 12:37:39 +02:00
|
|
|
public function SetMessageIdNotFound(string $instanceName): void
|
2020-08-17 23:46:58 +02:00
|
|
|
{
|
|
|
|
$this->setMessage(sprintf('Die für %s angeforderte ID existiert nicht!', $instanceName));
|
|
|
|
}
|
|
|
|
|
2020-08-23 12:37:39 +02:00
|
|
|
public function getStatus(): int
|
|
|
|
{
|
|
|
|
return $this->status;
|
|
|
|
}
|
2020-08-17 23:46:58 +02:00
|
|
|
|
2020-08-23 12:37:39 +02:00
|
|
|
public function getMimeType(): string
|
|
|
|
{
|
|
|
|
return $this->mimeType;
|
|
|
|
}
|
2020-08-17 23:46:58 +02:00
|
|
|
|
2020-08-23 12:37:39 +02:00
|
|
|
public function jsonSerialize()
|
|
|
|
{
|
|
|
|
return $this->parameters;
|
|
|
|
}
|
2020-08-17 23:46:58 +02:00
|
|
|
|
2020-08-23 12:37:39 +02:00
|
|
|
public function respond(): void
|
|
|
|
{
|
|
|
|
http_response_code($this->status);
|
|
|
|
header('Content-Type: ' . $this->mimeType);
|
|
|
|
}
|
2020-08-17 23:46:58 +02:00
|
|
|
}
|