/
Application.php
259 lines (218 loc) · 7.8 KB
/
Application.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
<?php
declare(strict_types=1);
namespace YapepBase;
use YapepBase\Controller\Exception\Exception as ControllerException;
use YapepBase\Controller\IController;
use YapepBase\DependencyInjection\Container;
use YapepBase\DependencyInjection\IContainer;
use YapepBase\Event\Entity\Event;
use YapepBase\Exception\Exception;
use YapepBase\Exception\HttpException;
use YapepBase\Exception\RedirectException;
use YapepBase\Exception\RouterException;
use YapepBase\Request\Request;
use YapepBase\Router\Entity\ControllerAction;
/**
* Singleton class responsible to "hold" the application together by managing the dispatch process.
*/
class Application
{
/** @var static */
protected static $instance;
/** @var Container||null */
protected $diContainer;
/** @var string */
protected $errorControllerName;
/**
* Singleton constructor
*/
protected function __construct()
{
}
/**
* Singleton __clone() method
*/
protected function __clone()
{
}
/**
* Singleton getter
*/
public static function getInstance(): self
{
if (is_null(static::$instance)) {
static::$instance = new static();
}
return static::$instance;
}
/**
* Sets the application instance.
*
* Be careful with this method, since it breaks the Singleton pattern.
*/
public static function setInstance(self $instance): void
{
static::$instance = $instance;
}
/**
* Sets the DI container to be used by the application
*/
public function setDiContainer(IContainer $diContainer): void
{
$this->diContainer = $diContainer;
}
/**
* Returns the DI container used by the application
*/
public function getDiContainer(): IContainer
{
if (empty($this->diContainer)) {
throw new Exception('You need to set a configured DI Container to be able to use the Application');
}
return $this->diContainer;
}
/**
* Sets the name of the Error controller to use.
*/
public function setErrorController(string $errorControllerName): void
{
$this->errorControllerName = $errorControllerName;
}
/**
* Runs the request on the application
*/
public function run(): void
{
if (empty($this->errorControllerName)) {
throw new Exception('Please set the error controller first');
}
$eventHandlerRegistry = $this->diContainer->getEventHandlerRegistry();
try {
$eventHandlerRegistry->raise(new Event(Event::APPLICATION_STARTED));
$controllerAction = null;
try {
$request = $this->diContainer->getRequest();
$controllerAction = $this->diContainer->getRouter()->getControllerActionByRequest($request);
} catch (RouterException $exception) {
if ($exception->getCode() == RouterException::ERR_NO_ROUTE_FOUND) {
// The route was not found, generate a 404 HttpException
throw new HttpException('Route not found', 404);
} else {
// This was not a no route found error, re-throw the exception
throw $exception;
}
}
$this->runAction($controllerAction);
$this->sendResponse();
} catch (HttpException $exception) {
$this->runErrorAction($exception->getCode());
} catch (RedirectException $exception) {
$this->sendResponse();
} catch (\Exception $exception) {
$this->handleFatalException($exception);
}
$this->raiseRequiredEventsIfNotRaisedYet();
$eventHandlerRegistry->raise(new Event(Event::APPLICATION_FINISHED));
}
/**
* Runs the given Action on the given Controller
*
* @throws ControllerException
* @throws Exception
* @throws RedirectException
*/
protected function runAction(?ControllerAction $controllerAction): void
{
$eventHandlerRegistry = $this->diContainer->getEventHandlerRegistry();
$controller = $this->getController($controllerAction->getController());
$eventHandlerRegistry->raise(new Event(Event::APPLICATION_CONTROLLER_BEFORE_RUN));
$controller->run($controllerAction->getAction());
$eventHandlerRegistry->raise(new Event(Event::APPLICATION_CONTROLLER_FINISHED));
}
protected function getController(string $controllerName): IController
{
/** @var IController $controller */
$controller = $this->diContainer->get($controllerName);
$controller->setRequest($this->diContainer->getRequest());
$controller->setResponse($this->diContainer->getResponse());
return $controller;
}
protected function raiseRequiredEventsIfNotRaisedYet(): void
{
$requiredEventTypes = [
Event::APPLICATION_STARTED,
Event::APPLICATION_CONTROLLER_BEFORE_RUN,
Event::APPLICATION_CONTROLLER_FINISHED,
Event::APPLICATION_OUTPUT_BEFORE_SEND,
Event::APPLICATION_OUTPUT_SENT,
];
foreach ($requiredEventTypes as $eventType) {
$this->raiseEventIfNotRaisedYet($eventType);
}
}
protected function sendResponse()
{
$response = $this->diContainer->getResponse();
$eventHandlerRegistry = $this->diContainer->getEventHandlerRegistry();
$response->render();
$eventHandlerRegistry->raise(new Event(Event::APPLICATION_OUTPUT_BEFORE_SEND));
$response->send();
$eventHandlerRegistry->raise(new Event(Event::APPLICATION_OUTPUT_SENT));
}
/**
* @throws \Exception Re-throws the received exception for the exception handler to handle.
*/
protected function handleFatalException(\Exception $exception): void
{
if ($this->diContainer->getRequest() instanceof Request) {
$this->diContainer->getErrorHandlerRegistry()->handleException($exception);
// We have an HTTP request, try to run
try {
$this->runErrorAction(500);
} catch (\Exception $exception) {
$this->outputError();
}
} else {
// Not an HTTP request, just use default error output
$this->outputError();
}
}
/**
* Runs the error controller action for the specified HTTP error code.
*/
protected function runErrorAction(int $errorCode): void
{
/** @var IController $controller */
$controller = $this->getController($this->errorControllerName);
$this->raiseEventIfNotRaisedYet(Event::APPLICATION_CONTROLLER_BEFORE_RUN);
$controller->run((string)$errorCode);
$this->raiseEventIfNotRaisedYet(Event::APPLICATION_CONTROLLER_FINISHED);
$response = $this->diContainer->getResponse();
$response->render();
$this->raiseEventIfNotRaisedYet(Event::APPLICATION_OUTPUT_BEFORE_SEND);
$response->send();
$this->raiseEventIfNotRaisedYet(Event::APPLICATION_OUTPUT_SENT);
}
/**
* Raises an event if an event with it's type was not yet raised.
*/
protected function raiseEventIfNotRaisedYet(string $eventType): void
{
$eventHandlerRegistry = $this->diContainer->getEventHandlerRegistry();
if (!$eventHandlerRegistry->isRaised($eventType)) {
$eventHandlerRegistry->raise(new Event($eventType));
}
}
/**
* Sends an error to the output.
*/
private function outputError(): void
{
try {
$this->diContainer->getResponse()->sendError();
} catch (\Exception $exception) {
error_log('Uncaught exception during error shutdown: ' . $exception->getMessage());
exit;
}
}
}