Skip to content

Commit 8024901

Browse files
committed
Jsonp output and support for headers without values
1 parent b219f89 commit 8024901

File tree

1 file changed

+30
-12
lines changed

1 file changed

+30
-12
lines changed

system/core/response.php

+30-12
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,15 @@ class Response {
2929

3030
private $type = ''; //html, json, xml
3131

32-
private $typeHeaders = ['html' => 'text/html', 'xml' => 'text/xml', 'text' => 'text/plain', 'json' => 'application/json'];
32+
private $status = 200;
33+
34+
private $callback = 'callback';
35+
36+
private $typeHeaders = ['html' => 'text/html', 'xml' => 'text/xml', 'text' => 'text/plain', 'json' => 'application/json', 'jsonp' => 'application/javascript'];
3337

3438
protected static $instance;
3539

36-
public static function getInstance() {
40+
final public static function getInstance() {
3741
if (is_null(static::$instance)) {
3842
static::$instance = new static();
3943
}
@@ -45,10 +49,14 @@ private function __construct() {
4549
$this->addHeader('X-Powered-By', 'Vvveb'/* . V_VERSION*/);
4650
}
4751

48-
public function addHeader($header, $value) {
52+
public function addHeader($header, $value = null) {
4953
$this->headers[$header] = $value;
5054
}
5155

56+
public function removeHeader($header) {
57+
unset($this->headers[$header]);
58+
}
59+
5260
public function getHeaders() {
5361
return $this->headers;
5462
}
@@ -59,7 +67,7 @@ public function redirect($url, $status = 302) {
5967
exit();
6068
}
6169

62-
public function getType($type) {
70+
public function getType() {
6371
return $this->type;
6472
}
6573

@@ -78,20 +86,30 @@ public function output($data = null) {
7886
}
7987

8088
if (! headers_sent()) {
81-
foreach ($this->headers as $header => $value) {
82-
header("$header: $value", true);
89+
foreach ($this->headers as $name => $value) {
90+
if ($value) {
91+
$header = "$name: $value";
92+
} else {
93+
$header = $name;
94+
}
95+
96+
header($header, true);
8397
}
8498
}
85-
99+
86100
if ($this->type == 'text' && $data !== null) {
87101
echo $data;
88102
} else {
89-
if ($this->type == 'json' && $data !== null && (! defined('CLI'))) {
90-
if (is_array($data)) {
91-
echo json_encode($data);
92-
} else {
93-
echo $data;
103+
if (($this->type == 'json' || $this->type == 'jsonp') && $data !== null && (! defined('CLI'))) {
104+
if (is_array($data) || is_object($data)) {
105+
$data = json_encode($data, JSON_PRETTY_PRINT);
106+
107+
if ($this->type == 'jsonp') {
108+
$data = "/**/{$this->callback}($data)";
109+
}
94110
}
111+
112+
echo $data;
95113
} else {
96114
$view = View :: getInstance();
97115

0 commit comments

Comments
 (0)