Simplify WeakInterface by replacing the MethodImp with a hash.
[hoplite.git] / http / root_controller.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 . '/base/weak_interface.php';
20 require_once HOPLITE_ROOT . '/http/request.php';
21 require_once HOPLITE_ROOT . '/http/response.php';
22 require_once HOPLITE_ROOT . '/http/response_code.php';
23
24 /*!
25 The RootController is meant to be invoked from the index.php of the
26 application.
27 */
28 class RootController
29 {
30 /*! @var Request */
31 private $request = NULL;
32
33 /*! @var Response */
34 private $response = NULL;
35
36 /*! @var UrlMap */
37 private $url_map = NULL;
38
39 /*! @var OutputFilter */
40 private $output_filter = NULL;
41
42 /*! @var WeakInterface<RootControllerDelegate> */
43 private $delegate = NULL;
44
45 /*!
46 Creates the controller with the request context information, typicallhy
47 from the global scope ($GLOBALS), but can be injected for testing.
48 @param UrlMap The routing map
49 @param OutputFilter The object responsible for decorating output.
50 @param array& PHP globals array
51 */
52 public function __construct(array $globals)
53 {
54 $this->response = new Response();
55 $this->request = new Request();
56 $this->request->data = array(
57 '_GET' => &$globals['_GET'],
58 '_POST' => &$globals['_POST'],
59 '_COOKIE' => &$globals['_COOKIE'],
60 '_SERVER' => &$globals['_SERVER']
61 );
62 $this->delegate = new \hoplite\base\WeakInterface('hoplite\http\RootControllerDelegate');
63 }
64
65 /*! Accessors */
66 public function request() { return $this->request; }
67 public function response() { return $this->response; }
68
69 /*! Sets the UrlMap. */
70 public function set_url_map(UrlMap $url_map) { $this->url_map = $url_map; }
71
72 /*! Sest the Output Filter. */
73 public function set_output_filter(OutputFilter $output_filter)
74 {
75 $this->output_filter = $output_filter;
76 }
77
78 /*! Sets the delegate. */
79 public function set_delegate($delegate)
80 {
81 $this->delegate->Bind($delegate);
82 }
83 public function delegate()
84 {
85 return $this->delegate->Get();
86 }
87
88 /*!
89 Createst the Request and Response that are used throughout the duration of
90 the execution.
91 */
92 public function Run()
93 {
94 // The query rewriter module of the webserver rewrites a request from:
95 // http://example.com/webapp/user/view/42
96 // to:
97 // http://example.com/webapp/index.php/user/view/42
98 // ... which then becomes accessible from PATH_INFO.
99 $data = $this->request->data['_SERVER'];
100 if (isset($data['PATH_INFO']))
101 $url = $data['PATH_INFO'];
102 else
103 $url = '/';
104 if ($url[0] == '/')
105 $url = substr($url, 1);
106
107 // Set the final pieces of the request.
108 $this->request->url = $url;
109 $this->request->http_method = $this->request->data['_SERVER']['REQUEST_METHOD'];
110
111 // Extract any PUT data as POST params.
112 if ($this->request->http_method == 'PUT')
113 parse_str(file_get_contents('php://input'), $this->request->data['_POST']);
114
115 // Register self as the active instance.
116 $GLOBALS[__CLASS__] = $this;
117
118 $this->delegate->OnInitialRequest($this->request, $this->response);
119
120 // Dispatch the request to an Action.
121 $this->RouteRequest($this->request);
122
123 // When control returns here, all actions have been invoked and it's time
124 // to start the output filter and exit.
125 $this->Stop();
126 }
127
128 /*!
129 Prevents any other Actions from executing. This starts the OutputFilter and
130 then exits.
131 */
132 public function Stop()
133 {
134 $this->delegate->WillStop($this->request, $this->response);
135 $this->output_filter->FilterOutput($this->request, $this->response);
136 $this->_Exit();
137 }
138
139 /*!
140 Sets the response code and stops the controller. Returns void.
141 */
142 public function StopWithCode($code)
143 {
144 $this->response->response_code = $code;
145 $this->Stop();
146 }
147
148 /*!
149 Wrapper around PHP exit().
150 */
151 protected function _Exit()
152 {
153 exit;
154 }
155
156 /*!
157 Invoked by Run() and can be invoked by others to evaluate and perform the
158 lookup in the UrlMap. This then calls InvokeAction().
159 @param Request The Request whose URL will be routed
160 */
161 public function RouteRequest(Request $request)
162 {
163 $this->delegate->WillRouteRequest($request, $this->response);
164
165 $url_map_value = $this->url_map->Evaluate($request);
166
167 $action = NULL;
168 if ($url_map_value)
169 $action = $this->url_map->LookupAction($url_map_value);
170
171 if (!$action) {
172 $this->response->response_code = ResponseCode::NOT_FOUND;
173 $this->Stop();
174 return;
175 }
176
177 $this->InvokeAction($action);
178 }
179
180 /*!
181 Used to run an Action and drive it through its states.
182 @param Action
183 */
184 public function InvokeAction(Action $action)
185 {
186 $this->delegate->WillInvokeAction($action, $this->request, $this->response);
187
188 $action->FilterRequest($this->request, $this->response);
189 $action->Invoke($this->request, $this->response);
190 $action->FilterResponse($this->request, $this->response);
191
192 $this->delegate->DidInvokeAction($action, $this->request, $this->response);
193 }
194
195 /*!
196 Performs a reverse-lookup in the UrlMap for the pattern/fragment for the
197 name of a given Action class.
198 @param string Class name.
199 */
200 public function LookupAction($class)
201 {
202 $map = $this->url_map->map();
203 foreach ($map as $pattern => $action) {
204 if ($action == $class)
205 return $pattern;
206 }
207 }
208
209 /*!
210 Given a relative path, return an absolute path from the root controller.
211 @param string The relative path for which a URL will be created
212 @param bool Include the HTTP scheme and host to create an RFC URL if true;
213 if false an absolute path will be returned.
214 */
215 public function MakeURL($new_path, $url = FALSE)
216 {
217 // Detect the common paths between the REQUEST_URI and the PATH_INFO. That
218 // common piece will be the path to the root controller.
219 $request_uri = $this->request()->data['_SERVER']['REQUEST_URI'];
220 $path_info = $this->request()->data['_SERVER']['PATH_INFO'];
221 if ($path_info === NULL)
222 $common_uri = substr($request_uri, 0, -1);
223 else
224 $common_uri = strstr($request_uri, $path_info, TRUE);
225
226 // If just constructing an absolute path, return that now.
227 if (!$url)
228 return $common_uri . $new_path;
229
230 // Otherwise, build the host part.
231 $url = 'http';
232 if (isset($this->request()->data['_SERVER']['HTTPS']) &&
233 $this->request()->data['_SERVER']['HTTPS'] == 'on') {
234 $url .= 's';
235 }
236 $url .= '://' . $this->request()->data['_SERVER']['HTTP_HOST'];
237
238 $port = $this->request()->data['_SERVER']['SERVER_PORT'];
239 if ($port != 80 && $port != 443)
240 $url .= ':' . $port;
241
242 $url .= $common_uri;
243 return $url . $new_path;
244 }
245 }
246
247 /*!
248 Delegate for the root controller. The controller uses WeakInterface to call
249 these methods, so they're all optional.
250 */
251 interface RootControllerDelegate
252 {
253 public function OnInitialRequest(Request $request, Response $response);
254
255 public function WillRouteRequest(Request $request, Response $response);
256
257 public function WillInvokeAction(Action $action, Request $request, Response $response);
258
259 public function DidInvokeAction(Action $action, Request $request, Response $response);
260
261 public function WillStop(Request $request, Response $response);
262 }