2017-03-19 02:30:36 +00:00
|
|
|
<?php
|
2017-11-17 01:23:18 +00:00
|
|
|
/** @license MIT
|
|
|
|
* Copyright 2017 J. King, Dustin Wilson et al.
|
|
|
|
* See LICENSE and AUTHORS files for details */
|
|
|
|
|
2017-03-19 02:30:36 +00:00
|
|
|
declare(strict_types=1);
|
2017-03-28 04:12:12 +00:00
|
|
|
namespace JKingWeb\Arsse\REST;
|
2017-08-29 14:50:31 +00:00
|
|
|
|
2017-07-21 21:15:43 +00:00
|
|
|
use JKingWeb\Arsse\Arsse;
|
2017-03-19 02:30:36 +00:00
|
|
|
|
|
|
|
class Response {
|
2017-04-07 01:41:21 +00:00
|
|
|
const T_JSON = "application/json";
|
|
|
|
const T_XML = "application/xml";
|
|
|
|
const T_TEXT = "text/plain";
|
2017-03-20 01:50:00 +00:00
|
|
|
|
2017-09-29 21:40:07 +00:00
|
|
|
public $head = false;
|
2017-04-07 01:41:21 +00:00
|
|
|
public $code;
|
|
|
|
public $payload;
|
|
|
|
public $type;
|
|
|
|
public $fields;
|
2017-03-20 01:50:00 +00:00
|
|
|
|
2017-04-07 01:41:21 +00:00
|
|
|
|
2017-08-29 14:50:31 +00:00
|
|
|
public function __construct(int $code, $payload = null, string $type = self::T_JSON, array $extraFields = []) {
|
2017-04-07 01:41:21 +00:00
|
|
|
$this->code = $code;
|
|
|
|
$this->payload = $payload;
|
|
|
|
$this->type = $type;
|
|
|
|
$this->fields = $extraFields;
|
|
|
|
}
|
2017-07-21 21:15:43 +00:00
|
|
|
|
2017-08-29 14:50:31 +00:00
|
|
|
public function output() {
|
|
|
|
if (!headers_sent()) {
|
2017-09-29 21:40:07 +00:00
|
|
|
foreach ($this->fields as $field) {
|
|
|
|
header($field);
|
2017-07-27 13:21:00 +00:00
|
|
|
}
|
2017-07-21 21:15:43 +00:00
|
|
|
$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);
|
2017-07-21 21:15:43 +00:00
|
|
|
break;
|
|
|
|
default:
|
|
|
|
$body = (string) $this->payload;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
2017-09-29 21:40:07 +00:00
|
|
|
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;
|
2017-07-21 21:15:43 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
throw new REST\Exception("headersSent");
|
|
|
|
}
|
|
|
|
}
|
2017-08-29 14:50:31 +00:00
|
|
|
}
|