/
Controller.class.php
237 lines (205 loc) · 8.09 KB
/
Controller.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
<?php
Library::import('recess.framework.AbstractController');
Library::import('recess.lang.Annotation');
Library::import('recess.framework.controllers.annotations.ViewAnnotation');
Library::import('recess.framework.controllers.annotations.RouteAnnotation');
Library::import('recess.framework.controllers.annotations.RoutesPrefixAnnotation');
/**
* The controller is responsible for interpretting a preprocessed Request,
* performing some action in response to the Request (usually CRUDS), and
* returning a Response which contains relevant state for a view to render
* the Response.
*
* @author Kris Jordan <krisjordan@gmail.com>
* @contributor Joshua Paine
*/
abstract class Controller extends AbstractController {
const CLASSNAME = 'Controller';
/** @var Request */
protected $request;
protected $headers;
/** @var Application */
protected $application;
/** The formats/content-types which a controller responds to. */
protected $formats = array(Formats::XHTML);
public function __construct($application = null) {
$this->application = $application;
}
public function init() { }
protected static function initClassDescriptor($class) {
$descriptor = new ClassDescriptor();
$descriptor->routes = array();
$descriptor->methodUrls = array();
$descriptor->routesPrefix = '';
$descriptor->viewClass = 'recess.framework.views.NativeView';
$descriptor->viewPrefix = '';
return $descriptor;
}
protected static function shapeDescriptorWithMethod($class, $method, $descriptor, $annotations) {
$unreachableMethods = array('serve','urlTo','__call','__construct','init','application');
if(in_array($method->getName(), $unreachableMethods)) return $descriptor;
if( empty($annotations) &&
$method->isPublic() &&
!$method->isStatic()
) {
$parameters = $method->getParameters();
$parameterNames = array();
foreach($parameters as $parameter) {
$parameterNames[] = '$' . $parameter->getName();
}
if(!empty($parameterNames)) {
$parameterPath = '/' . implode('/',$parameterNames);
} else {
$parameterPath = '';
}
// Default Routing for Public Methods Without Annotations
$descriptor->routes[] =
new Route( $class,
$method->getName(),
Methods::GET,
$descriptor->routesPrefix . $method->getName() . $parameterPath);
}
return $descriptor;
}
/**
* urlTo is a helper method that returns the url to a controller method.
* Examples:
* $controller->urlTo('someMethod'); => /route/to/someMethod/
* $controller->urlTo('someMethodOneParameter', 'param1'); => /route/to/someMethodOneParam/param1
* $controller->urlTo('OtherController::otherMethod'); => Returns the route to another controller's method
*
* Thanks to Joshua Paine for improving the API of urlTo!
*
* @param $methodName
* @return string The url linking to controller method.
*/
public function urlTo($methodName) {
$args = func_get_args();
array_shift($args);
// First check to see if this is a urlTo on another Controller Class
if(strpos($methodName,'::') !== false) {
list($controllerName, $methodName) = explode('::', $methodName, 2);
$controller = new $controllerName($this->application);
return $controller->urlTo($methodName);
}
$descriptor = Controller::getClassDescriptor($this);
if(isset($descriptor->methodUrls[$methodName])) {
$url = $descriptor->methodUrls[$methodName];
if($url[0] != '/') {
$url = $this->application->routingPrefix . $url;
} else {
$url = substr($url, 1);
}
if(!empty($args)) {
$reflectedMethod = new ReflectionMethod($this, $methodName);
$parameters = $reflectedMethod->getParameters();
if(count($parameters) < count($args)) {
throw new RecessException('urlTo(\'' . $methodName . '\') called with ' . count($args) . ' arguments, method "' . $methodName . '" takes ' . count($parameters) . '.', get_defined_vars());
}
$i = 0;
$params = array();
foreach($parameters as $parameter) {
if(isset($args[$i])) $params[] = '$' . $parameter->getName();
$i++;
}
$url = str_replace($params, $args, $url);
}
if(strpos($url, '$') !== false) {
throw new RecessException('Missing arguments in urlTo(' . $methodName . '). Provide values for missing arguments: ' . $url, get_defined_vars());
}
return trim($_ENV['url.base'] . $url);
} else {
throw new RecessException('No url for method ' . $methodName . ' exists.', get_defined_vars());
}
}
/**
* The serve method is where inversion of control occurs which delegates
* control to another method in the controller.
*
* The method name and arguments should have been extracted in the
* preprocessing step. Here we ensure that the method exists and that all
* required parameters are provided as arguments from the request string.
*
* Call the method and return its response.
*
* @param DefaultRequest $request The HTTP request being served.
*
* !Wrappable serve
*/
function wrappedServe(Request $request) {
$this->request = $request;
$shortWiredResponse = $this->init();
if($shortWiredResponse instanceof Response) {
$shortWiredResponse->meta->viewClass = 'recess.framework.views.NativeView';
$shortWiredResponse->meta->viewPrefix = '';
return $shortWiredResponse;
}
$methodName = $request->meta->controllerMethod;
$methodArguments = $request->meta->controllerMethodArguments;
$useAssociativeArguments = $request->meta->useAssociativeArguments;
// Does method exist? Do arguments match?
if (method_exists($this, $methodName)) {
$method = new ReflectionMethod($this, $methodName);
$parameters = $method->getParameters();
$callArguments = array();
try {
if($useAssociativeArguments) {
$callArguments = $this->getCallArgumentsAssociative($parameters, $methodArguments);
} else {
$callArguments = $this->getCallArgumentsSequential($parameters, $methodArguments);
}
} catch(RecessException $e) {
throw new RecessException('Error calling method "' . $methodName . '" in "' . get_class($this) . '". ' . $e->getMessage(), array());
}
$response = $method->invokeArgs($this, $callArguments);
} else {
throw new RecessException('Error calling method "' . $methodName . '" in "' . get_class($this) . '". Method does not exist.', array());
}
if(!$response instanceof Response) {
Library::import('recess.http.responses.OkResponse');
$response = new OkResponse($this->request);
}
$descriptor = self::getClassDescriptor($this);
if(!isset($response->meta->viewName)) $response->meta->viewName = $methodName;
$response->meta->viewClass = $descriptor->viewClass;
$response->meta->viewPrefix = $descriptor->viewPrefix;
$response->data = get_object_vars($this);
$response->data['controller'] = $this;
if(is_array($this->headers)) { foreach($this->headers as $header) $response->addHeader($header); }
unset($response->data['request']);
unset($response->data['headers']);
unset($response->data['formats']);
return $response;
}
private function getCallArgumentsAssociative($parameters, $arguments) {
$callArgs = array();
foreach($parameters as $parameter) {
if(!isset($arguments[$parameter->getName()])) {
if(!$parameter->isOptional()) {
throw new RecessException('Expects ' . count($parameters) . ' arguments, given ' . count($arguments) . ' and missing required parameter: "' . $parameter->name . '"', array());
}
} else {
$callArgs[] = $arguments[$parameter->getName()];
}
}
return $callArgs;
}
private function getCallArgumentsSequential($parameters, $arguments) {
$callArgs = array();
$parameterCount = count($parameters);
for($i = 0; $i < $parameterCount; $i++) {
if(!isset($arguments[$i])) {
if(!$parameters[$i]->isOptional()) {
throw new RecessException('Expects ' . count($parameters) . ' arguments, given ' . count($arguments) . ' and missing required parameter # ' . ($i + 1) . ' named: "' . $parameters[$i]->name . '"', array());
}
} else {
$callArgs[] = $arguments[$i];
}
}
return $callArgs;
}
public function application() {
return $this->application;
}
}
?>