. * */ namespace Vvveb\System\Core; class Response { private $headers = []; private $done = false; private $type = ''; //html, json, xml private $status = 200; private $callback = 'callback'; private $typeHeaders = ['html' => 'text/html', 'xml' => 'text/xml', 'text' => 'text/plain', 'json' => 'application/json', 'jsonp' => 'application/javascript', 'activityjson' => 'application/activity+json', 'ldjson' => 'application/ld+json', 'jrdjson' => 'application/jrd+json']; protected static $instance; final public static function getInstance() { if (is_null(static::$instance)) { static::$instance = new static(); } return static::$instance; } private function __construct() { $this->addHeader('X-Powered-By', 'Vvveb ' . V_VERSION); } function getStatus() { return $this->status; } function setStatus($status) { return $this->status = $status; } public function addHeader($header, $value = null) { $this->headers[$header] = $value; } public function removeHeader($header) { unset($this->headers[$header]); } public function getHeaders() { return $this->headers; } public function redirect($url, $status = 302) { header('Location: ' . str_replace(['&', "\n", "\r"], ['&', '', ''], $url), true, $status); exit(); } public function getType() { return $this->type; } public function setType($type) { $contentType = $this->typeHeaders[$type] ?? false; if ($contentType) { $this->addHeader('Content-Type', $contentType); $this->type = $type; } } public function output($data = null) { if ($this->done) { return false; } if (! headers_sent()) { foreach ($this->headers as $name => $value) { if ($value) { $header = "$name: $value"; } else { $header = $name; } header($header, true); } if ($this->status !== 200) { header(' ', true, $this->status); } } if ($this->type == 'text' && $data !== null) { echo $data; } else { if (($this->type == 'json' || $this->type == 'jsonp' || $this->type == 'ldjson' || $this->type == 'activityjson' || $this->type == 'jrdjson') && $data !== null && (! defined('CLI'))) { if (is_array($data) || is_object($data)) { $data = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); if ($this->type == 'jsonp') { $data = "/**/{$this->callback}($data)"; } } echo $data; } else { $view = View :: getInstance(); if ($this->type) { $view->setType($this->type); } $view->render(); } } $this->done = true; } }