2016-04-12 19:31:39 +02:00
|
|
|
<?php
|
|
|
|
|
2018-03-04 11:22:14 +01:00
|
|
|
namespace PHPCensor\Http;
|
2016-04-12 19:31:39 +02:00
|
|
|
|
|
|
|
class Response
|
|
|
|
{
|
2016-04-20 17:39:48 +02:00
|
|
|
protected $data = [];
|
|
|
|
|
|
|
|
public function __construct(Response $createFrom = null)
|
|
|
|
{
|
|
|
|
if (!is_null($createFrom)) {
|
|
|
|
$this->data = $createFrom->getData();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getData()
|
|
|
|
{
|
|
|
|
return $this->data;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function setResponseCode($code)
|
|
|
|
{
|
|
|
|
$this->data['code'] = (int)$code;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function setHeader($key, $val)
|
|
|
|
{
|
|
|
|
$this->data['headers'][$key] = $val;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function clearHeaders()
|
|
|
|
{
|
|
|
|
$this->data['headers'] = [];
|
|
|
|
}
|
|
|
|
|
|
|
|
public function setContent($content)
|
|
|
|
{
|
|
|
|
$this->data['body'] = $content;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getContent()
|
|
|
|
{
|
|
|
|
return $this->data['body'];
|
|
|
|
}
|
|
|
|
|
|
|
|
public function flush()
|
|
|
|
{
|
|
|
|
$this->sendResponseCode();
|
|
|
|
|
|
|
|
if (isset($this->data['headers'])) {
|
|
|
|
foreach ($this->data['headers'] as $header => $val) {
|
|
|
|
header($header . ': ' . $val, true);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return $this->flushBody();
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function sendResponseCode()
|
|
|
|
{
|
|
|
|
if (!isset($this->data['code'])) {
|
|
|
|
$this->data['code'] = 200;
|
|
|
|
}
|
|
|
|
|
|
|
|
switch ($this->data['code']) {
|
|
|
|
// 300 class
|
|
|
|
case 301:
|
|
|
|
$text = 'Moved Permanently';
|
|
|
|
break;
|
|
|
|
case 302:
|
|
|
|
$text = 'Moved Temporarily';
|
|
|
|
break;
|
|
|
|
|
|
|
|
// 400 class errors
|
|
|
|
case 400:
|
|
|
|
$text = 'Bad Request';
|
|
|
|
break;
|
|
|
|
case 401:
|
|
|
|
$text = 'Not Authorized';
|
|
|
|
break;
|
|
|
|
case 403:
|
|
|
|
$text = 'Forbidden';
|
|
|
|
break;
|
|
|
|
case 404:
|
|
|
|
$text = 'Not Found';
|
|
|
|
break;
|
|
|
|
|
|
|
|
// 500 class errors
|
|
|
|
case 500:
|
|
|
|
$text = 'Internal Server Error';
|
|
|
|
break;
|
|
|
|
|
|
|
|
// OK
|
|
|
|
case 200:
|
|
|
|
default:
|
|
|
|
$text = 'OK';
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
header('HTTP/1.1 ' . $this->data['code'] . ' ' . $text, true, $this->data['code']);
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function flushBody()
|
|
|
|
{
|
|
|
|
if (isset($this->data['body'])) {
|
|
|
|
return $this->data['body'];
|
|
|
|
}
|
|
|
|
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
|
|
|
|
public function __toString()
|
|
|
|
{
|
|
|
|
return $this->flush();
|
|
|
|
}
|
2016-04-25 19:30:23 +02:00
|
|
|
}
|