-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApplication.php
More file actions
536 lines (468 loc) · 12.8 KB
/
Application.php
File metadata and controls
536 lines (468 loc) · 12.8 KB
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
<?php
ClassLoader::import('framework.request.*');
ClassLoader::import('framework.renderer.*');
ClassLoader::import('framework.response.*');
ClassLoader::import('framework.controller.*');
ClassLoader::import('framework.ApplicationException');
/**
* Class for running an application.
*
* This class handles the whole application execution life-cycle:
* + request data collection
* + action dispatching
* + model loading
* + rendering output
*
* The purpose is to automate recurring tasks involved into application execution
* and result presentation and let a developer to concentrate on a model.
*
* A common application execution:
* <code>
* try {
* $myApplication = new Application();
* $myApplication->run();
* } catch(ApplicationException $ex) {
* echo $ex->getMessage();
* }
* </code>
*
* A few customizations are available before application is executed.
* Note: Avoid any output before application is executed because this will cause a response exception.
*
* @see self::setDefaultControllerName()
* @see self::setRenderer()
* @see self::setRequestFormatter()
*
* @package framework
* @author Integry Systems
*
*/
class Application
{
protected $routerClass = 'Router';
protected $requestClass = 'Request';
protected $rendererClass = 'PHPRenderer';
/**
* @var Router
*/
/* protected $router = null; */
/**
* Request instance
* @var Request
*/
protected $request = null;
/**
* Renderer instance (usualy a template renderer)
* @var Renderer
*/
protected $renderer = null;
/**
* Default controller name. It can be changed during a runtime (before run()'ing an
* application)
*
* @var string
* @see self::setDefaultControllerName()
*/
private $defaultControllerName = "index";
protected $controllerDirectories = array();
/**
* Application constructor.
*
* @see self::getInstance()
*/
public function __construct()
{
$this->request = new $this->requestClass();
}
/**
* Sets default controller name
*
* @param string $controller Name of controller
* @return void
*/
public function setDefaultControllerName($controllerName)
{
$this->defaultControllerName = $controllerName;
}
/**
* Gets default controller name
*
* @return string Controller name
*/
public function getDefaultControllerName()
{
return $this->defaultControllerName;
}
/**
* Sets renderer for application
*
* @param Renderer $renderer Instance of Renderer
* @return void
*/
public function setRenderer(Renderer $renderer)
{
$this->renderer = $renderer;
}
public function setRendererClass($className)
{
$this->rendererClass = $className;
}
/**
* Gets renderer for application
*
* @return Renderer
*/
public function getRenderer()
{
if (is_null($this->renderer))
{
$class = $this->rendererClass;
$this->renderer = new $class($this);
}
return $this->renderer;
}
/**
* Gets (or creates) a Request instance for accessing request data
*
* @return Request
*/
public function getRequest()
{
if ($this->request == null)
{
$this->request = $this->router->getRequest();
}
return $this->request;
}
public function setRequest(Request $request)
{
$this->request = $request;
}
/**
* Return a router instance
*
* @return Request
*/
public function getRouter()
{
return $this->router;
}
/**
* Executes an application and generates an output if any.
*
* @throws ApplicationException Rethrowed framework level exception (should be handled manually)
*/
public function run($redirect = false)
{
if (!$redirect)
{
$this->router->mapToRoute($this->router->getRequestedRoute(), $this->request);
}
$controllerName = $this->getRequest()->getControllerName();
$actionName = $this->getRequest()->getActionName();
if (empty($controllerName))
{
$controllerName = $this->getDefaultControllerName();
}
if (empty($actionName))
{
$actionName = Controller::DEFAULT_ACTION;
}
$output = '';
/* Execute an action of some controller */
try
{
$controllerInstance = $this->getControllerInstance($controllerName);
$this->controllerInstance = $controllerInstance;
$response = $this->execute($controllerInstance, $actionName);
$response->sendHeaders();
$response->sendData();
if ($response instanceof Renderable)
{
$output = $this->render($controllerInstance, $response);
// using layout defined in a controller for action output
if ($controllerInstance->getLayout() != null && !($response instanceof BlockResponse))
{
$this->getRenderer()->set("ACTION_VIEW", $output);
$output = $this->getRenderer()->render($this->getLayoutPath($controllerInstance->getLayout()));
}
}
else if ($response instanceof InternalRedirectResponse)
{
$this->getRequest()->setControllerName($response->getControllerName());
$this->getRequest()->setActionName($response->getActionName());
$this->getRequest()->setValueArray($response->getParamList());
return $this->run(true);
}
else
{
$output = $response->getData();
}
}
catch(ApplicationException $ex)
{
throw $ex;
}
$this->sendOutput($output);
}
protected function sendOutput($output)
{
echo $output;
}
public function getBlockContent($name, $params = null)
{
$output = '';
foreach ($this->renderBlockContainer($name, $params) as $rendered)
{
$output .= $rendered['output'];
}
return $output;
}
protected function renderBlockContainer($name, $params = null)
{
$render = array();
foreach ($this->controllerInstance->getBlocks($name) as $block)
{
$render[] = array('output' => $this->renderBlock($block, $this->controllerInstance, $params));
}
return $render;
}
protected function renderBlock($block, Controller $controllerInstance, $params = array())
{
$controllerInstance->setBlockName($block['container']);
$block['response'] = $controllerInstance->getBlockResponse($block);
$this->getRenderer()->getSmartyInstance()->assign($params);
if (!$block['response'])
{
$blockOutput = '';
$this->getRenderer()->appendValue($block['container'], $blockOutput);
return $blockOutput;
}
if (!($block['response'] instanceof BlockResponse))
{
throw new ApplicationException("Unknown response flom a block");
}
$this->postProcessResponse($block['response'], $controllerInstance);
//$blockOutput = $this->getRenderer()->process($block['response'], $block['view']);
// dynamically loaded blocks
if (substr($block['view'], 0, 2) == './')
{
// trim .tpl
$block['view'] = substr($block['view'], 0, -4);
$block['view'] = $this->getView($block['call'][0]->getControllerName(), $block['view']);
}
$blockOutput = $this->getRenderer()->process($block['response'], $block['view']);
$this->getRenderer()->appendValue($block['container'], $blockOutput);
return $blockOutput;
}
/**
* Executes controllers action and returns response
*
* @param Response $response Response object instance
* @return void
*/
protected function postProcessResponse(Response $response, Controller $controllerInstance)
{
}
/**
* Executes controllers action and returns response
*
* @param string $controllerName Controller name
* @param string $actionName Action name
* @return Response
* @throws ApplicationException if error situation occurs
*/
protected function execute($controllerInstance, $actionName)
{
try
{
$response = $controllerInstance->execute($actionName, $this->getRequest());
$this->processResponse($response);
$this->postProcessResponse($response, $controllerInstance);
return $response;
}
catch(ApplicationException $ex)
{
throw $ex;
}
}
/**
* Gets specified controller instance
*
* @param string $controllerName Controller name
* @return Controller
* @throws ControllerNotFoundException if controller does not exist
*/
protected function getControllerInstance($controllerName)
{
$controllerPath = explode(".", $controllerName);
$pathLength = count($controllerPath);
$className = ucfirst($controllerPath[$pathLength - 1]).'Controller';
$controllerPath[$pathLength - 1] = $className;
$controllerPath = implode("/", $controllerPath);
foreach ($this->getControllerDirectories() as $dir)
{
$controllerSystemPath = $dir . '/' . $controllerPath . '.php';
if (file_exists($controllerSystemPath))
{
$this->controllerDirectories[$controllerName] = $dir;
include_once($controllerSystemPath);
$refl = new ReflectionClass($className);
if (!$refl->isInstantiable())
{
continue;
}
$instance = new $className($this);
$instance->setControllerName($controllerName);
return $instance;
}
}
throw new ControllerNotFoundException($controllerName);
}
protected function getControllerDirectories()
{
$controllerSystemPaths = array();
$controllerSystemPaths[] = ClassLoader::getRealPath("application.controller");
return $controllerSystemPaths;
}
/**
* Processes response
*
* @param Response $response
* @return void
* @throws ApplicationException if error situation occurs
*/
protected function processResponse(Response $response)
{
/* Handle redirect to another action */
if ($response instanceof ActionRedirectResponse)
{
try
{
$this->getActionRedirectResponseUrl($response);
}
catch(ApplicationException $ex)
{
throw $ex;
}
}
/* Handle composite response */
if ($response instanceof CompositeResponse)
{
try
{
$responses = array();
foreach ($response->getRequestedActionList() as $outputHandle => $location)
{
$controllerName = $location[CompositeResponse::CONTROLLER_HANDLE];
$actionName = $location[CompositeResponse::ACTION_HANDLE];
if ($location['params'])
{
$originalRequest = $this->request;
$this->request = clone $this->request;
}
$instance = $this->getControllerInstance($controllerName);
// avoid parameter sanitization
if ($location['params'])
{
$this->request->setValueArray($location['params']);
}
$responses[$outputHandle] = array($this->execute($instance, $actionName), $instance, $actionName);
if ($location['params'])
{
$this->request = $originalRequest;
}
}
foreach (array_merge($responses, $response->getResponseList()) as $outputHandle => $data)
{
list($includedResponse, $controller, $actionName) = $data;
$this->processResponse($includedResponse);
$this->postProcessResponse($includedResponse, $controller);
if ($includedResponse instanceof Renderable)
{
$response->set($outputHandle, $this->render($controller, $includedResponse, $actionName));
}
else
{
$response->setResponse($outputHandle, $includedResponse);
}
}
}
catch(ApplicationException $ex)
{
throw $ex;
}
}
}
public function getActionRedirectResponseUrl(ActionRedirectResponse $response)
{
$paramList = array("controller" => $response->getControllerName(), "action" => $response->getActionName());
$paramList = array_merge($paramList, $response->getParamList());
$response->setRedirectURL($this->router->createURL($paramList));
return $response->getRedirectURL();
}
/**
* Renders response from controller action
*
* @param string $controllerInstance Controller
* @param Response $response Response to render
* @return string Renderer content
* @throws ViewNotFoundException if view does not exists for specified controller
*/
protected function render(Controller $controllerInstance, Response $response, $actionName = null)
{
$controllerName = $this->getRequest()->getControllerName();
$actionName = $actionName ? $actionName : $this->getRequest()->getActionName();
try
{
return $this->getRenderer()->process($response, $this->getView($controllerName, $actionName));
}
catch(ViewNotFoundException $ex)
{
throw $ex;
}
}
/**
* Gets view path for specified controllers action
*
* @param string $controllerName Controller name
* @param string $actionName Action name
* @return string View path
*/
public function getView($controllerName, $actionName)
{
$controllerName = str_replace('\\', '/', $controllerName);
$dir = dirname($this->controllerDirectories[str_replace('/', '.', $controllerName)]) . '/view';
return $dir . '/' . str_replace('.', '/', $controllerName) . '/' . $actionName . '.tpl'; //$this->getRenderer()->getViewExtension();
}
/**
* Gets a physical layout template path
*
* @param string $layout layout handle (filename without extension)
* @return string
*/
public function getLayoutPath($layout)
{
return ClassLoader::getRealPath('application.view.layout.' . $layout) . '.tpl'; //$this->getRenderer()->getViewExtension();
}
public function __get($name)
{
switch ($name)
{
case 'router':
$this->router = new $this->routerClass($this->request);
return $this->router;
break;
default:
break;
}
}
}
if (!function_exists('array_last'))
{
function array_last($array)
{
return end($array);
}
}
?>