1: <?php
2:
3: namespace PHPixie\HTTP;
4: use PHPixie\HTTP\Data\Headers;
5: use Psr\Http\Message\StreamInterface;
6:
7: 8: 9:
10: class Responses
11: {
12: 13: 14:
15: protected $builder;
16:
17: 18: 19: 20:
21: public function __construct($builder)
22: {
23: $this->builder = $builder;
24: }
25:
26: 27: 28: 29: 30:
31: public function string($string)
32: {
33: return $this->stringResponse($string);
34: }
35:
36: 37: 38: 39: 40: 41:
42: public function redirect($url, $statusCode = 302)
43: {
44: return $this->stringResponse(
45: '',
46: array(
47: 'Location' => $url
48: ),
49: $statusCode
50: );
51: }
52:
53: 54: 55: 56: 57: 58: 59:
60: public function json($data)
61: {
62: $string = json_encode($data);
63:
64: return $this->stringResponse(
65: $string,
66: array(
67: 'Cache-Control' => 'no-cache, must-revalidate',
68: 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
69: 'Content-type' => 'application/json'
70: )
71: );
72: }
73:
74: 75: 76: 77: 78:
79: public function streamFile($file)
80: {
81: $body = $this->builder->messages()->stream($file);
82: return $this->response($body);
83: }
84:
85: 86: 87: 88: 89: 90: 91:
92: public function download($fileName, $contentType, $contents)
93: {
94: $body = $this->builder->messages()->stringStream($contents);
95: return $this->downloadResponse($fileName, $contentType, $body);
96: }
97:
98: 99: 100: 101: 102: 103: 104:
105: public function downloadFile($fileName, $contentType, $file)
106: {
107: $body = $this->builder->messages()->stream($file);
108: return $this->downloadResponse($fileName, $contentType, $body);
109: }
110:
111: 112: 113: 114: 115: 116: 117: 118:
119: public function response($body, $headerArray = array(), $statusCode = 200, $reasonPhrase = null)
120: {
121: $headers = $this->builder->editableHeaders($headerArray);
122: return $this->buildResponse($headers, $body, $statusCode, $reasonPhrase);
123: }
124:
125: 126: 127: 128: 129: 130: 131: 132:
133: protected function stringResponse($string, $headers = array(), $statusCode = 200, $reasonPhrase = null)
134: {
135: $body = $this->builder->messages()->stringStream($string);
136: return $this->response($body, $headers, $statusCode, $reasonPhrase);
137: }
138:
139: 140: 141: 142: 143: 144: 145:
146: protected function downloadResponse($fileName, $contentType, $body)
147: {
148: $headers = array(
149: 'Content-Type' => $contentType,
150: 'Content-Disposition' => 'attachment; filename="'.$fileName.'"'
151: );
152:
153: return $this->response($body, $headers);
154: }
155:
156: 157: 158: 159: 160: 161: 162:
163: protected function buildResponse($headers, $body, $statusCode = 200, $reasonPhrase = null)
164: {
165: $messages = $this->builder->messages();
166: return new Responses\Response($messages, $headers, $body, $statusCode, $reasonPhrase);
167: }
168: }