1
1
Fork 0
mirror of https://code.mensbeam.com/MensBeam/Arsse.git synced 2024-12-23 09:02:41 +00:00
Arsse/lib/REST/Response.php

62 lines
1.8 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
2017-03-28 04:12:12 +00:00
namespace JKingWeb\Arsse\REST;
2017-08-29 14:50:31 +00:00
use JKingWeb\Arsse\Arsse;
class Response {
const T_JSON = "application/json";
const T_XML = "application/xml";
const T_TEXT = "text/plain";
public $head = false;
public $code;
public $payload;
public $type;
public $fields;
2017-08-29 14:50:31 +00:00
public function __construct(int $code, $payload = null, string $type = self::T_JSON, array $extraFields = []) {
$this->code = $code;
$this->payload = $payload;
$this->type = $type;
$this->fields = $extraFields;
}
2017-08-29 14:50:31 +00:00
public function output() {
if (!headers_sent()) {
foreach ($this->fields as $field) {
header($field);
}
$body = "";
2017-08-29 14:50:31 +00:00
if (!is_null($this->payload)) {
switch ($this->type) {
case self::T_JSON:
$body = (string) json_encode($this->payload, \JSON_PRETTY_PRINT);
break;
default:
$body = (string) $this->payload;
break;
}
}
if (strlen($body)) {
header("Content-Type: ".$this->type);
header("Content-Length: ".strlen($body));
} elseif ($this->code==200) {
$this->code = 204;
}
try {
$statusText = Arsse::$lang->msg("HTTP.Status.".$this->code);
} catch (\JKingWeb\Arsse\Lang\Exception $e) {
$statusText = "";
}
header("Status: ".$this->code." ".$statusText);
if (!$this->head) {
echo $body;
}
} else {
throw new REST\Exception("headersSent");
}
}
2017-08-29 14:50:31 +00:00
}