Application.php
1 <?php
2 /**
3  * wCMF - wemove Content Management Framework
4  * Copyright (C) 2005-2015 wemove digital solutions GmbH
5  *
6  * Licensed under the terms of the MIT License.
7  *
8  * See the LICENSE file distributed with this work for
9  * additional information.
10  */
11 namespace wcmf\lib\presentation;
12 
17 
18 /**
19  * Application is the main application class, that does all the initialization.
20  *
21  * @author ingo herwig <ingo@wemove.com>
22  */
23 class Application {
24 
25  private $_startTime = null;
26  private $_initialRequest = null;
27 
28  private $_debug = true;
29 
30  private static $_logger = null;
31 
32  /**
33  * Constructor
34  */
35  public function __construct() {
36  $this->_startTime = microtime(true);
37  if (self::$_logger == null) {
38  self::$_logger = LogManager::getLogger(__CLASS__);
39  }
40  ob_start(array($this, "outputHandler"));
41  new ErrorHandler();
42  }
43 
44  /**
45  * Destructor
46  */
47  public function __destruct() {
48  // log resource usage
49  if (self::$_logger->isDebugEnabled()) {
50  $timeDiff = microtime(true)-$this->_startTime;
51  $memory = number_format(memory_get_peak_usage()/(1024*1024), 2);
52  $msg = ": Time[".round($timeDiff, 2)."s] Memory[".$memory."mb]";
53  if ($this->_initialRequest != null) {
54  $msg .= " Request[".$this->_initialRequest->getSender()."?".
55  $this->_initialRequest->getContext()."?".$this->_initialRequest->getAction()."]";
56  }
57  $msg .= " URI[".$_SERVER['REQUEST_URI']."]";
58  self::$_logger->debug($msg);
59  }
60  ob_end_flush();
61  }
62 
63  /**
64  * Initialize the request.
65  *
66  * @param $defaultController The controller to call if none is given in request parameters (optional, default: '')
67  * @param $defaultContext The context to set if none is given in request parameters (optional, default: '')
68  * @param $defaultAction The action to perform if none is given in request parameters (optional, default: 'login')
69  * @return Request instance representing the current HTTP request
70  */
71  public function initialize($defaultController='', $defaultContext='', $defaultAction='login') {
72  $config = ObjectFactory::getInstance('configuration');
73 
74  // create the Request instance
75  $this->_initialRequest = ObjectFactory::getInstance('request');
76  $this->_initialRequest->initialize($defaultController, $defaultContext, $defaultAction);
77 
78  // initialize session
79  $session = ObjectFactory::getInstance('session');
80 
81  // clear errors
82  $session->clearErrors();
83 
84  // load user configuration
85  $authUser = $session->getAuthUser();
86  if ($authUser && strlen($authUser->getConfig()) > 0) {
87  $config->addConfiguration($authUser->getConfig(), true);
88  }
89 
90  // load event listeners
91  $listeners = $config->getValue('listeners', 'application');
92  foreach ($listeners as $key) {
94  }
95 
96  // set timezone
97  date_default_timezone_set($config->getValue('timezone', 'application'));
98 
99  // return the request
100  return $this->_initialRequest;
101  }
102 
103  /**
104  * Run the application with the given request
105  * @param $request
106  * @return Response instance
107  */
108  public function run(Request $request) {
109  // process the requested action
110  $response = ObjectFactory::getInstance('actionMapper')->processAction($request);
111  return $response;
112  }
113 
114  /**
115  * Default exception handling method. Rolls back the transaction and
116  * executes 'failure' action.
117  * @param $exception The Exception instance
118  * @param $request The Request instance
119  */
120  public function handleException(\Exception $exception, Request $request=null) {
121  self::$_logger->error($exception->getMessage()."\n".$exception->getTraceAsString());
122 
123  // rollback current transaction
124  if (ObjectFactory::getInstance('configuration') != null) {
125  $persistenceFacade = ObjectFactory::getInstance('persistenceFacade');
126  $persistenceFacade->getTransaction()->rollback();
127 
128  // redirect to failure action
129  if ($request == null) {
130  $request = $this->_initialRequest;
131  }
132  $request->addError(ApplicationError::fromException($exception));
133  $request->setAction('failure');
134  ObjectFactory::getInstance('actionMapper')->processAction($request);
135  }
136  else {
137  throw $exception;
138  }
139  }
140 
141  /**
142  * This method is run as ob_start callback
143  * @note must be public
144  * @param $buffer The content to be returned to the client
145  * @return String
146  */
147  public function outputHandler($buffer) {
148  // log last error
149  $error = error_get_last();
150  if ($error !== NULL) {
151  $info = "Error: ".$error['message']." in ".$error['file']." on line ".$error['line'];
152  self::$_logger->error($info);
153 
154  // suppress error message in browser
155  if (!$this->_debug) {
156  header('HTTP/1.1 500 Internal Server Error');
157  $buffer = '';
158  }
159  }
160  return trim($buffer);
161  }
162 }
163 ?>
initialize($defaultController='', $defaultContext='', $defaultAction='login')
Initialize the request.
Definition: Application.php:71
Application is the main application class, that does all the initialization.
Definition: Application.php:23
Presentation related interfaces and classes.
Definition: namespaces.php:59
static getLogger($name)
Get the logger with the given name.
Definition: LogManager.php:35
static getInstance($name, $dynamicConfiguration=array())
Request holds the request values that are used as input to Controller instances.
Definition: Request.php:20
static fromException(\Exception $ex)
Factory method for transforming an exception into an ApplicationError instance.
ErrorHandler catches all php errors and transforms fatal errors into ErrorExceptions and non-fatal in...
handleException(\Exception $exception, Request $request=null)
Default exception handling method.
outputHandler($buffer)
This method is run as ob_start callback.
run(Request $request)
Run the application with the given request.