Implement OutputFilter::_CreateBodyForResponse()
[hoplite.git] / http / output_filter.php
1 <?php
2 // Hoplite
3 // Copyright (c) 2011 Blue Static
4 //
5 // This program is free software: you can redistribute it and/or modify it
6 // under the terms of the GNU General Public License as published by the Free
7 // Software Foundation, either version 3 of the License, or any later version.
8 //
9 // This program is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 // more details.
13 //
14 // You should have received a copy of the GNU General Public License along with
15 // this program. If not, see <http://www.gnu.org/licenses/>.
16
17 namespace hoplite\http;
18
19 require_once HOPLITE_ROOT . '/http/response_code.php';
20
21 /*!
22 The OutputFilter is executed after all Actions have been processed. The
23 primary function is to generate the actual HTTP response body from the model
24 data contained within the http\Response. Depending on how the Request was
25 sent, this
26 */
27 class OutputFilter
28 {
29 /*! @var RootController */
30 private $controller;
31
32 /*! @const The key in Response#context that indicates which type of output to
33 produce, regardless of the request type.
34 */
35 const RESPONSE_TYPE = 'response_type';
36
37 /*!
38 Constructor that takes a reference to the RootController.
39 */
40 public function __construct(RootController $controller)
41 {
42 $this->controller = $controller;
43 }
44
45 /*! Accessor for the RootController. */
46 public function controller() { return $this->controller; }
47
48 /*! @brief Main entry point for output filtering
49 This is called from the RootController to begin processing the output and
50 generating the response.
51 */
52 public function FilterOutput(Request $request, Response $response)
53 {
54 // If there was an error during the processing of an action, allow hooking
55 // custom logic.
56 if ($response->response_code != ResponseCode::OK)
57 if (!$this->_ContinueHandlingResponseForCode($request, $response))
58 return;
59
60 // If there's already raw data for the body, just output that.
61 if ($response->body)
62 return;
63
64 // Otherwise, construct the body based on how the Request was received and
65 // any other information in the response.
66 $this->_CreateBodyForResponse($request, $response);
67
68 // Now just output the response.
69 foreach ($response->headers as $header => $value)
70 header("$header: $value");
71 print $response->body;
72 }
73
74 /*!
75 If the request did not generate an 200 response code, the filter gives the
76 client an opportunity to override the normal output control flow and perform
77 some other task. If you want the control flow to continue executing as
78 normal, return TRUE; otherwise, return FALSE to exit from ::FilterOutput().
79 @return boolean
80 */
81 protected function _ContinueHandlingResponseForCode(Request $request,
82 Response $response)
83 {
84 return TRUE;
85 }
86
87 /*!
88 Fills out the Response#data field. This could be an evaluated HTML template,
89 a JSON payload, XML, or any other type of response for the client.
90 */
91 protected function _CreateBodyForResponse(Request $request,
92 Response $response)
93 {
94 $type = NULL;
95
96 // See if the HTTP request contains the desired output format.
97 if ($request->data['format'] == 'xml')
98 $type = 'xml';
99 else if ($request->data['format'] == 'json')
100 $type = 'json';
101
102 // If the request didn't specify a type, try and figure it out using
103 // heuristics.
104
105 // If this was from an XHR, assume JSON.
106 if (!$type && isset($request->data['_SERVER']['X_REQUESTED_WITH']))
107 $type = 'json';
108
109 // Check if an Action specified an overriding response type.
110 if (isset($response->context[self::RESPONSE_TYPE]))
111 $type = $response->context[self::RESPONSE_TYPE];
112
113 // If no type has been determined, just assume HTML.
114 if (!$type)
115 $type = 'html';
116
117 if ($type == 'json') {
118 $response->headers['Content-Type'] = 'application/json';
119 $response->body = json_encode($response->data);
120 } else if ($type == 'xml') {
121 $response->headers['Content-Type'] = 'application/xml';
122 $response->body = $this->_EncodeXML($response->data);
123 } else if ($type == 'html') {
124 $response->headers['Content-Type'] = 'text/html';
125 }
126 }
127
128 /*!
129 Creates an XML tree from an array. Equivalent to json_encode.
130 */
131 protected function _EncodeXML($data)
132 {
133 $response = new \SimpleXMLElement('<response/>');
134
135 $writer = function($elm, $parent) use (&$writer) {
136 foreach ($elm as $key => $value) {
137 if (is_scalar($value)) {
138 $parent->AddChild($key, $value);
139 } else {
140 $new_parent = $parent->AddChild($key);
141 $writer($value, $new_parent);
142 }
143 }
144 };
145
146 $writer($data, $response);
147 return $response->AsXML();
148 }
149 }